1 / 48

LOOPS

LOOPS. INGE3016 Algorithms and Computer Programming with MATLAB Dr. Marco A. Arocha Sep 30th, 2013. Loops. Programming structure that allows to execute a sequence of statements more than once. false. cond?. true. statements. exit. Loops. Two basic syntax forms:.

chacha
Download Presentation

LOOPS

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. LOOPS INGE3016 Algorithms and Computer Programming with MATLAB Dr. Marco A. Arocha Sep 30th, 2013

  2. Loops Programming structure that allows to execute a sequence of statements more than once false cond? true statements exit

  3. Loops Two basic syntax forms: for cv=[list of values] end while condition end statements statements cv=control variable or index variable

  4. for & while (on when to use them) • for is used when the number of passes (or iterations or cycles) is known ahead of time • while is used if the looping process must terminate when a specified condition is not longer satisfied (i.e., becomes false), and thus the number of passes could be unknown ahead of time

  5. for Loop Syntax: for cv= a:h:b statements end Syntax: for cv= a:b statements end cv=loop control variable a= initial value of cv h= increment, if omitted defaults to 1 b=final value of cv

  6. ExampleConstruct a Table of Values fprintf(‘ x y \n’); % Table Title for x=0:3:30 y=x^2; fprintf( ‘ %f % f \n ’, x, y); end

  7. Examples Computes de values of x for an Integration Rule using control logic & loops for ii=1:1:n+1 if ii==1 x(ii)=a; else x(ii)=x(ii-1)+h end end x(1)=a for ii=2:1:n+1 x(ii)=x(ii-1)+h end Both examples assume that a, b, n and h has been previously defined or computed

  8. Quiz (1) To understand the mechanism of the for loop, write statements that give as output: 5 4 3 2 1 (2) Write a for loop in which the statements are never executed (3) Write an infinite loop

  9. Rules and recommendations when using for loops with the loop-variable expression ii=a:h:b • The step value h may be negative. For example, ii = 10:-2:4 produces ii =10, 8, 6, 4 • If h is omitted, the step value defaults to one • If h is positive, the loop will not be executed if a>b • If h is negative, the loop will not be executed if a<b • If a=b the loop will be executed only once • If the step value h is not an integer, round-off errors can cause the loop to execute a different number of passes than intended • Should not alter the value of the loop control variable ii within the statements. Doing so can cause unpredictable results • Do not use i and j as loop variables, earlier versions of MATLAB uses these symbols for the imaginary unit sqrt(-1). A better suggestion is to use ii for rows and jj for columns, just to help your memory.

  10. Combine if & for clc; clear; for counter=1:1:30 ng=input('Enter ng \n'); if ng>=90 fprintf('student got A‘); elseif ng>=80 fprintf('student got B'); elseif ng>=70 fprintf('student got C'); elseif ng>=60 fprintf('student got D'); else fprintf('student got F'); end end Example Grade a section with 30 students

  11. while loop • Syntax: while condition statements end • Repeats a series of statements, over and over, as long as the condition is true • The loop stops when the condition becomes false • The condition is just a logical expression

  12. Example-1 x=0; while x<=20 y=x^3; x=x+1; end • One statement modifying the condition must exist (e.g., x=x+1) How many iterations? Final value of x?

  13. Original: x=0; while x<=20 y=x^3; x=x+1; end Omitted: x=0; while x<=20 y=x^3; end What happens if we omit x=x+1;?

  14. Example-2 x=21; while x>=20 y = x^3; x = x+1; end How many iterations?

  15. Example-3 x=0; while x<=20 y=x^3 ; x=x-1; end How many iterations?

  16. Example-4 x=0; while x>=20 y=x^3; x=x+1; end % Cond. is false since the beginning % Loop is never executed

  17. Example-5 x=5; while x<25 disp(x) % write values columnwise x=2*x-1; end The execution of the above produces as output: >> 5 9 17 disp function is a line-oriented, each time produces a new line of output

  18. Remarks • If the condition is false before the while statement is executed, the loop is never executed. • The statements within the while loop must modify the variable controlling the loop, i.e., the condition must change from true to false to stop and exit the loop. Caution must be taken to avoid infinite loops. • IMPORTANT: If you realize your program execution fell into an infinite loop click the <control> and <c> keys simultaneously to stop execution. This action will abort your program execution and allow you to go back to the edition phase. During a problem like this do not try to close MATLAB.

  19. Counter A variable with the function of counting the number of times a given task is executed can be developed. The following program has several counters. These variables count the number of A-, B-, C-, etc. -letter grades in a given student group:

  20. Counter Variable N = 30 % the class group has 30 students countA= 0; countB= 0; countC=0; countD=0; countF=0; for k =1:1:N ng=input(‘Enter ng \n’); if ng>=90 countA=countA + 1; elseif ng>=80 countB=countB + 1; elseif ng>=70 countC=countC + 1; elseif ng>=60 countD=countD + 1; else countF=countF + 1; end end fprintf(‘Students got A=%d, B=%d, C=%d ‘, countA, countB, countC); fprintf(‘Students got D=%d, F=%d ‘, countD, countF);

  21. Counter, General Concept A variable with the function of counting the number of times a given task is executed : counter = counter ± value • Value is added o substracted to the original value of counter to obtain a new value of counter Original value Usually constant New value same variable name

  22. Counter, General Concept counter = counter ± value Examples: • c = c + 1 % counts one by one • c = c + 3 % counts three by three • c = c – 1 % counts backwards

  23. Accumulator A variable with the objective of accumulating the addition of several values can be created as: accumulator = accumulator + value original new same variable name Usually variable

  24. Example Write a small program to accumulate the values of the following elements of x: x=[1,3,5,7,9,11,13,15,17,19] 10 elements

  25. Solution-1 x= [ 1,3,5,7,9,11,13,15,17,19 ]; suma=0; length(x) for i=1:1:10 suma = suma +x( i ); end fprintf(‘Suma= %f \n’, suma);

  26. Solution-2 counter =1; x = 1; suma = 0; while counter <=10 suma = suma + x; x = x +2; counter = counter +1; end fprintf(‘The sum is %d’, suma); x is the values generator, suma is the accumulator, counter counts the iterations

  27. Solution-3 x = 1; suma = 0; while x <=19 suma = suma + x; x = x +2; end fprintf(‘The sum is %d’, suma); x is the values generator but also controls the loop, suma is the accumulator

  28. Solution-4 suma=0; for ii=1:1:10 if ii==1 x(ii)=1; else x(ii)=x(ii-1)+2; end suma=suma+x(ii); end fprintf(‘The sum is %d’, suma); Works only if numbers follow a pattern and you can guess the formula to produce it, e.g., xii=xii-1+2

  29. Solution-5 suma=0; for ii=1:2:19 suma=suma+ii; end suma adds up scalar elements of the control variable ii Classify solutions 1 through 5 as “scalar” or “array” solutions

  30. sum function We may use the MATLAB function sum instead of the accumulator acc. Example: B = sum(A); • Where A is an array, any dimension • sum(A) returns the sum of all the elements of array A. • classic accumulators and/or sum functions must be carefully placed in the program

  31. The sum function within Simpson 1/3 rule: acc=0; for ii=1:1:n+1 if ii==1 | ii==n+1 c(ii)=1; elseif mod(ii,2)==0 c(ii)=4; else c(ii)=2; end t(ii)=c(ii)*f(ii); end acc=sum(t); Note the statement off the loop Note: Assuming f has been previously computed

  32. Compare where to place accumulators classic accumulator sum function for ii=1:1:n+1 if ii==1 | ii==n+1 c(ii)=1; elseif mod(ii,2)==0 c(ii)=4; else c(ii)=2; end t(ii)=c(ii)*f(ii); end acc=sum(t); % Note the acc statement off the loop acc=0; for ii=1:1:n+1 if ii==1 | ii==n+1 c(ii)=1; elseif mod(ii,2)==0 c(ii)=4; else c(ii)=2; end t(ii)=c(ii)*f(ii); acc=acc+t(ii); end

  33. Accumulator, General Concept General expression accumulator = accumulator operator value Operator  +, -, *, \ Value  variable or constant If value is constant, the accumulator and counter share functions

  34. Example: Series ( as an application of accumulators) Write statements to accumulate: suma=0; for ii=1:1:10 suma = suma +ii; end

  35. Quiz Modify previous program to add values from 1 to 10,000

  36. Quiz-1 Write a small program to compute 1+4+9+16+…+100 Hint: Note that the above series is equivalent to: 12+22+32+42…+102

  37. Quiz-2 Write a program to compute: 1*2*3*4*5=5! (factorial of 5) Name the factors generator x Name the accumulator  f

  38. Quiz-3 Do it backwards Write a program to compute: 5*4*3*2*1=5! (factorial of 5)

  39. Quiz Write MATLAB code to accumulate: Ln(1)+Ln(3)+Ln(5)+….+Ln(21)

  40. Controlling the looping In the case of while loops there are two general ways of controlling the number of repetitions: • Using a counter • Using a sentinel

  41. Sentinel Controlled Loop clc, clear; counter=1; total=0; purchase=input('Enter purchase amount, -1 to end \n'); while purchase ~= -1 total = total + purchase; purchase=input('Enter purchase amount, -1 to end \n'); counter = counter + 1; end average purchase = total/(counter-1); fprintf ('The average purchse is %.1f ', average); A female-mall shopper is keeping track of each purchase: The value -1 is the sentinel Run this program

  42. break and continue statements Two statements can be used to interrupt the normal operation of a while and for loop The break statement terminates the execution of a loop and passes control to the next statement after the end of of the loop The continue statement terminates the current pass through the loop and returns control to the top of the loop

  43. clc; clear; for ii=1:1:5 if ii ==3 break; end fprintf('ii= %d \n', ii); end fprintf('End of loop'); Output: ii= 1 ii= 2 End of loop break, example

  44. clc; clear; for ii=1:1:5 if ii ==3 continue; end fprintf('ii= %d \n', ii); end fprintf('End of loop'); ii= 1 ii= 2 ii= 4 ii= 5 End of loop continue, example

  45. Nested Loops • MATLAB statement(s) can go inside the body of structures, such as if, loops, etc. • A for loop can go inside the body of another for loop (nested). • No restrictions for the number of nested loops • For two nested loops, the inner loop executes completely before the outer loop’s next iteration.

  46. clc;clear; for m = 1:1:5 for n = m:1:5 fprintf('%d',n); end fprintf('\n'); end Output: 12345 2345 345 45 5 Nested Loops

  47. clc, clear for m = 1:1:5 for n = 1:1:m fprintf('%d',n); end fprintf('\n'); end Output: 1 12 123 1234 12345 Nested Loops

  48. Nested Loops, example for m = 1:1:5 for n = 1:1:10 A(m, n) = 1/(m + n - 1); end end

More Related