Combining Loops and Logic Chapter 4 MATLAB Programming Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Combining Loops and Logic • Complex programs usually contain a both loops and logical statements to control the sequence of calculations • As an example, let’s consider this example: We want to create an identity matrix (a square array with all ones as diagonal elements, zeros as offdiagonal elements) for a given size. For size = 3, our matrix would be: 1 0 0 0 1 0 0 0 1 Engineering Computation: An Introduction Using MATLAB and Excel Example • There is a built-in MATLAB command “eye” that creates an identity matrix, but we will ignore that for this example • We will call the matrix A, so we need to define each element A(m,n) where m and n both range from 1 to the specified size • This will require two nested for loops • For each element, a conditional statement is required: if m = n, then A(m,n) = 1, else A(m,n) = 0 Engineering Computation: An Introduction Using MATLAB and Excel Example • Can you de-scramble these lines of code to create an identity matrix and print it to the screen? A(m,n) = 0; for m = 1:Size end Size = 10; A A(m,n) = 1; else end if m == n end for n = 1:Size Engineering Computation: An Introduction Using MATLAB and Excel Flow Chart Define Size for m = 1: Size for n = 1: Size m= n ? Yes A(m,n) = 1 No A(m,n) = 0 Output A Engineering Computation: An Introduction Using MATLAB and Excel Solution Size = 10; for m = 1:Size for n = 1: Size if m == n A(m,n) = 1; else A(m,n) = 0; end end end A Engineering Computation: An Introduction Using MATLAB and Excel Example Engineering Computation: An Introduction Using MATLAB and Excel Example • Let’s set the Size to 3 and repeat: • No change! What happened? Engineering Computation: An Introduction Using MATLAB and Excel Example • A was stored as a a 10 X 10 matrix in memory before the m-file was modified • When the new file was executed, the elements of A up to (3,3) were overwritten; the rest were unchanged • Good practice to clear your variables (especially arrays) at the beginning of an m-file: Engineering Computation: An Introduction Using MATLAB and Excel Example • Now it works: Engineering Computation: An Introduction Using MATLAB and Excel Example (Example 4.2) • In many textbook problems, a 3-4-5 triangle is encountered: 5 3 θ 4 • Note that the hypotenuse (5) is a perfect square: an integer that is the square root of another integer (25) • Many calculations are made simple for this configuration: cosθ = 4/5; sinθ = 3/5, etc. Problem Description • Can we find the other perfect squares for integer side lengths x and y from 1 to 25? • h = hypotenuse h y θ x Engineering Computation: An Introduction Using MATLAB and Excel Program Planning • We will need to use two nested loops, since we have two independent variables: x and y • Things to consider: – How will we identify perfect squares mathematically? – Do we want to store the perfect squares that we find, and/or do we want to print them to the screen or a file? – Do we want to count the number of perfect square combinations found? Engineering Computation: An Introduction Using MATLAB and Excel Begin Flow Chart with Loop Statements for x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2) • How do we determine if h is an integer? Consider the MATLAB function floor: >> help floor FLOOR Round towards minus infinity. FLOOR(X) rounds the elements of X to the nearest integers towards minus infinity. Engineering Computation: An Introduction Using MATLAB and Excel Check for Perfect Square • We can compare h and floor(h) directly in an if statement: if h == floor(h) • If this statement is true, then we will print the values of x, y, and h to the screen • If it is false, then we will do nothing Engineering Computation: An Introduction Using MATLAB and Excel m=0 for x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2) Is h an integer? Yes m=m +1 Print x, y, h No Print m Engineering Computation: An Introduction Using MATLAB and Excel MATLAB Code for x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2); • What type of conditional statement do we need? • if • if-else • if-elseif Engineering Computation: An Introduction Using MATLAB and Excel MATLAB Code • A simple if statement works here – we either do the next steps or we skip them for x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2); if h == floor(h) x y h end Engineering Computation: An Introduction Using MATLAB and Excel MATLAB Code • Close both loops with end statements for x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2); if h == floor(h) x y h end end end Engineering Computation: An Introduction Using MATLAB and Excel Results • Save file as “PerSquares” and run: >> PerSquares x = 3 y = 4 h = 5 x = 4 y = 3 h = 5 (Screen output continues for many lines) Engineering Computation: An Introduction Using MATLAB and Excel Add Formatting to Output for x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2); if h == floor(h) fprintf('%10i %10i %10i\n',x,y,h) end end end More about the fprintf command later Engineering Computation: An Introduction Using MATLAB and Excel Results >> PerSquares 3 4 5 6 7 8 8 9 10 12 12 12 15 15 16 18 20 20 21 24 24 24 >> 4 3 12 8 24 6 15 12 24 5 9 16 8 20 12 24 15 21 20 7 10 18 5 5 13 10 25 10 17 15 26 13 15 20 17 25 20 30 25 29 29 25 26 30 • How would we add a counter to report the number of combinations found? • How do we eliminate duplicates? (such as 3, 4, 5; 4, 3, 5) Engineering Computation: An Introduction Using MATLAB and Excel Counter Added m = 0; for x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2); if h == floor(h) fprintf('%10i %10i %10i\n',x,y,h) m = m + 1; end end end fprintf('\n Combinations found = %i\n',m) Engineering Computation: An Introduction Using MATLAB and Excel Eliminating Duplicates • The first time though the x-loop, x = 1 and y = 1:25: x=1 y = 1,2,3,4….25 • The second time though the x-loop, x = 2 and y = 1:25: x=2 y = 1,2,3,4….25 • But since we have already looked at the combination x = 1, y = 2, we do not want to look at x = 2, y = 1 Engineering Computation: An Introduction Using MATLAB and Excel Eliminating Duplicates • If we start the y-loop at 2 when x = 2: x=2 y = 2,3,4,5….25 • And start the y-loop at 3 when x = 3: x=3 y = 3,4,5,6….25 • And similar for the other values of x, then we have eliminated duplicate combinations Engineering Computation: An Introduction Using MATLAB and Excel y-Loop Adjusted m = 0; for x = 1:25 for y = x:25 h = sqrt(x^2 + y^2); if h == floor(h) fprintf('%10i %10i %10i\n',x,y,h) m = m + 1; end end end fprintf('\n Combinations found = %i\n',m) Engineering Computation: An Introduction Using MATLAB and Excel Results >> PerSquares 3 5 6 7 8 9 10 12 15 18 20 4 12 8 24 15 12 24 16 20 24 21 Combinations found = 11 >> 5 13 10 25 17 15 26 20 25 30 29 • For you to think about: • How would we eliminate combinations that are multiples of other combinations? (Example: 6, 8, 10 is a multiple of 3, 4, 5 – forms a similar triangle) Engineering Computation: An Introduction Using MATLAB and Excel The fprintf Command • This command writes formatted output to the screen • The format of the command is: fprintf(fid, ’Text to be written, including conversion specifications for any variables to be printed’, variables) • The file ID (fid) is omitted for output to the screen • Conversion specifications are instructions for how the variables are to be formatted, inserted at the points where the variables are to be written Engineering Computation: An Introduction Using MATLAB and Excel Conversion Specifications • Conversion specifications begin with a % symbol • Next comes the number of digits and decimal places • Last is designator of format type. Most common are: • f = fixed number of decimal places • E or e = exponential notation • i = integer Engineering Computation: An Introduction Using MATLAB and Excel Examples • >> fprintf('Pi = %8.3f',pi) Pi = 3.142 Text to be written to the screen, including the conversion specification for the variable (pi) pi is output over 8 spaces, including 3 decimal places Engineering Computation: An Introduction Using MATLAB and Excel Examples • >> fprintf('Pi = %e',pi) Pi = 3.141593e+000 Note that the number of digits and the number of decimal places are optional pi is output in exponential notation, with the number of digits corresponding to the default “short” format Engineering Computation: An Introduction Using MATLAB and Excel Examples • >> fprintf('\nPi = %.4f\n',pi) Pi = 3.1416 >> The characters \n within the output string start a new line pi is output to 4 decimal places Engineering Computation: An Introduction Using MATLAB and Excel Examples • >> m = 12; >> fprintf('\n\nThe value of m is %i\n\n',m) The value of m is 12 >> m is output as an integer Engineering Computation: An Introduction Using MATLAB and Excel Writing to a File • Before writing to a file, you must first open a file and assign it to “fid” (file ID): • Example: fid = fopen('amtable','wt'); • 'wt' indicates write access; text file format. If the file does not exist, it will be created. If it already exists, its contents will be overwritten • 'at' instead of 'wt' indicates that an existing file will be appended – the new results will be added to the end of an existing file Engineering Computation: An Introduction Using MATLAB and Excel Modifications to “PerSquares” File: New file “output.txt” m = 0; opened for write access fid = fopen('output.txt','wt'); fprintf(fid,' x y h\n'); fprintf(fid,' === === ===\n'); for x = 1:25 Column headers for y = x:25 written to file h = sqrt(x^2 + y^2); if h == floor(h) fprintf(fid,'%5i %5i %5i\n',x,y,h); m = m + 1; Integer triangles end written to file end end fprintf('\n Combinations found = %i\n',m) Number of triangles found written to screen Engineering Computation: An Introduction Using MATLAB and Excel Output • The table is now printed to the file “output,” which can be opened in Word or Notepad, or imported into Excel Engineering Computation: An Introduction Using MATLAB and Excel