MATLAB: Basic Shift Cipher Decryption Algorithm HELP!

algorithm

Hello guys, I'm using matlab to make a function that basically decrypts a shift cipher by taking in the ciphertext string and key integer as parameters and returning the plaintext.
here is the code..
function [ plainText ] = ccdt( c, k )
s = double(c);
for i = 1:numel(s)
s(i) = s(i)-k;
end
plainText = char(s);
return
end
This works fine when the letters don't necessarily need to loop back around to the beginning of the alphabet. For example, if I decrypt the letter 'b' with key = 3, it should give me back 'y', but it's just returning whatever ascii code for 'b' minus 3 which isn't 'y'.
How can I fix this problem? also, how can i modify the code so that lower/ upper case letters don't really matter?
Thanks for your time!

Best Answer

Use mode or reminder to loop over certain range of numbers. Something like this:
% A --> 65
% Z --> 90
% a --> 97
% z --> 122
shift=-3;
inputChar=char( [ (65:90)'; (97:122)'] );
for i=1:numel(inputChar)
numericChar=double(inputChar(i));
if ( numericChar>=65 && numericChar<=90 )
numericChar=mod(numericChar-65+shift,26);
outputChar(i,1)=char(numericChar+65);
elseif ( numericChar>=97 && numericChar<=122 )
numericChar=mod(numericChar-97+shift,26);
outputChar(i,1)=char(numericChar+97);
else
error('just alphabetic chars are accepted')
end
end
You can use both negative shift or positive shift, depending on the direction.