Using For loop to convert a message. Help pls.

4 views (last 30 days)
I'm trying to convert a string from alphabetical characters to numbers
for example: The message I want to convert is "abc" and so the code should read "123" if i set a=1 b=2 c=3
I must do this while using for loops but don't know how to do it. This is how I thought it would work:
message=('abc');
for i=1:1:length(message)
if message(i)=a
code(1)=1
elseif message(i)=b
code(2)=2
elseif message(i)=c
code(3)=3
end
end
disp(code)
In case you haven't figured it out yet I'm new to Mat lab and am very confused by loops.

Accepted Answer

sixwwwwww
sixwwwwww on 12 Oct 2013
Dear Micheal, here is the code:
message='abc';
for i=1:1:length(message)
if message(i)=='a'
code(1)='1';
elseif message(i)=='b'
code(2)='2';
elseif message(i)=='c'
code(3)='3';
end
end
disp(code)

More Answers (1)

Image Analyst
Image Analyst on 12 Oct 2013
Here's one way that's somewhat flexible, in that you can change the input letters and output numerical digits to almost whatever you want (as long as the numbers are only 1 digit and not 2 - in other words, 'a' maps to 0-9 and doesn't map to 375 or something.)
s='abc'
% Define the mapping of alphabet to numbers.
dictionary = [1,2,3] + '0';
% Create an output matrix where each element
% comes from the translation dictionary.
for index = 1 : length(s)
outIndex = s(index) - 'a' + 1;
s_out(index) = char(dictionary(outIndex));
end
% Print the output string to the command window.
s_out

Categories

Find more on Encryption / Cryptography in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!