1 welcome ef 105 fall 2006 week 11. 2 topics: 1.plotting with matlab 2.program flows

40
1 WELCOME WELCOME EF 105 Fall 2006 Week 11

Upload: ashlynn-wilkinson

Post on 28-Dec-2015

213 views

Category:

Documents


0 download

TRANSCRIPT

1

WELCOMEWELCOMEEF 105

Fall 2006

Week 11

2

Topics:

1. Plotting with MATLAB

2. Program Flows

3

MATLAB Plotting: Basic Commands•Graphing in MATLAB•Several types of graphs can be created in MATLAB, including:• x-y charts• column charts (or histograms)• contour plots• surface plots•x-y charts are most commonly used in engineering courses, so we will focus on these.

•x-y Charts in MATLAB•The table on the next page shows several commands that are available in MATLAB for plotting x-y graphs.

4

MATLAB Command Description

plot(x,y) Plots y values versus x values

(x and y values stored in vectors).

plot(x,y,S) Similar to plot(x,y) except the character string S can be used to specify various line types, symbols, and colors as shown in the

table on the next page.

loglog(x,y) Like plot(x,y) but uses log-log axes

semilogx(x,y) Like plot(x,y) but uses log scale for x-axis

semilogy(x,y) Like plot(x,y) but uses log scale for y-axis

hold Plot the next set of data on the same chart

title(‘text’) Adds a title to the top of the graph.

xlabel(‘text’) Adds a label to the x-axis.

ylabel(‘text’) Adds a label to the y-axis.

grid on (or grid) Turns on the grid lines.

grid off Turns off the grid lines.

grid minor Turns on the minor grid lines.

Table of MATLAB Plotting Commands

5

S Color S Data

Symbol

S Line

Type

b Blue . Point - Solid

g Green O Circle : Dotted

r Red x x-mark -. Dash-dot

c Cyan + Plus -- Dashed

m Magenta * Star

y Yellow s Square

k Black d Diamond

v Triangle (down)

^ Triangle (up)

< Triangle (left)

> Triangle (right)

Table of S Options for the MATLAB plot(x,y,S) Command

Note: Many of these options can be set using the Graph Property Editor (illustrated in the following pages)

6

Examples of using S options in the plot command:plot(x, y, ‘k*-’) - Plot y versus x using a solid black line with an *

marker shown for each pointplot(x, y, ‘gd:’) - Plot y versus x using a dotted green line with a diamond

marker shown for each pointplot(x, y, ‘r+--’) - Plot y versus x using a dashed red line with a +

marker shown for each point

Example – MATLAB program to plot an x-y graph:

Enter the name of the program (Graph) in the MATLAB Command Window and the graph (Figure 1) on the following page appears.

7

Note that certain features of the graph may be edited from this window (called the Graph Property Editor).See next page.

8

Editing a graphChanging Line Series Properties

Begin by pressing this button to enter “picking mode”.

Double-click on a graph line or point to open the Property Editor – Lineseries shown below. You can

change various line series properties here.

9

Editing a graphChanging Axes Properties

Double-click on an axis (or a point on an axis) to open the Property Editor – Axes shown below.

You can change various axes properties here.

Note that the x-axis was changed to a log scale.

10

Use Insert – Text Arrow to add the arrow and text shown on the graph.

Use Insert – Text Box to add the text box shown on the graph.

Editing a graphUsing features on the Insert menu.

Note that various other features of graphs can be changed using the Graph Properties Editor above.

11

Graphing data pointsGraphing data points is similar to graphing functions. The data points simply need to be stored in vectors.Example: Suppose that the power, P, dissipated by a resistor was measured in lab for a variety of resistance, R, values using a constant voltage of 50 V. The measured results are shown below. Graph P versus R.

Resistance

R (k)

Power

P (W)

10 248.3

22 110.2

47 50.4

68 36.1

100 24.2

220 11.0

470 5.25

680 3.85

1000 2.75

12

13

Example: Try the following example in class:• Calculate the area of a circle for a radius of 10, 15, 20, … , 75 (inches).• Display the results in a table.• Graph area versus radius.

14

MATLAB EnvironmentEnter the following:

15

Mathematics Example:Linear Systems

• Solve the system:

• A*S=B• Enter the following MATLAB Code:

• You should see:

609

234

3325

zyx

zy

zyx

>> A=[5,-2,-3;0,4,3;1,-1,9];>> B=[-3,-2,60]'; % Note vector transpose (‘)>> S=linsolve(A,B)

S = 1.0000 -5.0000 6.0000

16

Mathematics Example: Polynomial Roots

• Find the roots of the following system:

• Enter the following MATLAB code:

Now enter the following:

812 2 xxy

>> roots([12 -1 -8])ans = 0.8592 -0.7759

>> a=12;>> b=-1;>> c=-8;>> x=-1:0.1:1;>> y=a*x.^2+b*x+c;>> plot(x,y)

17

Physics Example:Graphical Solution of a Trajectory

• Problem:

A football kicker can give the ball an initial speed of 25 m/s. Within what two elevation angles must he kick the ball to score a field goal from a point 50 m in front of goalposts whose horizontal bar is 3.44 m above the ground?

18

Physics Example:Field Goal Problem

Solution: The general solution is the “trajectory equation.”

where y = height, x = distance from goal, v0 = take-off speed, θ0 = take-off angle. Given the take-off speed of 25 m/s, the problem requires the solutions for θ0 that result in a minimum height of y = 3.44 m at a distance of x = 50 m from the goal post. Although an analytical solution is possible, a graphical solution provides more physical insight.

)(cos2)tan(

022

0

2

0

v

gxxy

19

Physics Example:Field Goal Problem• Enter the following MATLAB code for a graphical

solution:

>> v0=25;>> x=50;>> g=9.8;>> y=3.44;>> theta=5:.1:70;>> theta_r=theta*pi/180;>> z=y*ones(1,length(theta));>> zz=x*tan(theta_r)-g*x^2./(2*v0^2*(cos(theta_r)).^2);>> plot(theta,zz)>> holdCurrent plot held>> plot(theta,z)

20

Physics Example:MATLAB Results

21

Outputting a Table with Headings

22

MATLAB Program Flows

Command

Command

Command

Command

Command

Straight Line Control

Command

Test

Commandsto execute

if False

Command

Commandsto execute

if True

TrueFalse

Conditional Control(branching structure)

Command

Commands

Command

Setup Done

Iterative Control(looping structure)

23

MATLAB Program Flows (cont.)

Since conditional structures involve branching based on the result of logical tests (such as a program that branches if x > 2), it is important to first introduce logical expressions.

Logical ExpressionsLogical variables in MATLAB can have values of true or false.To create a logical variable, a logical values simply needs to be assigned to it.For example: A = true; B = false;

Note that logical values also have a numerical equivalent:true = 1false = 0

24

MATLAB Program Flows (cont.)

Logical Operators Logical operators are used in MATLAB between two logical operands to yield a logical result. The general form for logical expression with the 5 available binary operators is: L1 logical operator L2 (for example: x > 2 AND x < 8)where L1 and L2 are logical expressions or variables. The general form for logical expression with the one available unary operators is: logical operator L1 (for example: ~x > 2)

Logical Operators

Operator Operation Binary or unary

& Logical AND Binary

&& Logical AND with shortcut evaluation

Binary

| Logical OR Binary

|| Logical OR with shortcut evaluation

Binary

xor Logical Exclusive OR Binary

~ Logical NOT Unary

25

MATLAB Program Flows (cont.)

Truth Tables for Logical Operators

L1 L2 L1 & L2

AND

L1 | L2

OR

xor(L1,L2)

Exclusive-OR

~L1

NOT

false false false false false true

false true false true true true

true false false true true false

true true true true false false

Precedence Operator

1 Arithmetic operators (as described previously)

2 Relational operators (= =, ~=, >, >=, <, <=) from left to right

3 Unary NOT operator (~)

4 Logical AND operators (&, &&) from left to right

5 Logical OR and Exclusive OR operators (|, ||, xor) from left to right

Precedence of Operations (1 = highest precedence, 5 = lowest precedence)

26

MATLAB Program Flows (cont.)

Logical Expression

(for x = 2, y = 5) Result

x < 4 & x > 1 true (1)

1 < x < 4 invalid expression

x = = 1 | x = = 3 false (0)

~x < y false (0)

xor(x > 3, y > 3) true (1)

x = = 2| y = = 3 & x < 0 true (1)

Examples of Logical Expressions

Shortcut evaluation (a minor point)What is the difference between Logical AND (&) and Logical AND with shortcut evaluation (&&)? The difference is illustrated below: L1 & L2 % L1 and L2 are both evaluated, then the results are ANDed L1 && L2 % L1 is evaluated. If it is false, the result of the entire expression is % false, so L2 is never evaluated. Also note that && works only with scalars, where & works with either scalar or array values.The differences are between Logical OR (|) and Logical OR with shortcut evaluation (||) are similar to those described above for & and &&.

27

MATLAB Program Flows (cont.)

Conditional Control Structures in MATLABMATLAB offers three types of conditional control structures:• IF – THEN – ELSE structure• SWITCH structure• TRY/CATCH structure

We will only cover the IF – THEN – ELSE structure as it is the most common.

28

MATLAB Program Flows (cont.)

IF – THEN – ELSE structureThere are four versions of this structure as shown.

if relational/logical test <commands to execute if test is true>end

if relational/logical test <commands to execute if test is true>else <commands to execute if test is false>end

if relational/logical test #1 <commands to execute if test #1 is true>elseif relational/logical test #2 <commands to execute if test #2 is true>end

if relational/logical test #1 <commands to execute if test #1 is true>elseif relational/logical test #2 <commands to execute if test #2 is true>else <commands to execute if all tests above are false>end

Note that an unlimited number of elseif statements could be added to the last two structures.

29

MATLAB Program Flows (cont.)

% IF - THEN - ELSE structure - Example 1% EF105% filename: if1.m% Sample program to calculate weekly pay. Overtime paid for over 40 hours.format compactHours = input('Enter number of hours worked this week: ');Rate = input('Enter amount paid per hour: $');Pay = Hours*Rate;if Hours > 40 disp('You earned overtime pay.') Pay = Pay + (Hours-40)*Rate/2;endfprintf('Your pay is $%0.2f\n',Pay)

30

MATLAB Program Flows (cont.)

% IF - THEN - ELSE structure - Example 2% EF 105% filename: if2.m% Sample program to calculate weekly pay. Overtime paid for over 40 hours.format compactHours = input('Enter number of hours worked this week: ');Rate = input('Enter amount paid per hour: $');if Hours <= 40 disp('No overtime earned.') Pay = Hours*Rate;else disp('You earned overtime pay.') Pay = 40*Rate + (Hours-40)*Rate*1.5;endfprintf('Your pay is $%0.2f\n',Pay)

31

MATLAB Program Flows (cont.)

% IF - THEN - ELSE structure - Example 3% EF 105% filename: if3.m% Sample program to calculate y(x) defined% over several ranges of x.format compactx = input('Enter value of x: ');y = 0; % This value will be replaced if % x is between 0 and 20.if 0 <= x & x < 10 y = 4*x;elseif 10 <= x & x < 20 y = -4*x+80;endfprintf('y(x) = %0.2f\n',y)

x 20 ,0

20x 10 ,80x4

10x 0 x,4

0 x ,0

y(x)

:follows as defined is y(x)Function

0 10 20x

y

40

32

MATLAB Program Flows (cont.)

% IF - THEN - ELSE structure - Example 4% EF 105% filename: if4.m% Sample program to display letter grade for an input% numerical grade using a standard 10 point scale. % Display error message if grades are from 0 to 100.format compactGrade = input('Enter numerical grade (0 to 100): ');if Grade < 0 | Grade > 100 disp('Invalid grade')elseif Grade >= 90 disp('Grade = A')elseif Grade >= 80 disp('Grade = B')elseif Grade >= 70 disp('Grade = C')elseif Grade >= 60 disp('Grade = D')else disp('Grade = F')end

33

The “for” statement

for index = start : [increment :] endstatements

end

index, start, increment, and end do not need to be integer valued

increment is optional, if increment is not specified increment defaults to 1

index can be incremented positive (increment > 0) or negative (increment < 0)

loop stops when index > end (or index < end)

MATLAB Flow Control

34

“legend” remembers the order the graphs were plotted

Adding a Legend for multiple graphs

MATLAB PLOTTING

35

MATLAB Program Flows (cont.)

The for loopThe for loop is used to execute a block of statements a specified number of times. It has the form shown to the right.

for loopVar = loopVector Command 1 Command 2 … Command nend

ExampleEvaluate the following summation:

10

1i

3i Sum

>> for1Sum = 3025>> for2Sum = 3025>>

% filename: for1.m% Example: Use a for loop to find sum(i^3) for i = 1 to 10.Sum = 0; %Initialize variable to zerofor i = 1:1:10 Sum = Sum + i^3;endfprintf('Sum = %0.0f\n',Sum);

% filename: for2.m% Example: Use a for loop to find sum(i^3) for i = 1 to 10.Sum = 0; %Initialize variable to zerofor i = [1,2,3,4,5,6,7,8,9,10] Sum = Sum + i^3;endfprintf('Sum = %0.0f\n',Sum);

Results:

36

MATLAB Program Flows (cont.)

ExampleWrite a program to determine the balance after N years on an account that contains an initial deposit D and earns a simple interest of I percent. Prompt the user to enter values for N, D, and I.

>> InterestEnter the amount of the initial deposit: $1000Enter the percent interest rate: 6Enter the number of years: 10Final balance = $1790.85

% Sample program to determine the final balance in a savings account where% D = initial deposit% I = interest rate (percent)% N = number of years% Filename: Interest.mD = input('Enter the amount of the initial deposit: $');I = input('Enter the percent interest rate: ');N = input('Enter the number of years: ');Balance = D; %Initial value in the accountfor years = 1:N Balance = Balance*(1+I/100);endfprintf('Final balance = $%0.2f\n',Balance);

37

MATLAB Program Flows (cont.)

Nested for loopsFor loops can occur within other for loops as shown in the examples below. Note that while indenting loops is not required, it helps to make them more readable.

for loopVar1 = loopVector1 Command 1 for loopVar2 = loopVector2 Command A1 Command A2 … Command An end Command 2 … Command nend

Sum = 0;for I = 1:10 for J = 1:15 Sum = Sum + 1; endEndfprintf(‘\nSum = %0.0f’,Sum);

What value for Sum is printed in the program below?

Example:The example program on the following slide:• Prompts the user to enter each value of a 2D array• Calculates the maximum value of the array (and the row/column where the max occurs)

38

MATLAB Program Flows (cont.)% Program to prompt the user to enter values in a matrix % by row and column number.% Also find the max value in the matrix.% Filename: Matrixmax.mformat compactRows = input('Enter the number of rows in the matrix: ');Columns = input('Enter the number of columns in the matrix: ');for i = 1:Rows for j = 1:Columns fprintf('Enter A(%0.0f,%0.0f):',i,j); A(i,j) = input(' '); endendA% find the max value in the matrixMax = A(1,1); %Set max to first value in arrayMaxRow = 1;MaxCol = 1;for i = 1:Rows for j = 1:Columns if A(i,j)> Max Max = A(i,j); MaxRow = i; MaxCol = j; end endendfprintf('Max value in array A is A(%0.0f,%0.0f) = %0.2f\n',MaxRow,MaxCol,Max);

39

MATLAB Program Flows (cont.)

>> MatrixmaxEnter the number of rows in the matrix: 2Enter the number of columns in the matrix: 3Enter A(1,1): 12Enter A(1,2): 14Enter A(1,3): 17Enter A(2,1): 23Enter A(2,2): 11Enter A(2,3): -8A = 12 14 17 23 11 -8Max value in array A is A(2,1) = 23.00

40

MATLAB Exercise 2• See the Word document for this exercise and perform at end of class on your own!!