Matlab coding help - for/while construct
Show older comments
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.
Accepted Answer
More Answers (1)
Walter Roberson
on 2 Dec 2015
0 votes
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 Comment
Walter Roberson
on 2 Dec 2015
CompleteCode = '';
for K = 1 : 5
switch Word(K)
...
end
CompleteCode = [CompleteCode, Code];
end
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!