Can this be improved? Rot13 Encode & Decode

2 次查看(过去 30 天)
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

回答(1 个)

Sid Singh
Sid Singh 2019-10-21
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.

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by