MATLAB: Trying to make a function for Caesar Encryption — need help.

caesar ciphercaesar encryptionencryptionMATLABmatlab functionmatlab gui

I've got a project which involves designing a GUI that can encrypt a string using Caesar encryption. I've been making this function file to use in the GUI .m file, but I've encountered some problems. I think I've got the method properly, I just can't seem to get it right without any errors.
function output = encCsar(word,key)
numWord = uint8(word);
numKey = uint8(lower(key)) - 96;
for i = 1:numel(numWord)
if ( numWord>=65 & numWord<=90 )
numWord=mod(numWord-65+numKey,26);
output(i,1)=char(numWord+65);
elseif ( numWord>=97 & numWord<=122 )
numWord=mod(numWord-97+numKey,26);
output(i,1)=char(numWord+97);
else
error('Please enter a string and a number key.')
end
end
My method is:
  1. Convert "word" (a string) into its respective numerical array in ASCII.
  2. Convert the key (one lowercase letter to determine how much to shift by) to its respective ASCII number.
  3. run a for loop that runs for each element of the numerical array numWord
  4. Apply the Caesar encryption formula (num value of the letter + num value of the key) in mod 26, and I had it run for both uppercase and lowercase letters just in case the string isn't completely lowercase or uppercase.
  5. It then outputs each encrypted element as a new array, and it converts it back to characters.
That's what it's supposed to do in theory, but I've gotten the error I set up ('Please enter a string and a number key.') in case it fails each time. If I try commenting out the else part, the function just doesn't do anything. How should I go about fixing this? Any answers or help would be appreciated.

Best Answer

I assume, that word is a string or char vector. Then
numWord = uint8(word);
converts it to a vector of type uint8. Now
for i = 1:numel(numWord)
starts a loop over all elements of this vector. But
if ( numWord>=65 & numWord<=90 )
uses the complete vector in the condition. If Matlab's if gets an array as condition, if performs this implicitly:
if all(X(:)) && ~isempty(X)
Most likely you want to use the loop index i:
if numWord(i) >= 65 & numWord(i) <= 90
% ^^^ ^^^
By the way, it is easier to operate on the characters directly:
for i = 1:numel(word)
if word(i) >= 'a' && word(i) < 'z'
output(i) = char(65 + mod(word(i) - 65 + numKey, 26));
...