Using For loop to convert a message. Help pls.

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.

 Akzeptierte Antwort

sixwwwwww
sixwwwwww am 12 Okt. 2013

0 Stimmen

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)

2 Kommentare

Michael
Michael am 12 Okt. 2013
I can't thank you enough!
sixwwwwww
sixwwwwww am 12 Okt. 2013
why something wrong?

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Image Analyst
Image Analyst am 12 Okt. 2013

0 Stimmen

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

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by