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.')endend
My method is:
- Convert "word" (a string) into its respective numerical array in ASCII.
- Convert the key (one lowercase letter to determine how much to shift by) to its respective ASCII number.
- run a for loop that runs for each element of the numerical array numWord
- 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.
- 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