Control Structures: An Example
In this lesson, we're going to build a piece of code that uses three kinds of loops to do a simple task: read in keyboard input until the user types a particular phrase (!!!).
You will need to open a new script and copy the following into it:
endnow=0; %variable will be 1 (true) when we need to end the loop while ~endnow %do this while endnow is false instr=input('Enter text now. Type !!! to end:\n','s'); %gets input back as string instr=strtrim(instr); %remove leading and trailing white space if strcmp(instr,'!!!') %did the user enter the magic quit code break %if so, exit while loop immediately end %now we parse instr to get the first word: %our strategy will be to look for a space strlen=length(instr); %length of string firstspace=0; %initialize position of first space in instr for ind=1:strlen if (instr(ind)==' '); %if first element is a space firstspace=ind; break %kicks us out of for loop prematurely end end if firstspace %if the location of the first space is nonzero firstword=instr(1:(firstspace-1)); %pull out everything leading up to it: that's the first word else firstword=instr; %else, first word is whole word end %now, we will output a keyword based on the last letter of the first % word, but only if it's a vowel lastletter=firstword(end); switch lastletter case 'a' disp('aardvark!') case 'e' disp('egret!') case 'i' disp('iguana!') case 'o' disp('ocelot!') case 'u' disp('ungulate!') case 'y' disp('yak!') otherwise disp(['Your word was ' firstword '. FAIL']) end end