But, Our MATLAB Tutorial is Not Over! MATLAB Has Many More ...
Transcript of But, Our MATLAB Tutorial is Not Over! MATLAB Has Many More ...
90
But, Our MATLAB Tutorial is Not Over!MATLAB Has Many More Useful Features.
• Built-in functions
• Data plotting
• Logical expressions
• Branches and loops
• User-defined functions
91
MATLAB’s Built-In Functions
MATLAB comes with a very large variety of built-in mathfunctions that are ready for use. Common ones include:
sin(x) cos(x) tan(x)
asin(x) acos(x) atan(x) atan2(y,x)
exp(x) log(x) sqrt(x)
abs(x) angle(x)
Less common ones include hyperbolics and their inverses,Bessel functions of various flavors, and other functionsused in advanced engineering and scientific analyses.This is one of MATLAB’s greatest strengths.
92
Function Operations on Arrays
Upon receiving an array of input numbers, many MATLABfunctions calculate an array of output values on anelement-by-element basis. For example, if
x = [0 pi/2 pi 3*pi/2 2*pi]
then the statement
y = sin(x)
produces the result y = [0 1 0 -1 0] .
93
Complex-Valued Inputs
Unlike many languages such as C and Fortran, manyMATLAB functions work correctly for both real-valuedand complex-valued inputs. For example:
>> sqrt(-2) ans = 0 + 1.4142i
For information about the admissible inputs for a specificfunction, use the MATLAB Help Browser.
94
Introduction to Data Plotting
To plot a data set in MATLAB, simply create two vectorscontaining the x and y values to be plotted and use theplot function. Any pair of vectors can be plotted versuseach other as long as both have the same length.
For example, say we want to plot f(x) = sin(2x) for0 ≤ x ≤ 2π in increments of π/100 radian.
x = 0:pi/100:2*pi;y = sin(2*x);plot(x,y);
When the plot function is executed,MATLAB opens a Figure Window anddisplays the plot in that window.
95
Add Title, Axis Labels, and Grid Lines
Titles and axis labels can be added with the title ,xlabel , and ylabel functions. Grid lines can be addedwith grid on and removed with grid off . Example:
x = 0:pi/100:2*pi; y = sin(2*x); plot(x,y);
title( ' Plot of f(x) = sin(2x) ' );
xlabel( ' x ' );
ylabel( ' y ' ); grid on;
Addedcode
96
Plot Multiple Functions on the Same Graph
Example: Plot f(x) = sin(2x) and its derivativeg(x) = 2cos(2x) on the same graph.
x = 0:pi/100:2*pi;
y1 = sin(2*x);
y2 = 2*cos(2*x);
plot(x,y1,x,y2);
97
Specify Line Colors and Styles
Example: Plot f(x) = sin(2x) and its derivative
g(x) = 2cos(2x) on the same graph. Use a solid red
line for f(x) and a dashed green line for g(x).
x = 0:pi/100:2*pi;
y1 = sin(2*x);
y2 = 2*cos(2*x);
plot(x,y1,'r-',x,y2,'g--');
denotes a
red solid
line
denotes a
green dashed
line
98
Add an Explanatory Legend
Example: Add an explanatory legend to the previous
graph.
x = 0:pi/100:2*pi;
y1 = sin(2*x);
y2 = 2*cos(2*x);
plot(x,y1,'r-',x,y2,'g--');
legend('f(x)','d/dx f(x)',1);
Legend position parameter: 0 for automatic
best placement (least conflict with the data);
1 for upper right-hand corner; etc.
100
Implement Logarithmic Axes, If Needed
Logarithmic x and / or y axes can be very useful whenthe data to be displayed varies over ranges of about100:1 or more. This feature can be implemented byusing the following variations of the plot function:
plot Both x and y data are plotted on linearaxes.
semilogx x data are plotted on a log axis and y dataare plotted on a linear axis.
semilogy x data are plotted on a linear axis andy data are plotted on a log axis.
loglog Both x and y data are plotted on log axes.
102
Relational Operators in MATLAB
• Allow us to test whether two values (floating point,integer, or character) are the same, or whether one isgreater than or less than the other.
• If the test yields a “True” condition, the number 1 isreturned. If the test yields a “False” condition, thenumber 0 is returned.
• We can then act on the “True” or “False” conditionby subsequently choosing different paths within theprogram.
103
Cautionary Remark
• Unlike most programming languages, MATLAB doesnot have a logical type. In MATLAB, the “True” and“False” conditions are represented as 1 and 0 ,respectively.
• Therefore, we must be careful to distinguish betweenthe numbers 1 and 0 produced during normalcalculations and the numbers 1 and 0 produced as aresult of “True” and “False” tests. The context is thekey!
104
List of Relational Operators
== equal to
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
105
Sample Results of Relational Operators
Operation Result
5 == 6 0
5 < 6 1
5 <= 5 1
5 ~= 4 1
[5 6] < [7 4] [1 0]
[5 6] < 6 [1 0]
106
More Sample Results of
Relational Operators
Operation Result
97 == 'a' 1
65 == 'A' 1
'B' == 66 1
32 == ' ' 1
41 == ')' 1
'a' == 'A' 0
'a' < 'B' 0
')' < 'A' 1
ASCII
values
(see
Slide
328)
Interesting side note:
ASCII values can be
used in arithmetic
expressions such as
>> 2 * ')'
ans =
82
107
Two Cautions About theUse of the == Operator
1. Do not confuse the equality relational operator ==
with the arithmetic assignment operator = .
Here is an example where both are used in the
same statement:
>> a = 'fate';
>> b = 'cake';
>> result = a == b
result =
0 1 0 1
108
Two Cautions About theUse of the == Operator
2. Beware of checking for the equality of two floating-
point numbers. Roundoff error during calculations
can cause two theoretically equal numbers to differ
enough so that the equality test fails. Example:
>> a = 0;
>> b = sin(pi);
>> a == b
ans =
0
MATLAB yields 1.2246e-16
instead of exactly 0!
109
Testing for the “Equality” of Two Values
Instead of comparing two floating-point values forexact equality, set up a test to determine if thenumbers are nearly equal to each other within somemargin that accounts for the amount of roundoff errorexpected during the calculation. Example:
>> a = 0;>> b = sin(pi);>> abs(a-b) < 1.0e-14ans = 1
Note: This problemdoes not occur whencomparing integers!
110
Logic Operators
• These permit combinations of relational tests toyield a composite “True” or “False” condition.
• Set of logical operators:
& AND
OR
xor Exclusive OR
∼∼∼∼ Not
111
Truth Table for Logic Operators
Inputs AND OR XOR NOT
i 1 i 2 i 1 & i 2 i 1 i 2 xor(i 1 , i 2) ∼∼∼∼i 1
0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0