Transcript Slide 1

An Engineer’s Guide to MATLAB
Chapter 1
AN ENGINEER’S GUIDE TO MATLAB
3rd Edition
CHAPTER 1
INTRODUCTION
Copyright © Edward B. Magrab 2009
1
An Engineer’s Guide to MATLAB
Chapter 1
Goal of Course
For you to be able to generate readable, compact,
and verifiably correct MATLAB programs that
obtain numerical solutions to a wide range of
physical and empirical models, and to display the
results with fully annotated graphics.
Copyright © Edward B. Magrab 2009
2
An Engineer’s Guide to MATLAB
Chapter 1
MATLAB founded in 1984 by Jack Little, Steve
Bangert, and Clive Moler
1985 - MIT bought 10 copies
1986 - MATLAB 2
1987 - MATLAB 3
1990 - Simulink 1
1994 - MATLAB 4
1996 - MATLAB 5
2000 - MATLAB 6
2004 - MATLAB 7
2009 – MATLAB 7.8 (2009a)
Copyright © Edward B. Magrab 2009
3
An Engineer’s Guide to MATLAB
Chapter 1
Chapter 1 – Objective
To introduce the fundamental characteristics of the
MATLAB environment and the language’s basic
syntax
Copyright © Edward B. Magrab 2009
4
An Engineer’s Guide to MATLAB
Chapter 1
MATLAB
• A computing language devoted to processing data in
the form of arrays of numbers (called matrices).
• Integrates computation and visualization into a
flexible computer environment, and provides a diverse
family of built-in functions that can be used to obtain
numerical solutions to a wide range of engineering
problems.
• Derives its name from MATrix LABoratory.
Copyright © Edward B. Magrab 2009
5
An Engineer’s Guide to MATLAB
Chapter 1
Some Suggestions on How to Use MATLAB
Use the Help files extensively.
This will minimize errors caused by incorrect syntax
and by incorrect or inappropriate application of a
MATLAB function.
Write scripts and functions in a text editor and save them
as M files.
This will save time, save the code, and greatly
facilitate the debugging process, especially if the
MATLAB editor/debugger is used.
Copyright © Edward B. Magrab 2009
6
An Engineer’s Guide to MATLAB
Chapter 1
Some Suggestions on How to Use MATLAB
Attempt to minimize the number of expressions
comprising scripts and functions.
This usually leads to a tradeoff between readability
and compactness, but it can encourage the search
for MATLAB functions and procedures that can
perform some of the steps faster and more directly.
When practical, use graphical output as the script or
function is being developed.
This usually shortens the code development process
by identifying potential coding errors and can
facilitate the understanding of the physical process
being modeled or analyzed.
Copyright © Edward B. Magrab 2009
7
An Engineer’s Guide to MATLAB
Chapter 1
Some Suggestions on How to Use MATLAB
Most importantly, verify by independent means that
the outputs from the scripts and functions are correct.
Copyright © Edward B. Magrab 2009
8
An Engineer’s Guide to MATLAB
Chapter 1
Notation Conventions
Variable/Function Name
User-created variable
Font
Times Roman
MATLAB function
Courier
User-created function
Times Roman
Bold
BeamRoots(a, x, k)
Numerical Value
Font
Example
Provided in program
Times Roman
5.672
Output to command window
or to a graphical display
Helvetica
5.672
Copyright © Edward B. Magrab 2009
Example
ExitPressure
a2, sig
cosh(x), pi
9
An Engineer’s Guide to MATLAB
Chapter 1
What We Will Cover in Chapter 1
The MATLAB Environment
Preliminaries: Command Window Management
Executing Expressions from the MATLAB Command
Window: Basic MATLAB Syntax
Clarification and Exceptions to MATLAB Syntax
MATLAB Functions
Creating Scripts and Executing Them from the
MATLAB Editor
Online Help
Symbolic Toolbox
Copyright © Edward B. Magrab 2009
10
An Engineer’s Guide to MATLAB
Chapter 1
Command Window, Command History, Workspace
Copyright © Edward B. Magrab 2009
11
An Engineer’s Guide to MATLAB
Chapter 1
Command Window, Command History, Workspace,
and Editor
Copyright © Edward B. Magrab 2009
12
An Engineer’s Guide to MATLAB
Chapter 1
Command Window and Editor
MATLAB command window (left) and editor (right)
after closing the command history and workspace windows
Copyright © Edward B. Magrab 2009
13
An Engineer’s Guide to MATLAB
Chapter 1
Clearing of Command Window and Workspace
MATLAB function
Description
clc
Clear the command window
clear
Removes variables from the
workspace (computer memory)
close all
Closes (deletes) all graphic
windows
format
Formats the display of numerical
output to the command window
format compact
Removes empty (blank) lines
Copyright © Edward B. Magrab 2009
14
An Engineer’s Guide to MATLAB
Chapter 1
These operation can also be done with
Copyright © Edward B. Magrab 2009
15
An Engineer’s Guide to MATLAB
Chapter 1
and with
format compact
format long e
format short
Copyright © Edward B. Magrab 2009
16
An Engineer’s Guide to MATLAB
Chapter 1
Results from Different Format Selections
Option
Display (number > 0)
Display (number < 0)
short
long
short e
long e
short g
long g
short eng
long eng
rational
hex
bank
444.4444
4.444444444444445e+002
4.4444e+002
4.444444444444445e+002
444.44
444.444444444444
444.4444e+000
444.444444444444e+000
4000/9
407bc71c71c71c72
444.44
0.0044
0.004444444444444
4.4444e-003
4.444444444444444e-003
0.0044444
0.00444444444444444
4.4444e-003
4.44444444444444e-003
1/225
3f723456789abcdf
0.00
Copyright © Edward B. Magrab 2009
17
An Engineer’s Guide to MATLAB
Chapter 1
Preferences Menu Selections: Font Size
Copyright © Edward B. Magrab 2009
18
An Engineer’s Guide to MATLAB
Chapter 1
MATLAB Variable Names
• 63 alphanumeric characters
• Start with uppercase or lowercase letter
Followed by any combination of uppercase and
lowercase letters, numbers, and the underscore
character (_)
• Case sensitive - junk different from junK
• Example –
exit_pressure or ExitPressure
• Length of variable names Tradeoff between easily recognizable identifiers and
readability of the resulting expressions
Copyright © Edward B. Magrab 2009
19
An Engineer’s Guide to MATLAB
Chapter 1
Keywords Reserved Explicitly for the MATLAB
Programming Language
break
case
catch
continue
else
elseif
end
for
function
Copyright © Edward B. Magrab 2009
global
if
otherwise
persistent
return
switch
try
while
20
An Engineer’s Guide to MATLAB
Chapter 1
Command Window Interaction
» p = 7.1
p=
7.1000
» x = 4.92
x=
4.9200
» k = -1.7
k=
-1.7000
Copyright © Edward B. Magrab 2009
User types and hits Enter
System response
User types and hits Enter
System response
User types and hits Enter
System response
21
An Engineer’s Guide to MATLAB
Chapter 1
Suppression of System Response - Semicolon
» p = 7.1;
» x = 4.92;
» k = -1.7;
»
Several Expressions Placed on One Line
p = 7.1, x = 4.92, k = 1.7
System response –
p=
7.1000
x=
4.9200
k=
-1.7000
»
Copyright © Edward B. Magrab 2009
Using semicolon
instead of commas
suppresses this output
22
An Engineer’s Guide to MATLAB
Chapter 1
Arithmetic Operators
Hierarchy
Level
( ) Parentheses
1
´ Prime (Apostrophe) 1
^ Exponentiation
2
* Multiplication
3
/ Division
3
+ Addition
4
 Subtraction
4
Copyright © Edward B. Magrab 2009
23
An Engineer’s Guide to MATLAB
Chapter 1
Parentheses
• Needed so that the mathematical operations are
performed on the proper collections of quantities
and in their proper order.
• Within each set of parentheses the mathematical
operation are performed from left to right on
quantities at the same hierarchical level.
These rules can help minimize the number of
parentheses.
Copyright © Edward B. Magrab 2009
24
An Engineer’s Guide to MATLAB
Chapter 1
Some Examples
Mathematical
expression
1 dcx+2
dcx + 2
(2/d)cx+2
(dcx + 2)/g2.7
dc x  2
Copyright © Edward B. Magrab 2009
MATLAB expression
1-d*c^(x+2)
d*c^x+2 or 2+d*c^x
(2/d)*c^(x+2) or 2/d*c^(x+2) or 2*c^(x+2)/d
(d*c^x+2)/g^2.7
sqrt(d*c^x+2) or (d*c^x+2)^0.5
25
An Engineer’s Guide to MATLAB
Chapter 1
Another Example
Consider
 1 
t 

 1 + px 
k
The MATLAB script is
p = 7.1; x = 4.92; k = 1.7; % Numerical values
% must be assigned first
t = (1/(1+p*x))^k
which results in
t=
440.8779
Copyright © Edward B. Magrab 2009
26
An Engineer’s Guide to MATLAB
Chapter 1
Syntax Clarification and Exceptions
Blanks
In an arithmetic expression, blanks can be employed
with no consequence – except when
expression appears in an array specification; that is,
between two brackets [ ]
Excluding blanks in assignment statements, variable
names on the right hand side of the equal sign must be
separated by
one of the arithmetic operators
a comma (,)
a semicolon (;)
Copyright © Edward B. Magrab 2009
27
An Engineer’s Guide to MATLAB
Chapter 1
Two Exceptions
(1) Complex Numbers: z = a +1jb or z = a +1ib (i = j =
-1)
Example
a = 2; b = 3;
z = (a+1j*b)*(4-7j)
Note:
Real and complex numbers can be mixed without any
special concerns.
Example 1
z = 4 + sqrt(-4)
System displays
z=
4.0000 + 2.0000i
Copyright © Edward B. Magrab 2009
Example 2
z = 1i^1i
System displays
z=
0.2079
28
An Engineer’s Guide to MATLAB
Chapter 1
(2) Exponential Form: x = 4.56102
x = 4.56e-2
or
x = 0.0456
or
x = 4.56*10^-2
Note:
Maximum number of digits that can follow the ‘e’ is 3.
Copyright © Edward B. Magrab 2009
29
An Engineer’s Guide to MATLAB
Chapter 1
System Assignment of Variable Names
Type in the command window
cos(pi/3)
The system responds with
ans =
0.5000
The variable ans can now be used as one would any
other variable. Then, typing in the command window
ans+2
the system responds with
ans =
2.5000
Copyright © Edward B. Magrab 2009
30
An Engineer’s Guide to MATLAB
Chapter 1
Scalars versus Arrays
MATLAB considers all variables as arrays of numbers –
• When using the five arithmetic operators, +, , *, /,
and ^, these operations have to obey the rules of
linear (matrix) algebra
• When the variables are scalar quantities [arrays of
one element (one row and one column)] the usual
rules of algebra apply
• One can operate on arrays of numbers and suspend
the rules of linear algebra by using dot operations
Copyright © Edward B. Magrab 2009
31
An Engineer’s Guide to MATLAB
Chapter 1
Some Elementary MATLAB Functions
Mathematical function
ex
ex  1 x << 1
x
ln(x) or loge(x)
log10(x)
|x|
signum(x)
loge(1+x) x << 1
n!
All prime numbers  n
Copyright © Edward B. Magrab 2009
MATLAB expression
exp(x)
expm1(x)
sqrt(x)
log(x)
log10(x)
abs(x)
sign(x)
log1p(x)
factorial(n)
primes(n)
32
An Engineer’s Guide to MATLAB
Chapter 1
Some MATLAB Constants and Special Quantities
Mathematical quantity or MATLAB
operation
expression
pi

i or j
1
eps
Floating point relative
accuracy
inf

NaN
0/0, 0×, /
realmax
Largest floating-point
number before overflow
realmin
Smallest floating-point
number before underflow
Copyright © Edward B. Magrab 2009
Comments
3.141592653589793
Indicates complex quantity.
 2.2210-16
Infinity
Undefined mathematical
operation
 1.7977e+308
 2.2251e-308
33
An Engineer’s Guide to MATLAB
Chapter 1
MATLAB Trigonometric and Hyperbolic Functions
Trigonometric
Function (radians) (degrees)
sin(x) sind(x)
sine
cos(x) cosd(x)
cosine
tangent
tan(x) tand(x)
secant
sec(x) secd(x)
cosecant csc(x) cscd(x)
cotangent cot(x) cotd(x)
†
Hyperbolic
Inverse
asin(x) sinh(x)
acos(x) cosh(x)
atan(x)† tanh(x)
asec(x) sech(x)
acsc(x) csch(x)
acot(x) coth(x)
Inverse
asinh(x)
acosh(x)
atanh(x)
asech(x)
acsch(x)
acoth(x)
atan2(y, x) is the four quadrant version.
Copyright © Edward B. Magrab 2009
34
An Engineer’s Guide to MATLAB
Chapter 1
Several Specialized Mathematical Functions
Mathematical
function
Ai(x)
Bi(x)
I(x)
J(x)
K(x)
Y(x)
B(x,w)
K(m), E(m)
erf(x), erfc(x)
E1(z)
(a)
Pnm ( x)
MATLAB
Expression
airy(0,x)
airy(2,x)
besseli(nu, x)
besselj(nu, x)
besselk(nu, x)
bessely(nu, x)
beta(x, w)
ellipke(m)
erf(x), erfc(x)
expint(x)
gamma(a)
legendre(n, x)
Copyright © Edward B. Magrab 2009
Description
Airy function
Airy function
Modified Bessel function of first kind
Bessel function of first kind
Modified Bessel function of second kind
Bessel function of second kind
Beta function
Complete elliptic integrals of 1st & 2nd kind
Error and complementary error function
Exponential integral
Gamma function
Associated Legendre function
35
An Engineer’s Guide to MATLAB
Chapter 1
Several Specialized Statistical Functions
Mathematical function MATLAB
Expression
maximum value of x
max(x)

mean(x)
median
median(x)
minimum value of x
min(x)
mode
mode(x)
 or s
std(x)
2
2
 or s
var(x)
Copyright © Edward B. Magrab 2009
Description
Largest element(s) in an array
Average or mean value of an array
Median value of an array
Smallest element(s) in an array
Most frequent values in an array
Standard deviation of an array
Variance of an array of values
36
An Engineer’s Guide to MATLAB
Chapter 1
MATLAB Relational Operators
Conditional
equal
not equal
less than
greater than
less than or equal
greater than or equal
Copyright © Edward B. Magrab 2009
Mathematical
symbol
=

<
>


MATLAB
symbol
==
~=
<
>
<=
>=
37
An Engineer’s Guide to MATLAB
Chapter 1
Example
For x = 0.1 and a = 0.5, determine the value of y when
y=
e  - πx  - sin( x )/cosh(a ) - ln e ( x + a )
The script is
x = 0.1; a = 0.5;
y = sqrt(abs(exp(-pi*x)-sin(x)/cosh(a)-log(x+a)))
When executed, the system returns
y=
1.0736
Copyright © Edward B. Magrab 2009
38
An Engineer’s Guide to MATLAB
Chapter 1
Decimal-to-Integer Conversion Functions
MATLAB
function
y = fix(x)
y = round(x)
y = ceil(x)
y = floor(x)
Copyright © Edward B. Magrab 2009
x
y
2.7
1.9
2.49-2.51j
2.7
1.9
2.492.51j
2.7
1.9
2.49  2.51j
2.7
1.9
2.49  2.51j
2.0000
1.0000
2.0000  2.0000i
3.0000
2.0000
2.0000  3.0000i
3.0000
1.0000
3.0000 - 2.0000i
2.0000
2.0000
2.0000  3.0000i
Description
Round toward
zero
Round to nearest
integer
Round toward
infinity
Round toward
minus infinity
39
An Engineer’s Guide to MATLAB
Chapter 1
Complex Number Manipulation Functions
MATLAB function
z = complex(a, b)
z
y
a + b*j -
Description
Form complex number;
a and b real
y = abs(z)
3 + 4j
5
y = conj(z)
3 + 4j
3  4j
Absolute value: a2  b2
Complex conjugate
y = real(z)
3 + 4j
3
Real part
y = imag(z)
3 + 4j
4
Imaginary part
y = angle(z)
a +b*j
atan2(b, a) Phase angle in radians:
  y  
Copyright © Edward B. Magrab 2009
40
An Engineer’s Guide to MATLAB
Chapter 1
Additional Special Characters and a
Summary of Their Usage
Character Name
Usage
.
Period
(a) Decimal point.
(b) Part of arithmetic operators to indicate a special type of vector or
matrix operation, called the dot operation, such as c = a.*b.
,
Comma
(a) Separator within parentheses of matrix elements such as b(2,7) and
functions such as besselj(1, x) or brackets creating vectors such as v =
[1, x] or the output of function arguments such as [x, s] = max(a).
(b) Placed at the end of an expression when several expressions appear on
one line.
;
Semicolon
(a) Suppresses display of the results when placed at end of an expression.
(b) Indicates the end of a row in matrix creation statement such as
m = [x y z; a b c].
:
Colon
(a) Separator in the vector creation expression x = a:b:c.
(b) For a matrix, z it indicates “all rows” when written as z(:,k) or “all
columns” when written as z(k,:).
Copyright © Edward B. Magrab 2009
41
An Engineer’s Guide to MATLAB
Chapter 1
Additional Special Characters and a Summary of Their
Usage
()
Parentheses (a) Denote subscript of an element of matrix z, where z(j, k) is the element
in row j and column k.
(b) Delimiters in mathematical expressions such as a^(b+c).
(c) Delimiters for the arguments of functions, such as sin(x).
[]
Brackets
Creates an array of numbers, either a vector or a matrix, or a string
(literal).
{}
Braces
Creates a cell matrix or structure.
%
Percentage Comment delimiter; used to indicate the beginning of a comment wherein
the MATLAB compiler ignores everything to its right. The exception is
when it is used inside a pair of quotes to define a string such as a = 'p1 =
14 % of the total'.
%%
Percentage Used to delimit the start and end of a cell in the MATLAB editor, which is a
portion of program code.
%{
Percentage Used to enclose a block of contiguous comment lines. Comments placed
and brace
between these delimiters do not have to be preceded by a %. However, no
text can be placed on the line containing these delimiters.
%}
Copyright © Edward B. Magrab 2009
42
An Engineer’s Guide to MATLAB
Chapter 1
Additional Special Characters and a Summary of Their
Usage
Character Name
'
…
@
\
Usage
Quote or
(a) 'Expression' indicates that Expression is a string (literal)
Apostrophe (b) Indicates the transpose of a vector or matrix.
Ellipsis
Continuation of a MATLAB expression to the next line. Used to create
code that is more readable.
Blank
Context dependent: either ignored, indicates a delimiter in a data creation
statement such as c = [a b], or is a character in a string statement.
At sign
Construct a function handle by placing @ before a function name, such as
@FunctionName.
Backslash
A mathematical operator to perform certain matrix operations.
Copyright © Edward B. Magrab 2009
43
An Engineer’s Guide to MATLAB
Chapter 1
Creating Programs and Executing Them from
the MATLAB Editor
When to use the editor 1. The program will contain more than a few lines of
code.
2. The program will be used again.
3. A permanent record is desired.
4. It is expected that occasional upgrading will be
required.
5. Substantial debugging is required.
6. One wants to transfer the listing to another person
or organization.
Copyright © Edward B. Magrab 2009
44
An Engineer’s Guide to MATLAB
Chapter 1
Additional Reasons •
Required when creating functions
•
Editor has many features
 Commenting/Un-commenting
lines
 Smart Indenting
 Parentheses checking
Comments
in green
Keywords
in blue
Smart
indent
Copyright © Edward B. Magrab 2009
Strings
in violet
45
An Engineer’s Guide to MATLAB
Chapter 1
Additional Reasons • Click one icon to save and run a program
(Must use Save As first time)
Save and Run icon
Copyright © Edward B. Magrab 2009
46
An Engineer’s Guide to MATLAB
Chapter 1
Additional Reasons Enabling M-Lint from the Preferences menu
Copyright © Edward B. Magrab 2009
47
An Engineer’s Guide to MATLAB
Chapter 1
Illustration of M-Lint
Red
square
Orange
bar
Red bar
With cursor placed on red bar,
this error message is displayed.
Copyright © Edward B. Magrab 2009
48
An Engineer’s Guide to MATLAB
Chapter 1
Additional Reasons –
Enabling the cell feature of the Editor
Copyright © Edward B. Magrab 2009
49
An Engineer’s Guide to MATLAB
Chapter 1
Illustration of Editing Cells
Run the
highlighted
cell
Run the
highlighted
cell and
advance to
the next cell
Selected cell is
highlighted
Second cell
Third cell
Copyright © Edward B. Magrab 2009
50
An Engineer’s Guide to MATLAB
Chapter 1
A Script or a Function Typically Has the
Following Attributes 1. Documentation:
Purpose and operations performed
Programmer's Name
Date originated
Date(s) revised
Description of the input(s): number, meaning, and
type
Description of the output(s): number, meaning, and
type
Copyright © Edward B. Magrab 2009
51
An Engineer’s Guide to MATLAB
Chapter 1
2. Input which includes numerous checks to ensure that all
input values have the qualities required for the
script/function to work properly.
3. Initialization where the appropriate variables are assigned their
numerical values.
4. Computation where the numerical evaluations are performed.
5. Output where the results are presented as graphical and/or
annotated numerical quantities.
Copyright © Edward B. Magrab 2009
52
An Engineer’s Guide to MATLAB
Chapter 1
Naming of Programs and Functions
File name follows that for variable names.
Must start with an upper or lower case letter followed
by up to 62 contiguous alphanumeric characters and
the underscore character.
No blank spaces are allowed in file names.
[This is different from what is allowed by the
Windows operating system]
A ‘.m’ suffix must be affixed to the file name –
Consequently, these files are called ‘M’ files
Copyright © Edward B. Magrab 2009
53
An Engineer’s Guide to MATLAB
Chapter 1
Saving/Executing (Running) M Files
Set Path window (File)
Change current path
to file being executed.
Copyright © Edward B. Magrab 2009
54
An Engineer’s Guide to MATLAB
Chapter 1
Accessing the Browser Window to Change Current
Path (Directory)
Clicking on this
icon brings up the
Browser
Copyright © Edward B. Magrab 2009
55
An Engineer’s Guide to MATLAB
Chapter 1
Example - Flow in a circular channel
d/2
2
d/2
Q=
Dc
Dc 
23/2 Dc5/2 g  θ - 0.5sin  2θ  
3/2
8 sinθ 1- cosθ 
5/2
d
1  cos 
2
Let d = 2 m, g = 9.8 m/s2, and  = 60 = /3. Then the script is
g = 9.8; d = 2; th = pi/3; % Input
Dc = d/2*(1-cos(th));
Qnum = 2^(3/2)*Dc^(5/2)*sqrt(g)*(th-0.5*sin(2*th))^(3/2);
Qden = 8*sqrt(sin(th))*(1-cos(th))^(5/2);
Q = Qnum/Qden % m^3/s
Copyright © Edward B. Magrab 2009
56
An Engineer’s Guide to MATLAB
Chapter 1
The various
MATLAB windows
after executing the
program
Copyright © Edward B. Magrab 2009
57
An Engineer’s Guide to MATLAB
Chapter 1
On-Line Help: Getting Started
Copyright © Edward B. Magrab 2009
58
An Engineer’s Guide to MATLAB
Chapter 1
On-Line Help: Desktop
Copyright © Edward B. Magrab 2009
59
An Engineer’s Guide to MATLAB
Chapter 1
On-Line Help:
Command Window
Copyright © Edward B. Magrab 2009
60
An Engineer’s Guide to MATLAB
Chapter 1
On-Line Help: When Function Name is Known
Type in
function name
Copyright © Edward B. Magrab 2009
61
An Engineer’s Guide to MATLAB
Chapter 1
On-Line Help: When Function Name Is Not Known
Type search entry
and press Enter
Copyright © Edward B. Magrab 2009
62
An Engineer’s Guide to MATLAB
Chapter 1
Symbolic Toolbox
The Symbolic Math Toolbox provides the capability
of manipulating symbols to perform algebraic,
matrix, and calculus operations symbolically
When one couples the results obtained from
symbolic operations with MATLAB’s ability to create
functions, one has a very effective means of
numerically evaluating symbolically obtained
expressions. This is introduced in Chapter 5.
Copyright © Edward B. Magrab 2009
63
An Engineer’s Guide to MATLAB
Chapter 1
We will illustrate by example –
• Syntax
• Variable precision arithmetic
• Taylor series expansions
• Differentiation and integration
• Limits
• Substitution
• Inverse Laplace transform
Copyright © Edward B. Magrab 2009
64
An Engineer’s Guide to MATLAB
Chapter 1
The shorthand way to create symbolic variables is with
syms a b c …
where a, b, and c are now symbolic variables.
The blanks between each variable are required
If the variables are restricted to being real variables,
then we modify this statement as
syms a b c real
These symbols can be intermixed with non-symbolic
variable names, numbers, and MATLAB functions, with
the result being a symbolic expression.
Copyright © Edward B. Magrab 2009
65
An Engineer’s Guide to MATLAB
Chapter 1
Consider the expression
f = 11.92e
- a2
+ b/d
Assuming that d = 4.2 (1/d = 0.238095), the script to
represent this expression symbolically is
syms a b
d = 4.2;
f = 11.92*exp(-a^2)+b/d
which, upon execution, displays
f=
298/25*exp(-a^2)+5/21*b
where f is a symbolic object.
Copyright © Edward B. Magrab 2009
Note that:
21/5 = 4.2
298/25 = 11.92
66
An Engineer’s Guide to MATLAB
Chapter 1
Numbers in a symbolic expression are converted to the
ratio of two integers, when possible.
If the decimal representation of numbers is desired, then
one uses
vpa(f, n)
where f is the symbolic expression and n is the number of
digits.
Thus, to revert to the decimal notation with five decimal
digits, the script becomes
syms a b
d = 4.2;
f = vpa(11.92*exp(-a^2)+b/d, 5)
Copyright © Edward B. Magrab 2009
f = 11.92e
- a2
+ b/d
67
An Engineer’s Guide to MATLAB
which yields
f=
11.920*exp(-1.*a^2)+.23810*b
Chapter 1
Note:
1/d = 1/4.2 = 0.2381
Variable Precision Arithmetic
One can also use vpa to calculate quantities with
more than 15 digits of accuracy as follows
vpa('Expression', n)
where Expression is a valid MATLAB symbolic
relation and n is the desired number of digits of
precision.
Copyright © Edward B. Magrab 2009
68
An Engineer’s Guide to MATLAB
Chapter 1
Consider the evaluation of the following expression
y  32! e100
The script to evaluate this relation with 50 digits of precision
is
y = vpa('factorial(32)-exp(100)', 50)
Its execution gives
y=
-26881171155030517550432725348582123713611118.773742
If variable precision arithmetic had not been used, then
y = 2.688117115503052×1043
Copyright © Edward B. Magrab 2009
69
An Engineer’s Guide to MATLAB
Chapter 1
Symbolic Differentiation and Integration
Differentiation is performed with the function
diff(f, x, n)
where
f = f(x) is a symbolic expression
x = variable with which differentiation is performed
n = number of differentiations to be performed
For example, when n = 2 the second
derivative is taken
Copyright © Edward B. Magrab 2009
70
An Engineer’s Guide to MATLAB
Chapter 1
Example
We shall take the derivative of bcos(bt), first with
respect to t and then with respect to b.
The script is
syms b t
dt = diff(b*cos(b*t), t, 1)
db = diff(b*cos(b*t), b, 1)
Upon execution, we obtain
dt =
-b^2*sin(b*t)
db =
cos(b*t)-b*sin(b*t)*t
Copyright © Edward B. Magrab 2009
71
An Engineer’s Guide to MATLAB
Chapter 1
Integration is performed with the function
int(f, x, c, d)
where
f = f(x) is a symbolic expression
x = variable of integration
c = lower limit of integration
d = upper limit of integration
When c and d are omitted, the application of int results in
the indefinite integral of f(x)
Copyright © Edward B. Magrab 2009
72
An Engineer’s Guide to MATLAB
Chapter 1
Example
We shall integrate the results of the differentiation
performed previously. Thus,
syms b t
f = b*cos(b*t);
dt = diff(f, t, 1);
db = diff(f, b, 1);
it = int(dt, t)
ib = int(db, b)
The execution results in
it =
b*cos(b*t)
ib =
b*t*cos(b*t))
Copyright © Edward B. Magrab 2009
73
An Engineer’s Guide to MATLAB
Chapter 1
Limits
One can take the limit of a symbolic expression using
limit(f, x, z)
where
f = f(x) is the symbolic function
x = symbolic variable that is to assume the limiting
value z
Example
Determine the limit of
 2a  b 
Lim 

a  3a  4


Copyright © Edward B. Magrab 2009
74
An Engineer’s Guide to MATLAB
Chapter 1
The script is
syms a b
Lim = limit((2*a+b)/(3*a-4), a, inf)
 2a  b 
Lim 

a  3a  4


where inf = 
Example
Determine the limit of
y

Lim 1  
x 
x

Copyright © Edward B. Magrab 2009
x
75
An Engineer’s Guide to MATLAB
The script is
syms y x
Lim = limit((1+y/x)^x, x, inf)
Chapter 1
y

Lim 1  
x 
x

x
Upon execution, we obtain
Lim =
exp(y)
In other words, the limit is ey.
Copyright © Edward B. Magrab 2009
76
An Engineer’s Guide to MATLAB
Chapter 1
Taylor Series Expansion
An n-term Taylor series expansion of a function f(x)
about the point a is given by
n 1
f ( k ) (a)
( x  a)

k!
k 0
k
The function that performs this operation is
taylor(f, n, a, x)
Copyright © Edward B. Magrab 2009
77
An Engineer’s Guide to MATLAB
Chapter 1
Example
Obtain a four-term expansion of cos about o. The
script is
syms x tho
Tay = taylor(cos(x), 4, tho, x)
Upon execution, we obtain
Tay =
cos(tho)-sin(tho)*(x-tho)-1/2*cos(tho)*(x-tho)^2
+1/6*sin(tho)*(x-tho)^3
That is,
1
1
2
3
coso  sin o  x  o   coso  x  o   sin o  x  o 
2
6
Copyright © Edward B. Magrab 2009
78
An Engineer’s Guide to MATLAB
Chapter 1
Substitution
To substitute one expression b for another
expression a, the following function is used
subs(f, a, b)
where f = f(a)
Inverse Laplace Transform
If the Laplace transform of a function f(t) is F(s),
where s is the Laplace transform parameter, then the
inverse Laplace transform is obtained from
ilaplace(F, s, t)
Copyright © Edward B. Magrab 2009
79
An Engineer’s Guide to MATLAB
Chapter 1
Example
Consider the expression
1
F ( s)  2
s  2 s  1
where 0 <  < 1.
The inverse Laplace transform is obtained from
syms s t z
f = ilaplace(1/(s^2+2*z*s+1), s, t)
The execution of this script gives
f=
exp(-t*z)*sinh(t*(z^2-1)^(1/2))/(z^2-1)^(1/2)
Copyright © Edward B. Magrab 2009
80
An Engineer’s Guide to MATLAB
Chapter 1
To simplify this expression, we make use of the following
change of variables
z^2-1   2 1   1   2   r 2
Then, a simplified expression can be obtained by
modifying the original script as follows
syms s t z r
f = ilaplace(1/(s^2+2*z*s+1), s, t)
f = simple(subs(f,(z^2-1), -r^2))
Upon execution, we obtain
f=
exp(-t*z)*sin(t*r)/r
Copyright © Edward B. Magrab 2009

e  t
1 
2

sin t 1   2

81
An Engineer’s Guide to MATLAB
Chapter 1
Example
Determine the curvature of the parametric curves
x  2b cos t  b cos 2t
y  2b sin t  b sin 2t
The curvature is determined from

xy  yx
2
2


x

y


3/ 2
where the prime denoted the derivative with respect to t.
The script is
Copyright © Edward B. Magrab 2009
82
An Engineer’s Guide to MATLAB
Chapter 1
syms t a b
x = 2*b*cos(t) +b*cos(2*t);
y = 2*b*sin(t)-b*sin(2*t);
xp = diff(x, t, 1);
xpp = diff(x, t, 2);
yp = diff(y, t, 1);
ypp = diff(y, t, 2);
kn = xp*ypp-yp*xpp;
kd = xp^2+yp^2;
kn = factor(simple(kn));
kd = factor(simple(kd));
k = simple(kn/kd^(3/2))
The execution of this script gives
k=
-1/4/(2-2*cos(3*t))^(1/2)/b
Copyright © Edward B. Magrab 2009

1
4b 2  2cos3t
83
An Engineer’s Guide to MATLAB
Chapter 1
This result can be simplified with the following
trigonometric identity
1  cos a  2sin 2 (a / 2)
Then
2-2*cos(3*t)  2 1  cos3t   4sin 2 3t / 2
To make this final change, we employ subs as follows
k = simple(subs(k, 2-2*cos(3*t), 4*sin(3*t/2)^2))
to obtain
k=
-1/8/sin(3/2*t)/b
Copyright © Edward B. Magrab 2009

1
8b sin(3t / 2)
84