1 / 40

WELCOME

WELCOME. EF 105 Fall 2006 Week 11. Topics:. Plotting with MATLAB Program Flows. 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

spencer
Télécharger la présentation

WELCOME

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. WELCOME EF 105 Fall 2006 Week 11

  2. Topics: • Plotting with MATLAB • 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. Table of MATLAB Plotting Commands

  5. 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 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.

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

  8. 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. Editing a graph Changing Line Series Properties

  9. Note that the x-axis was changed to a log scale. 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. Editing a graph Changing Axes Properties

  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 graph Using features on the Insert menu. Note that various other features of graphs can be changed using the Graph Properties Editor above.

  11. 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.

  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: • A*S=B • Enter the following MATLAB Code: • You should see: >> 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

  15. Mathematics Example: Polynomial Roots • Find the roots of the following system: • Enter the following MATLAB code: Now enter the following: >> 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)

  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.” 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. Command Command Command Command False True Done Test Setup Command Commands to execute if False Commands to execute if True Commands Command Command Command Command Straight Line Control Conditional Control (branching structure) Iterative Control (looping structure) MATLAB Program Flows

  22. 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

  24. MATLAB Program Flows (cont.) Truth Tables for Logical Operators Precedence of Operations (1 = highest precedence, 5 = lowest precedence)

  25. MATLAB Program Flows (cont.) 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 &&.

  26. 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. y 40 x 0 20 10 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 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: % 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); Results: >> for1 Sum = 3025 >> for2 Sum = 3025 >> % 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);

  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 occurs)

  37. 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 fprintf('Max value in array A is A(%0.0f,%0.0f) = %0.2f\n',MaxRow,MaxCol,Max);

  38. 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!!

More Related