Write a Matlab function called swap code m that takes a stri

Write a Matlab function called swap code. m that takes a string msg as input and returns another string coded as output. The function encodes the string by reversing the alphabet: it replaces each \'a\' with \'z\', each \'b\' with \'y\', each \'c\' with \'at\', etc. The function must work for uppercase letters the same way. but it must not change any other characters. Note that if you call the function twice like this txtout = swapcode(swapcode(txtin)) then the string stored in txtout will be identical to the string stored in txtin. The specifications for the function and some sample function calls are shown below. input parameter msg a string output parameter coded a string sample function calls swapcode(\'This is a sentence.\') produces the string \'Gsrh rh z hvmgvmxv.\' Swapcode(\'Who has a 3-legged dog?\') produces the string \'Dsl szh z 3-ovttvw wlt? Swapcode(swapcode(\'Dave97\')) produces the string \'Dave97\'

Solution

Here is the code for you:

function coded = swapcode(msg)

coded = \'\';

upperCase = [\'A\' \'B\' \'C\' \'D\' \'E\' \'F\' \'G\' \'H\' \'I\' \'J\' \'K\' \'L\' \'M\' \'N\' \'O\' \'P\' \'Q\' \'R\' \'S\' \'T\' \'U\' \'V\' \'W\' \'X\' \'Y\' \'Z\'];

lowerCase = [\'a\' \'b\' \'c\' \'d\' \'e\' \'f\' \'g\' \'h\' \'i\' \'j\' \'k\' \'l\' \'m\' \'n\' \'o\' \'p\' \'q\' \'r\' \'s\' \'t\' \'u\' \'v\' \'w\' \'x\' \'y\' \'z\'];

for i = 1 : length(msg)

if(isletter(msg(i)))

if(ismember(msg(i), upperCase))

temp = fliplr(upperCase);

pos = find(upperCase==msg(i));

coded = strcat(coded, temp(pos));

else if(ismember(msg(i), lowerCase))

temp = fliplr(lowerCase);

pos = find(lowerCase==msg(i));

coded = strcat(coded, temp(pos));

else

coded = strcat(coded, msg(i));

end

end

else

coded = strcat(coded, msg(i));

end

  

end

end

 Write a Matlab function called swap code. m that takes a string msg as input and returns another string coded as output. The function encodes the string by rev

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site