Matlab coding help - for/while construct
显示 更早的评论
Hello. I am trying to make my morse code encoder program accept strings and allow me to write a whole word. Currently it will only accept single letters/digits and reject anything else. I am extremely confused and can't seem to get it right. Please help. Here is what I could muster up so far:
MC_1='.----'; MC_2='..---'; MC_3='...--';
MC_4='....-'; MC_5='.....'; MC_6='-....';
MC_7='--...'; MC_8='---..'; MC_9='----.';
MC_0='-----'; MC_A='.-'; MC_B='-...';
MC_C='-.-.'; MC_D='-..'; MC_E='.';
MC_F='..-.'; MC_G='--.'; MC_H='....';
MC_I='..'; MC_J='.---'; MC_K='-.-';
MC_L='.-..'; MC_M='--'; MC_N='-.';
MC_O='---'; MC_P='.--.'; MC_Q='--.-';
MC_R='.-.'; MC_S='...'; MC_T='-';
MC_U='..-'; MC_V='...-'; MC_W='.--';
MC_X='-..-'; MC_Y='-.--'; MC_Z='--..';
Word=input('Enter Word to encode here: ','s');
Word=upper(Word);
Valid = 1;
switch(Word)
case '1'
Code=MC_1;
case '2'
Code=MC_2;
case '3'
Code=MC_3;
case '4'
Code=MC_4;
case '5'
Code=MC_5;
case '6'
Code=MC_6;
case '7'
Code=MC_7;
case '8'
Code=MC_8;
case '9'
Code=MC_9;
case '0'
Code=MC_0;
case 'A'
Code=MC_A;
case 'B'
Code=MC_B;
case 'C'
Code=MC_C;
case 'D'
Code=MC_D;
case 'E'
Code=MC_E;
case 'F'
Code=MC_F;
case 'G'
Code=MC_G;
case 'H'
Code=MC_H;
case 'I'
Code=MC_I;
case 'J'
Code=MC_J;
case 'K'
Code=MC_K;
case 'L'
Code=MC_L;
case 'M'
Code=MC_M;
case 'N'
Code=MC_N;
case 'O'
Code=MC_O;
case 'P'
Code=MC_P;
case 'Q'
Code=MC_Q;
case 'R'
Code=MC_R;
case 'S'
Code=MC_S;
case 'T'
Code=MC_T;
case 'U'
Code=MC_U;
case 'V'
Code=MC_V;
case 'W'
Code=MC_W;
case 'X'
Code=MC_X;
case 'Y'
Code=MC_Y;
case 'Z'
Code=MC_Z;
otherwise
Valid =0;
end
if Valid
disp(Code);
else
disp('Error: Invalid Character(s)');
end
I do not want to use MatLab cell arrays (e.g. {'.--.'; '.-.'; '---'; ...}) as I would prefer to just make small revisions and additions to my program.
This is how I want to add to it but not sure how:
for index= ...
% find out the Morse code of the corresponding character in Word.
...
% print out the Morse code
...
end
My goal is for it to look like this in the end:
>> step2
The word to be encoded: Programming
The Morse code is .--. .-. --- --. .-. .- -- -- .. -. --
Thank you so much for any help.
采纳的回答
更多回答(1 个)
Walter Roberson
2015-12-2
0 个投票
Do not switch on Word, switch on Word indexed at a particular character. This would involve a "for" (or while) loop from 1 to the length of the word.
Do not just assign to Code: initialize Code to empty and then for every character, append the new information to the end of Code.
1 个评论
Walter Roberson
2015-12-2
CompleteCode = '';
for K = 1 : 5
switch Word(K)
...
end
CompleteCode = [CompleteCode, Code];
end
类别
在 帮助中心 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!