Upload
elmer-lynch
View
222
Download
0
Embed Size (px)
Citation preview
MATLAB GraphicsMATLAB Graphics One of the best things about MATLAB is
interactive graphics “plot” is the one you will be using most often Many other 3D plotting functions -- plot3,
mesh, surfc, etc. Use “help plot” for plotting options To get a new figure, use “figure” logarithmic plots available using semilogx,
semilogy and loglog
plot(x,y) defaults to a blue line
plot(x,y,’ro’) uses red circles
plot(x,y,’g*’) uses magenta asterisks
If you want to put two plots on the same graph, use “hold on”
plot(a,b,’r:’) (red dotted line)hold onplot(a,c,’ko’) (black circles)
Plotting CommandsPlotting Commands
plot (x, y) plot(x1, y1, x2, y2)
plot (x, y, ‘color symbol line style’)
» x = linspace(0, 2*pi);» y = sin (2.*x);» z = cos (0.5*x);» plot (x, y)» plot (x, y, x, z)» figure (2)» plot (x, y, 'r o -'); grid on» hold on» plot (x, z, 'b * :')
(red, circle, solid line)
(blue, star, dotted line)
figure or figure (#) : open a figure
Plotting CommandsPlotting Commands
» xlabel (Time)» ylabel (Temperature)» title (Temperature Record : 1900 - 2000)» text (17, 120, Record High )» text (85, -40, Record Low )» axis ([0 100 -50 140])» hold off
xlabel ( label ) ylabel ( label )title ( title of the plot )text ( x_location, y_location, text )axis ( [ x_min x_max y_min y_max ] )
- text string
Graphics CommandsGraphics Commands Axis, Labels, and Title
Color, Symbols, and Line TypesColor, Symbols, and Line Types Use “help plot” to find available Specifiers
b blue . point - solid
g green o circle : dotted
r red x x-mark -. dashdot
c cyan + plus -- dashed
m magenta * star
y yellow s square
k black d diamond
v triangle (down)
^ triangle (up)
< triangle (left)
> triangle (right)
p pentagram
h hexagram
Colors Symbols Line Types
» x=0:0.1:5;» y=2*x.^3-12*x.^2+8*x-6;» H=plot(x,y,'b',x,y,'r*');» set(H,'LineWidth',3,'MarkerSize',12)» xlabel('x'); ylabel('y');» title('f(x)=2x^3-12x^2+8x-6');» print -djpeg075 poly.jpg
element-by-element operations x.^n
Adjust line thickness, font size, marker size, etc.
» x=0:0.1:10;» y=sin(2.*pi*x)+cos(pi*x);» H1=plot(x,y,'m'); set(H1,'LineWidth',3); hold on;» H2=plot(x,y,'bO'); set(H2,'LineWidth',3,'MarkerSize',10); hold off;» xlabel('x'); ylabel('y');» title('y = sin(2\pix)+cos(\pix)');» print -djpeg075 function.jpg
» x=0:0.1:3; y1=exp(-x); y2=sqrt(x);» H=plot(x,y1,'b-',x,y2,'r--');» set(H,'LineWidth',3)» xlabel('x'); ylabel('y'); title('MATLAB Plots');» H1=text(1.8,0.2,'exp(-x)'); set(H1,'FontSize',18);» H2=text(1.8,1.3,'sqrt(x)'); set(H2,'FontSize',18);
3-D plots generate a grid containing the x and y values of each point.
x = 0:0.2:2*pi; % create vector of points on x-axis y = 0:0.2:2*pi; % create vector of points on y-axis
% Now if n=length(x) and m=length(y), the grid will contain % N=n*m grid points. XX and YY are n by m matrices containing % the x and y values for each grid point respectively. [XX,YY] = meshgrid(x,y);
% The convention in numbering the points is apparent from % the following lines. x2 = 1:5; y2 = 11:15; [XX2,YY2] = meshgrid(x2,y2); XX2, YY2
% This shows that XX2(i,j) contains the jth component of the % x vector and YY2(i,j) contains the ith component of the y vector.
% Now, we generate a function to save as a separate z-axis value % for each (x,y) 2-D grid point. Z1 = sin(XX).*sin(YY); % calculate value of function to be plotted
% create a colored mesh plot figure; mesh(XX,YY,Z1); xlabel('x'); ylabel('y'); zlabel('z'); title('sin(x)*sin(y)');
% create a colored surface plot figure; surf(XX,YY,Z1); xlabel('x'); ylabel('y'); zlabel('z'); title('sin(x)*sin(y)');
% create a contour plot figure; contour(XX,YY,Z1); xlabel('x'); ylabel('y'); zlabel('z'); title('sin(x)*sin(y)');
% create a filled contour plot with bar to show function values figure; contourf(XX,YY,Z1); colorbar; xlabel('x'); ylabel('y'); zlabel('z'); title('sin(x)*sin(y)');
% create a 3-D contour plot figure; contour3(XX,YY,Z1); xlabel('x'); ylabel('y'); zlabel('z'); title('sin(x)*sin(y)');
subplot ( m, n, p ) --
breaks the figure window into m by n small figures, select the p-th figure for the current plot
» figure (3)» subplot (3, 2, 1)» plot (t,wv1)» subplot (3, 2, 2)» plot (t,wv2)» subplot (3, 2, 4)» plot (t, wv1+wv2)» subplot (3, 2, 6)» plot (t, wv1-wv2)
MATLAB SubplotsMATLAB Subplots
1 2
3 4
5 6
MATLAB SubplotsMATLAB Subplots Filename waves2.m (script file)
% Plot Bi-chromatic Wave Profile% Display the results in three subplotsclf % clear the graphics windowa1 = 1; a2 = 1.5; c1 = 2.0; c2 = 1.8;time = 0:0.1:100;wave1 = a1 * sin(c1*time);wave2 = a2 * sin(c2*time);wave3 = wave1 + wave2;subplot(3,1,1) % top figureplot(time,wave1,'m'); axis([0 100 -3 3]); ylabel('wave 1');subplot(3,1,2) % middle figureplot(time,wave2,'g'); axis([0 100 -3 3]); ylabel('wave 2');subplot(3,1,3) % bottom figureplot(time,wave3,'r'); axis([0 100 -3 3]);xlabel(’time'); ylabel('waves 1&2');
» x=0:0.1:10; y1=sin(pi*x); y2=sin(0.5*pi*x); y3=y1+y2;» z1=cos(pi*x); z2=cos(0.5*pi*x); z3=z1-z2;» subplot(3,2,1); H1=plot(x,y1,'b'); set(H1,'LineWidth',2);» subplot(3,2,2); H2=plot(x,z1,'b'); set(H2,'LineWidth',2);» subplot(3,2,3); H3=plot(x,y2,'m'); set(H3,'LineWidth',2);» subplot(3,2,4); H4=plot(x,z2,'m'); set(H4,'LineWidth',2);» subplot(3,2,5); H5=plot(x,y3,'r'); set(H5,'LineWidth',2);» subplot(3,2,6); H6=plot(x,z3,'r'); set(H6,'LineWidth',2);
Subplot (m,n,p)
Multiple plots
Interactive inputInteractive input The input function allows you to prompt the user
for values directly from the command window
Enter either “value” or “string”
n = input(‘promptstring’)
name = input ('Enter your name: ');
name = input('Enter your name: ','s');
sid = input('Enter your student ID: ');
phone = input('Enter your Telphone number: ','s');
email = input('Enter your Email address: ','s');
string
value
M-Files: Scripts and FunctionsM-Files: Scripts and Functions You can create and save code in text files using
MATLAB Editor/Debugger or other text editors (called m-files since the ending must be .m)
A script can be executed by typing the file name, or using the “run” command
Difference between scripts and functionsDifference between scripts and functions
Scripts share variables with the main workspace
Functions do not
Comments!!!Comments!!!
Program DocumentationProgram Documentation
You must include comments in the computer programs you turn in -- otherwise we will have great difficulty knowing what you are doing
Comments are indicated by “%” at the beginning of the line
Script FilesScript Files Script file – a series of MATLAB commands
saved on a file, can be executed by
typing the file name in the Command Window invoking the menu selections in the Edit Window:
Debug, Run
Create a script file using menu selection: menu File -> New -> M-file opens the integrated
MATLAB text editor for writing a m-file.
Function FileFunction FileStructured programming with functions
Function FileFunction File Function file: M-file that starts with the word function
Function can accept input arguments and return outputs
Analogous to user-defined functions in programming languages such as Fortran, C, …
Save the function file as function_name.m
User help function in command window for additional information
FunctionsFunctions One output variable
function y = function_name(input arguments) More than one output variables
function [y, z] = function_name(input arguments)
Examples: function y = my_func (x)
y = x^3 + 3*x^2 -5 * x +2 ;
Function M-FilesFunction M-Files Function M-file can return more than one result Example – mean and standard deviation of a vector
function [mean, stdev] = stats(x)
% calculate the mean and standard deviation of a vector x
n = length(x);
mean = sum(x)/n;
stdev = sqrt(sum((x-mean).^2/(n-1)));
>> x=[1.5 3.7 5.4 2.6 0.9 2.8 5.2 4.9 6.3 3.5];
>> [m,s] = stats(x)m = 3.6800s = 1.7662
Interactive M-FileInteractive M-File An interactive M-file for free-falling bungee jumper
Use input and disp functions for input/output
function velocity = freefallinteract
% freefallinteract()
% compute the free-fall velocity of a bungee jumper
% input: interactive from command window
% output: ve;ocity = downward velocity (m/s)
g=9.81; % acceleration of gravity
m = input('Mass (kg): ');
cd = input('Drag coefficient (kg/m): ');
t = input('Time (s): ');
disp(' ')
disp('Velocity (m/s):')
vel = sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t);disp([t;vel]')
Interactive M-FileInteractive M-File>> freefallinteractMass (kg): 68.1Drag coefficient (kg/m): 0.25Time (s): 0:1:20 Velocity (m/s): 0 0 1.0000 9.6939 2.0000 18.7292 3.0000 26.6148 4.0000 33.1118 5.0000 38.2154 6.0000 42.0762 7.0000 44.9145 8.0000 46.9575 9.0000 48.4058 10.0000 49.4214 11.0000 50.1282 12.0000 50.6175 13.0000 50.9550 14.0000 51.1871 15.0000 51.3466 16.0000 51.4560 17.0000 51.5310 18.0000 51.5823 19.0000 51.6175 20.0000 51.6416
Problem-Solving MethodologyProblem-Solving Methodology State the problem clearly Describe the Input/Output (I/O) Work the problem by hand or with a
calculator for a simple set of data Algorithm Develop a MATLAB Solution Debugging and Testing Optimize the program and make a document
Structured ProgrammingStructured Programming
The ideal style of programming is StructuredStructured or ModularModular programming
Break down a large goal into smaller tasks Develop a module for each task A module has a single entrance and exit Modules can be used repeatedly A subroutinesubroutine (function M-file)(function M-file) may contain several
modules Subroutines (Function M-files) called by a main
program
Algorithm DesignAlgorithm Design
The sequence of logical steps required to
perform a specific task (solve a problem)
Each step must be deterministic The process must always end after a finite
number of steps The algorithm must be general enough to deal
with any contingency
Common Program StructuresCommon Program Structures
Sequence Selection Repetition
Structured ProgrammingStructured Programming
Sequential paths Sequence – all instructions (statements) are
executed sequentially from top to bottom
Non-sequential paths Decisions (Selection) – if, else, elseif Loops (Repetition) – for, while, break
Relational OperatorsRelational Operators MATLAB provides these relational operators.
MATLAB == ~= < <= > >= & | ~
Interpretation is equal to is not equal to is less than is less than or equal to is greater than is greater than or equal to and, true if both are true or, true if either one is true not
Logical ConditionsLogical Conditions ~ (not) – logical negation of an expression ~ expression If the expression is true, the result is false.
Conversely, if the expression is false, the result is true.
& (and) – logical conjunction on two expressions
expression1 & expression2
If both expressions are true, the result is true. If either or both expressions are false, the result is false.
| (or) – logical disjunction on two expressions
expression1 | expression2
If either or both expressions are true, the result is true
True Table for Logical OperatorsTrue Table for Logical Operators Order of priority of logical operators
x y ~x x&y x|y
T T F T T
T F F F T
F T T F T
F F T F F
Logical OperatorsLogical Operators 0 - 1 matrix 0: false ; 1: True
a=[2 4 6] b=[3 5 1] c=[4 3 2] a<b ans = 1 1 0 b<c ans = 1 0 1 a ~= b ans = 1 1 1 a<b&b<c ans = 1 0 0 a <= b | b >= c ans = 1 1 0
Example of a Complex DecisionExample of a Complex Decision
If a=-1, b=2, x=1, and y=‘b’, evaluate
A * b > 0 & b == 2 & x > 7 | ~(y > ‘d’)
1. Expression 1: A*b = -2 > 0 (false)
2. Expression 2: b = 2 (true)
3. Expression 3: x = 1 > 7 (false)
4. Expression 4: ‘b’ > ‘d’ (false)
5. Expression 5: ~(Expression 4) (true)
6. Expression 6: (Expression 1) & (Expression 2) (false)
7. Expression 7: (Expression 6) & (Expression 3) (false)
8. Expression 8: (Expression 7) | (Expression 5) (true)
Complex DecisionComplex Decision A step-by-step evaluation of a complex decision
any & allany(A) Returns 1 for a vector where any element of the vector is true (nonzero), and 0 if no elements are true. all(A) Returns 1 for a vector where all elements of the vector are true (nonzero), and 0 if all elements are not true. A = [0 1 2; 0 -3 8; 0 5 0];any(A)ans = 0 1 1
all(A)ans = 0 1 0
Selection Selection ((IFIF)) Statements Statements The most common form of selection
structure is a simple if statement The if statement will have a condition
associated with it The condition is typically a logical
expression that must be evaluated as either “true” or “false”
The outcome of the evaluation will determine the next step performed
Logical IF StatementsLogical IF Statements If (condition) executable_statements end
-1 1x
1
y
if (x < = -1.0 | x > = 1.0) y = 0endif (x > -1.0 & x < 0.) y = 1 + xendif (x > = 0. & x < 1.0) y = 1- xend
Nested IF StatementNested IF Statement
if (condition or experssion1) statement blockelseif (condition or experssion2) another statement blockelse another statement blockend
Structures can be nested within each other
How to use Nested IFHow to use Nested IF If the condition is true the
statements following the statement block are executed.
If the condition is not true, then the control is transferred to the next
else, elseif, or end statement at the same if level.
Else and ElseifElse and Elseifif temperature > 100
disp(‘Too hot - equipment malfunctioning.’)
elseif temperature > 75
disp(‘Normal operating range.’)
elseif temperature > 60
disp(‘Temperature below desired operating range.’)
else
disp(‘Too Cold - turn off equipment.’)
end
Nested IF StatementsNested IF Statements nested if (if, if else, if elseif)
-1 1x
1
y
if (x < = -1.0)
y = 0.
elseif (x < = 0.)
y = 1. + x
elseif (x < = 1.0)
y = 1. - x
else
y=0.
end
M-file: Evaluate StudentsM-file: Evaluate Students GradeGrade function cven302_gradename = input('Enter Student Name: ','s');sid = input('Enter Student ID: ');HW = input('Enter Homework Average (30%): ');Exam1 = input('Enter Exam I score (20%): ');Exam2 = input('Enter Exam II score (20%): ');Final = input('Enter Final Exam score (30%): ');Average= HW*0.3 + Exam1*0.2 + Exam2*0.2 + Final*0.3; fprintf('Your Semester Average is: %6.2f \n',Average)if Average >= 90 Grade = 'A';elseif Average >= 80 Grade = 'B';elseif Average >= 70 Grade = 'C';elseif Average >= 60 Grade = 'D';else Grade = 'F';endfprintf('Your Semester Grade is : '), disp(Grade)
>> cven302_grade
Enter Student Name: Jane Doe
Enter Student ID: 1234567
Enter Homework Average (30%): 96
Enter Exam I score (20%): 88
Enter Exam II score (20%): 92
Enter Final Exam score (30%): 85
Your Semester Average is: 90.30
Your Semester Grade is : A
>> cven302_grade
Enter Student Name: John Doe
Enter Student ID: 9876543
Enter Homework Average (30%): 62
Enter Exam I score (20%): 84
Enter Exam II score (20%): 80
Enter Final Exam score (30%): 91
Your Semester Average is: 78.70
Your Semester Grade is : C
Decisions (Selections)Decisions (Selections) if … elseif if … elseif
StructureStructure
switch, case, and otherwiseswitch, case, and otherwiseswitch executes certain statements based on the value of a variable or expression. Its basic form is: switch expression (scalar or string) case value1 statements % Executes if expression is value1 case value2 statements % Executes if expression is value2 . . . otherwise statements % Executes if expression does not % match any caseend
switch, case, and otherwiseswitch, case, and otherwiseswitch 'b'
case -1 disp('negative one'); case 0 disp('zero'); case 'b'
disp('positive one'); otherwise disp('other value');end
Note for C Programmers Unlike the C language the, MATLAB switch executes only the first matching case; subsequent matching cases do not execute. Therefore, break statements are not used.
RepetitionRepetition
for i=1:mfor j=1:n
a(i,j)=(i+1)^2*sin(0.2*j*pi);end
end
while condition statementsend
For LoopsFor Loopsfor index = start : step : finish statementsend
for k = 1:length(d)
if d(k) < 30
velocity(k) = 0.5 - 0.3*d(k).^2;
else
velocity(k) = 0.6 + 0.2*d(k)-0.01*d(k).^2
end
end
Ends after a specified number
of repetitions
For LoopFor Loopfunction A = for_loop(m,n)
for i = 1:m
for j = 1:n
A(i,j) = 50*exp(-0.2*i)^2*sin(0.1*j*pi);
end
end
>> A = for_loop(8,6)
A =
10.3570 19.7002 27.1150 31.8756 33.5160 31.8756
6.9425 13.2054 18.1757 21.3669 22.4664 21.3669
4.6537 8.8519 12.1836 14.3226 15.0597 14.3226
3.1195 5.9336 8.1669 9.6007 10.0948 9.6007
2.0910 3.9774 5.4744 6.4356 6.7668 6.4356
1.4017 2.6661 3.6696 4.3139 4.5359 4.3139
0.9396 1.7872 2.4598 2.8917 3.0405 2.8917
0.6298 1.1980 1.6489 1.9384 2.0381 1.9384
For LoopFor Loop M-file for computing the factorial n! MATLAB has a built-in function factorial(n) to compute n!
function fout = factor(n)
% factor(n):
% Computes the product of all the integers from 1 to n.
x=1;
for i = 1:n
x = x*i;
end
fout = x;
>> factor(12)
ans =
479001600
>> factor(100)
ans =
9.332621544394410e+157
While LoopsWhile Loops
while condition statementsend
If the statement is true, the statements are executed
If the statement is always true, the loop becomes an “infinite loop”
The “break” statement can be used to terminate the “while” or “for” loop prematurely.
Ends on the basis of a logical condition
While LoopWhile Loop Compute your checking account balancefunction checking
% Compute balance in checking account
Balance = input('Current Checking Account Balance ($) = ');
Deposit = input('Monthly Deposit ($) = ');
Subtract = input('Monthly Subtractions ($) = ');
Month = 0;
while Balance >= 0
Month = Month + 1;
Balance = Balance + Deposit - Subtract;
if Balance >= 0
fprintf('Month %3d Account Balance = %8.2f \n',Month,Balance)
else
fprintf('Month %3d Account Closed \n',Month)
end
end
While LoopWhile Loop>> checking
Current Checking Account Balance ($) = 8527.20
Monthly Deposit ($) = 1025.50
Monthly Subtractions ($) = 1800
Month 1 Account Balance = 7752.70
Month 2 Account Balance = 6978.20
Month 3 Account Balance = 6203.70
Month 4 Account Balance = 5429.20
Month 5 Account Balance = 4654.70
Month 6 Account Balance = 3880.20
Month 7 Account Balance = 3105.70
Month 8 Account Balance = 2331.20
Month 9 Account Balance = 1556.70
Month 10 Account Balance = 782.20
Month 11 Account Balance = 7.70
Month 12 Account Closed
Example: Roots of Quadratic EquationExample: Roots of Quadratic Equation
a
acbbx
cbxax
2
4
02
2
If a=0, b=0, no solution (or trivial sol. c=0)
If a=0, b0, one real root: x=-c/b
If a0, d=b2 4ac 0, two real roots
If a0, d=b2 4ac <0, two complex roots
function quad = quadroots(a,b,c)% Computes real and complex roots of quadratic equation% a*x^2 + b*x + c = 0% Output: (r1,i1,r2,i2) - real and imaginary parts of the% first and second rootif a == 0 % weird cases if b ~= 0 % single root r1 = -c/b else % trivial solution error('Trivial or No Solution. Try again') end % quadratic formulaelsed = b^2 - 4*a*c; % discriminant if d >= 0 % real roots r1 = (-b + sqrt(d)) / (2*a) r2 = (-b - sqrt(d)) / (2*a) else % complex roots r1 = -b / (2*a) r2 = r1 i1 = sqrt(abs(d)) / (2*a) i2 = -i1 endend
>> quad = quadroots(5,3,-4)
r1 =
0.6434
r2 =
-1.2434
>> quad = quadroots(5,3,4)
r1 =
-0.3000
r2 =
-0.3000
i1 =
0.8426
i2 =
-0.8426
>> quad = quadroots(0,0,5)
??? Error using ==> quadroots
Trivial or No Solution. Try again
(two real roots)
(two complex roots)
(no root)