MATLAB: Matlab coding help – for/while construct

codingprogramming

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.

Best Answer

I would do it a bit differently:
Ltrs = {'A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W' 'X' 'Y' 'Z' '0' '1' '2' '3' '4' '5' '6' '7' '8' '9' '/'};
IMC = {'.-' '-...' '-.-.' '-..' '.' '..-.' '--.' '....' '..' '.---' '-.-' '.-..' '--' '-.' '---' '.--.' '--.-' '.-.' '...' '-' '..-' '...-' '.--' '-..-' '-.--' '--..' '-----' '.----' '..---' '...--' '....-' '.....' '-....' '--...' '---..' '----.' '-..-.'};
Message = {'P' 'R' 'O' 'G' 'R' 'A' 'M' 'M' 'I' 'N' 'G' '/' 'N' '0' 'K' 'F'};
for k1 = 1:length(Message)
Lgv = cellfun(@(x)ismember(Ltrs, x), Message(k1), 'Uni',0);
Loc = find(Lgv{:});
Morse{k1} = IMC{Loc};
end
Morse
This could likely be made more efficient, but it works.
73 DE N0KF