WELCOME EF 105 Fall 2006 Week 11 1 Topics: 1. Plotting with MATLAB 2. Program Flows 2 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. 3 Table of MATLAB Plotting Commands 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. 4 Table of S Options for the MATLAB plot(x,y,S) Command 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) Note: Many of these options can be set using the Graph Property Editor (illustrated in the following pages) 5 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 point plot(x, y, ‘gd:’) - Plot y versus x using a dotted green line with a diamond marker shown for each point plot(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. 6 Note that certain features of the graph may be edited from this window (called the Graph Property Editor). See next page. 7 Editing a graph Changing 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. 8 Editing a graph Changing Axes Properties Double-click on an axis (or a point on an axis) to open the Property Editor – Axes shown below. Note that the x-axis was changed to a log scale. You can change various axes properties here. 9 Editing a graph Using features on the Insert menu. 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. Note that various other features of graphs can be changed using the Graph Properties Editor above. 10 Graphing data points Graphing 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 11 12 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. 13 MATLAB Environment Enter the following: 14 Mathematics Example:Linear Systems • Solve the system: 5 x 2 y 3 z 3 4 y 3 z 2 x y 9 z 60 • A*S=B • Enter the following MATLAB Code: >> A=[5,-2,-3;0,4,3;1,-1,9]; >> B=[-3,-2,60]'; % Note vector transpose (‘) >> S=linsolve(A,B) • You should see: S= 1.0000 -5.0000 6.0000 15 Mathematics Example: Polynomial Roots • Find the roots of the following system: y 12 x 2 x 8 • Enter the following MATLAB code: >> roots([12 -1 -8]) ans = 0.8592 -0.7759 Now enter the following: >> >> >> >> >> >> a=12; b=-1; c=-8; x=-1:0.1:1; y=a*x.^2+b*x+c; plot(x,y) 16 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? 17 Physics Example: Field Goal Problem Solution: The general solution is the “trajectory equation.” gx 2 y x tan( 0 ) 2 2v0 cos 2 ( 0 ) 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. 18 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) >> hold Current plot held >> plot(theta,z) 19 Physics Example: MATLAB Results 20 Outputting a Table with Headings 21 MATLAB Program Flows Command Command Command Command Command False Test Commands to execute if False True Commands to execute if True Setup Done Commands Command Command Straight Line Control Command Conditional Control (branching structure) Command Iterative Control 22 (looping structure) 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 Expressions Logical 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 = 1 false = 0 23 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 24 MATLAB Program Flows (cont.) Truth Tables for Logical Operators L1 L2 L1 & L2 L1 | L2 AND 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 of Operations (1 = highest precedence, 5 = lowest precedence) 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 25 MATLAB Program Flows (cont.) Examples of Logical Expressions 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) 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 26 evaluation (||) are similar to those described above for & and &&. MATLAB Program Flows (cont.) Conditional Control Structures in MATLAB MATLAB 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. 27 MATLAB Program Flows (cont.) if relational/logical test <commands to execute if test is true> end IF – THEN – ELSE structure There are four versions of this structure as shown. 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 Note that an unlimited number of elseif statements could be added to the last two structures. 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 28 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 compact Hours = 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; end fprintf('Your pay is $%0.2f\n',Pay) 29 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 compact Hours = 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; end fprintf('Your pay is $%0.2f\n',Pay) 30 MATLAB Program Flows (cont.) Function y(x) is defined as follows : 0, 4x, y(x) 4x 80, 0, x0 0 x 10 10 x 20 20 x y 40 x 0 10 20 % IF - THEN - ELSE structure - Example 3 % EF 105 % filename: if3.m % Sample program to calculate y(x) defined % over several ranges of x. format compact x = 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; end fprintf('y(x) = %0.2f\n',y) 31 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 compact Grade = 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 32 MATLAB Flow Control The “for” statement for index = start : [increment :] end statements 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) 33 MATLAB PLOTTING Adding a Legend for multiple graphs “legend” remembers the order the graphs were plotted 34 MATLAB Program Flows (cont.) for loopVar = loopVector Command 1 Command 2 … Command n end The for loop The for loop is used to execute a block of statements a specified number of times. It has the form shown to the right. Example Evaluate the following summation: Sum 10 3 i i 1 % filename: for1.m % Example: Use a for loop to find sum(i^3) for i = 1 to 10. Sum = 0; %Initialize variable to zero for i = 1:1:10 Sum = Sum + i^3; end fprintf('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 zero for i = [1,2,3,4,5,6,7,8,9,10] Sum = Sum + i^3; end fprintf('Sum = %0.0f\n',Sum); Results: >> for1 Sum = 3025 >> for2 Sum = 3025 >> 35 MATLAB Program Flows (cont.) Example Write 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. % 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.m D = 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 account for years = 1:N Balance = Balance*(1+I/100); end fprintf('Final balance = $%0.2f\n',Balance); >> Interest Enter the amount of the initial deposit: $1000 Enter the percent interest rate: 6 Enter the number of years: 10 Final balance = $1790.85 36 MATLAB Program Flows (cont.) Nested for loops For 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 n end What value for Sum is printed in the program below? Sum = 0; for I = 1:10 for J = 1:15 Sum = Sum + 1; end End fprintf(‘\nSum = %0.0f’,Sum); 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 37 occurs) 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.m format compact Rows = 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(' '); end end A % find the max value in the matrix Max = A(1,1); %Set max to first value in array MaxRow = 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 end end 38 fprintf('Max value in array A is A(%0.0f,%0.0f) = %0.2f\n',MaxRow,MaxCol,Max); MATLAB Program Flows (cont.) >> Matrixmax Enter the number of rows in the matrix: 2 Enter the number of columns in the matrix: 3 Enter A(1,1): 12 Enter A(1,2): 14 Enter A(1,3): 17 Enter A(2,1): 23 Enter A(2,2): 11 Enter A(2,3): -8 A = 12 14 17 23 11 -8 Max value in array A is A(2,1) = 23.00 39 MATLAB Exercise 2 • See the Word document for this exercise and perform at end of class on your own!! 40