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.

 採用された回答

sixwwwwww
sixwwwwww 2013 年 10 月 12 日

0 投票

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 件のコメント

Michael
Michael 2013 年 10 月 12 日
I can't thank you enough!
sixwwwwww
sixwwwwww 2013 年 10 月 12 日
why something wrong?

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2013 年 10 月 12 日

0 投票

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

カテゴリ

ヘルプ センター および File ExchangeLanguage Support についてさらに検索

質問済み:

2013 年 10 月 12 日

回答済み:

2013 年 10 月 12 日

Community Treasure Hunt

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

Start Hunting!

Translated by