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 Exchange에서 Language 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