MATLAB While Loops ENGR 1181 Presentation by Annie Abell
Today’s Topics • Reminders about while loops • Useful functions for while loops • Examples of simple and complex while loops
Reminders About While Loops • While loops must have a conditional expression, and the conditional expression must have at least one variable. • Conditional variables must be "initialized" before the loop. • The conditional variable must advance with each pass. (Otherwise the loop will continue indefinitely!) • "Ctrl + C" will terminate execution of an indefinite loop.
Function: rem() This function checks for a remainder when dividing x by y. rem(x,y) Ex: rem(x,3)will check if the value of xis divisible by 3.
Function: tic/toc • tic and toc are timing functions that monitor elapsed time in your program • tic starts a stopwatch that runs in the background • toc returns the elapsed time since the tic command • The value of toc can be assigned to a variable
Example: Simple While Loop Note: • conditional variable is initialized • variable advances each time • one end corresponds to if • one end corresponds to while a=0 while a<10 a=a+1if (a==5) continueenddisp(a)end 1234678910
Example: Complex While Loop Task Steps Initialize variables: sq & # Loop while sq < 3325 Advance # by 3 in each pass Check if # is divisible by 5 If yes, square the # Repeat loop until sq >3325. Loop stops & # value will give us the smallest integer to meet conditions Write a program that will use a while loop to find the smallest number divisible by both 3 and 5, with the square of the number greater than 3325.
Example: Complex While Loops n=0; sq=0; %initialize variables: # & square whilesq<=3325 %loop until square >3325n=n+3 %advance # by 3 each pass if rem(n,5)==0 %check if # is divisible by 5sq=n^2; %if yes, square #end %end if statementend %end while loop disp(n) %display the # that meets criteria
Tic/Toc Example N=input('\nPlease enter a large value for N: '); ticfori=1:N sqroot= sqrt(i);end SqrtTime=toc; fprintf('\n\nIt took MATLAB %f seconds to calculate %i square roots\n', SqrtTime, N) %obtain value for N %start stopwatch%loop to calculate all of the square roots %obtain elapsed time %statement reporting how long it took to calculate the sq roots