# Chapter 4 MATLAB Programming Combining Loops and Logic Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

## Presentation on theme: "Chapter 4 MATLAB Programming Combining Loops and Logic Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display."— Presentation transcript:

Chapter 4 MATLAB Programming Combining Loops and Logic 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 off- diagonal elements) for a given size. For size = 3, our matrix would be: Engineering Computation: An Introduction Using MATLAB and Excel 1 0 0 0 1 0 0 0 1

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? Engineering Computation: An Introduction Using MATLAB and Excel 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

Flow Chart Engineering Computation: An Introduction Using MATLAB and Excel

Solution Engineering Computation: An Introduction Using MATLAB and Excel Size = 10; for m = 1:Size for n = 1: Size if m == n A(m,n) = 1; else A(m,n) = 0; end A

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: 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. θ 3 4 5

Problem Description Can we find the other perfect squares for integer side lengths x and y from 1 to 25? h = hypotenuse Engineering Computation: An Introduction Using MATLAB and Excel θ y x h

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 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 for x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2)

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

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 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 More about the fprintf command later Engineering Computation: An Introduction Using MATLAB and Excel

Results >> PerSquares 3 4 5 4 3 5 5 12 13 6 8 10 7 24 25 8 6 10 8 15 17 9 12 15 10 24 26 12 5 13 12 9 15 12 16 20 15 8 17 15 20 25 16 12 20 18 24 30 20 15 25 20 21 29 21 20 29 24 7 25 24 10 26 24 18 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 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 fprintf('\n Combinations found = %i\n',m) Engineering Computation: An Introduction Using MATLAB and Excel

Results >> PerSquares 3 4 5 5 12 13 6 8 10 7 24 25 8 15 17 9 12 15 10 24 26 12 16 20 15 20 25 18 24 30 20 21 29 Combinations found = 11 >> 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 Engineering Computation: An Introduction Using MATLAB and Excel 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

Examples >> fprintf('Pi = %e',pi) Pi = 3.141593e+000 Engineering Computation: An Introduction Using MATLAB and Excel 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

Examples >> fprintf('\nPi = %.4f\n',pi) Pi = 3.1416 >> Engineering Computation: An Introduction Using MATLAB and Excel The characters \n within the output string start a new line pi is output to 4 decimal places

Examples >> m = 12; >> fprintf('\n\nThe value of m is %i\n\n',m) The value of m is 12 >> Engineering Computation: An Introduction Using MATLAB and Excel m is output as an integer

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: m = 0; fid = fopen('output.txt','wt'); fprintf(fid,' x y h\n'); fprintf(fid,' === === ===\n'); for x = 1:25 for y = x:25 h = sqrt(x^2 + y^2); if h == floor(h) fprintf(fid,'%5i %5i %5i\n',x,y,h); m = m + 1; end fprintf('\n Combinations found = %i\n',m) Engineering Computation: An Introduction Using MATLAB and Excel New file “output.txt” opened for write access Column headers written to file Integer triangles written to file Number of triangles found written to screen

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

Similar presentations