Can this be improved? Rot13 Encode & Decode

1 view (last 30 days)
Jake Wright
Jake Wright on 17 Oct 2019
Edited: Rik on 21 Oct 2019
Hello,
Im a new student studying computer science and we have recently started learning Matlab. (2-3 Weeks so still very novice!)
I was given a task of creating two scripts to both encode and decode the rot13 cypher. I believe I have completed them but just wanted to see if you guys can spot any
rookie mistakes or any improvements you would make? Thanks for any help!
Encode :
function [ciphermessage] = rot13_encode(plainmessage)
ciphermessage = plainmessage + 13;
for i=1:length(ciphermessage)
if(ciphermessage(i)>90)
ciphermessage(i) = ciphermessage(i) - 26;
end
end
ciphermessage = char(ciphermessage);
end
Decode:
function [ciphermessage] = rot13_encode(plainmessage)
ciphermessage = plainmessage - 13;
for i=1:length(ciphermessage)
if(ciphermessage(i) < 65)
ciphermessage(i) = ciphermessage(i) + 26;
end
end
ciphermessage = char(ciphermessage);
end

Answers (1)

Sid Singh
Sid Singh on 21 Oct 2019
Hi, you should rename your decoding function, it is very misleading.
Instead of using the for loop, you can use logical indexing to make it more MATLAB like.
idx = ciphermessage>90;
ciphermessage(idx) = ciphermessage(idx) - 26;
Also your code doesn't work for lowercase ASCII. Maybe you can improve it to support this as well.

Categories

Find more on Programming in Help Center and File Exchange

Products


Release

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!