matlab - Output morse code from a file -
my program supposed read text file , output in morse code.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function morse(filename) % morse converts text morse code , writes file % defining characters & numbers = ['.-']; b = ['-...']; c = ['-.-.']; d = ['-..']; e = ['.']; f = ['..-.']; g = ['--.']; h = ['....']; = ['..']; j = ['.---']; k = ['-.-']; l = ['.-..']; m = ['--']; n = ['-.']; o = ['---']; p = ['.--.']; q = ['--.-']; r = ['.-.']; s = ['...']; t = ['-']; u = ['..-']; v = ['...-']; w = ['.--']; x = ['-..-']; y = ['-.--']; z = ['--..']; period = ['.-.-.-']; comma = ['--..--']; question = ['..--..']; slash_ = ['-..-.']; n1 = ['.----']; n2 = ['..---']; n3 = ['...--']; n4 = ['....-']; n5 = ['.....']; n6 = ['-....']; n7 = ['--...']; n8 = ['---..']; n9 = ['----.']; n0 = ['-----']; text = upper(text); vars ={'period','comma','question','slash_'}; morsecode=[]; i=1:length(text) if isvarname(text(i)) morsecode = [morsecode;eval(text(i))]; elseif ismember(text(i),'.,?/') x = findstr(text(i),'.,?/'); morsecode = [morsecode;eval(vars{x})]; elseif ~isempty(str2num(text(i))) morsecode = [morsecode;eval(['n' text(i)])]; elseif text(i)==' ' morsecode = [' ']; end morsecode = [morsecode;eval(text(i))]; end code = morsecode; if exist('file','var') fprintf(code, '%c') end
despite terrible question, is nice project imo , got me thinking: how can text-to-morse conversion in elegant way. lead me inevitably following implementation (to op: take humble piece of code , learn it).
the nicest quirk imo in there one-liner cell2mat , arrayfun (split code on more lines intermediate variable if want debug every step).
text2morsefile.m :
function text2morsefile(txt,filename) fid = fopen(filename,'w'); fprintf(fid,text2morse(txt)); fclose(fid); end function m = text2morse(str) m=cell2mat(arrayfun(@char2morse,str,'uni',false)); end function m = char2morse(ch) persistent morsemap; if isempty(morsemap) morsemap ={' ','-.-.--', '.-..-.', nan, '...-..-', nan, '.-...', '.----.',... '-.--.', '-.--.-', nan, '.-.-.', '--..--', '-....-', '.-.-.-', '-..-.',... '-----', '.----', '..---', '...--', '....-', '.....', '-....', '--...',... '---..', '----.', '---...', '-.-.-.', nan, '-...-', nan, '..--..',... '.--.-.', '.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..',... '.---', '-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.', '...',... '-', '..-', '...-', '.--', '-..-', '-.--', '--..', nan,nan,nan,nan,'..--.-'}; end % specify char non-morse character: missingmorse_symbol = ''; ch = double(upper(ch)); m = nan; if ch>=32 && ch<=95 m = morsemap{ch-31}; end if isnan(m) m = missingmorse_symbol; else % might add space between characters? m = [m ' ']; end end
Comments
Post a Comment