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.
采纳的回答
更多回答(1 个)
Image Analyst
2013-10-12
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 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!