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

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

Embed Size (px)

Citation preview

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

Chapter 4MATLAB Programming

Combining Loops and Logic

Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Page 2: 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

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

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

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

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:SizeendSize = 10;AA(m,n) = 1;elseendif m == nendfor n = 1:Size

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

Flow Chart

Engineering Computation: An Introduction Using MATLAB and Excel

No

Yes

Define Size

for m = 1: Size

m = n ?

for n = 1: Size

A(m,n) = 1 A(m,n) = 0

Output A

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

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 endendA

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

Example

Engineering Computation: An Introduction Using MATLAB and Excel

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

Example

• Let’s set the Size to 3 and repeat:

• No change! What happened?

Engineering Computation: An Introduction Using MATLAB and Excel

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

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

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

Example

• Now it works:

Engineering Computation: An Introduction Using MATLAB and Excel

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

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

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

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

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

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

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

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)

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

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

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

Engineering Computation: An Introduction Using MATLAB and Excel

for x = 1:25

Is h an integer?

Print m

No

Yes m = m + 1Print x, y, h

for y = 1:25

h = sqrt(x^2 + y^2)

m = 0

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

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

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

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

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

MATLAB Code

• Close both loops with end statementsfor x = 1:25 for y = 1:25 h = sqrt(x^2 + y^2); if h == floor(h) x y h end endend

Engineering Computation: An Introduction Using MATLAB and Excel

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 endendfprintf('\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

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

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