MATLAB: I am writting a code for Vigenere Cipher but i am troubled with a question that how could i repeat key as that of the text to be ciphered

homeworkmatlab codervigenere cipher

my code is given below but error is key length is not same as plain_text
% Matlab code to encipher and Decipher Vigenere Cipher
% input parameter
key = input('Enter the cipher key: ','s' );
plain_text =input('ENter the text to be ciphered: ','s');
length(plain_text)
k=repmat((key),1,length(plain_text))
%k1=k(:)'
%k=repelem(key,length(plain_text))
% Vigenere ciphere Encryption
plain_num=plain_text-97;
k1=k-97;
ciphered_num=rem(plain_num+k1,26);
ciphered_text=char(ciphered_num+97)
% Vigenere ciphere Decryption
ciphered_num=ciphered_text-97;
deciphered_num=rem(ciphered_num-k1,26);
deciphered_text=char(deciphered_num+97)

Best Answer

mahnoor - the problem is with
k=repmat((key),1,length(plain_text))
You don't want to repeat the key for each letter of plain_text (unless the key is a single character) but you want to repeat it enough times so that the "extended" key has the same characters as the plain text. For example, if
key = 'logan';
plainText = 'superheromovies2017';
then the extended key would be
extendedKey = 'loganloganloganloga';
So your code will have to determine this. I suppose you could do something like
extendedKey = '';
if length(key) < length(plainText)
keyReps = floor(length(plainText)/length(key));
extendedKey = [repmat(key,1,keyReps) key(1:rem(length(plainText),length(key)))];
else
extendedKey = key(1:length(plainText));
end
This should give you the correct key, but you may want to step through the remainder of the code to ensure that it is doing what you expect.