Вы находитесь на странице: 1из 84

An Engineers Guide to MATLAB Chapter 1

AN ENGINEERS GUIDE TO MATLAB


3rd Edition

CHAPTER 1
INTRODUCTION

Copyright Edward B. Magrab 2009 1


An Engineers 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 Engineers 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 Engineers Guide to MATLAB Chapter 1

Chapter 1 Objective
To introduce the fundamental characteristics of the
MATLAB environment and the languages basic
syntax

Copyright Edward B. Magrab 2009 4


An Engineers 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 Engineers 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 Engineers 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 Engineers 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 Engineers Guide to MATLAB Chapter 1

Notation Conventions
Variable/Function Name Font Example
User-created variable Times Roman ExitPressure
a2, sig
MATLAB function Courier cosh(x), pi
User-created function Times Roman BeamRoots(a, x, k)
Bold
Numerical Value Font Example
Provided in program Times Roman 5.672
Output to command window Helvetica 5.672
or to a graphical display

Copyright Edward B. Magrab 2009 9


An Engineers 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 Engineers Guide to MATLAB Chapter 1
Command Window, Command History, Workspace

Copyright Edward B. Magrab 2009 11


An Engineers Guide to MATLAB Chapter 1
Command Window, Command History, Workspace,
and Editor

Copyright Edward B. Magrab 2009 12


An Engineers 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 Engineers 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 Engineers Guide to MATLAB Chapter 1

These operation can also be done with

Copyright Edward B. Magrab 2009 15


An Engineers Guide to MATLAB Chapter 1

and with

format compact

format long e

format short

Copyright Edward B. Magrab 2009 16


An Engineers Guide to MATLAB Chapter 1

Results from Different Format Selections

Option Display (number > 0) Display (number < 0)


short 444.4444 0.0044
long 4.444444444444445e+002 0.004444444444444
short e 4.4444e+002 4.4444e-003
long e 4.444444444444445e+002 4.444444444444444e-003
short g 444.44 0.0044444
long g 444.444444444444 0.00444444444444444
short eng 444.4444e+000 4.4444e-003
long eng 444.444444444444e+000 4.44444444444444e-003
rational 4000/9 1/225
hex 407bc71c71c71c72 3f723456789abcdf
bank 444.44 0.00

Copyright Edward B. Magrab 2009 17


An Engineers Guide to MATLAB Chapter 1

Preferences Menu Selections: Font Size

Copyright Edward B. Magrab 2009 18


An Engineers 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 Engineers Guide to MATLAB Chapter 1

Keywords Reserved Explicitly for the MATLAB


Programming Language

break global
case if
catch otherwise
continue persistent
else return
elseif switch
end try
for while
function

Copyright Edward B. Magrab 2009 20


An Engineers Guide to MATLAB Chapter 1

Command Window Interaction

p = 7.1 User types and hits Enter


p=
System response
7.1000
x = 4.92 User types and hits Enter
x=
System response
4.9200
k = -1.7 User types and hits Enter
k=
System response
-1.7000

Copyright Edward B. Magrab 2009 21


An Engineers 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 Using semicolon
x= instead of commas
4.9200 suppresses this output
k=
-1.7000

Copyright Edward B. Magrab 2009 22


An Engineers 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 Engineers 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 Engineers Guide to MATLAB Chapter 1

Some Examples

Mathematical
expression MATLAB expression
1 dcx+2 1-d*c^(x+2)
dcx + 2 d*c^x+2 or 2+d*c^x
(2/d)cx+2 (2/d)*c^(x+2) or 2/d*c^(x+2) or 2*c^(x+2)/d
(dcx + 2)/g2.7 (d*c^x+2)/g^2.7
dc x 2 sqrt(d*c^x+2) or (d*c^x+2)^0.5

Copyright Edward B. Magrab 2009 25


An Engineers Guide to MATLAB Chapter 1

Another Example
Consider
k
1
t
1 + px
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 Engineers 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 Engineers 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 Example 2
z = 4 + sqrt(-4) z = 1i^1i
System displays System displays
z= z=
4.0000 + 2.0000i 0.2079
Copyright Edward B. Magrab 2009 28
An Engineers Guide to MATLAB Chapter 1

(2) Exponential Form: x = 4.56102

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 Engineers 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 Engineers 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 Engineers Guide to MATLAB Chapter 1

Some Elementary MATLAB Functions

Mathematical function MATLAB expression


ex exp(x)
ex 1 x << 1 expm1(x)
x sqrt(x)
ln(x) or loge(x) log(x)
log10(x) log10(x)
|x| abs(x)
signum(x) sign(x)
loge(1+x) x << 1 log1p(x)
n! factorial(n)
All prime numbers n primes(n)

Copyright Edward B. Magrab 2009 32


An Engineers Guide to MATLAB Chapter 1

Some MATLAB Constants and Special Quantities

Mathematical quantity or MATLAB Comments


operation expression
pi 3.141592653589793
1 i or j Indicates complex quantity.
Floating point relative eps 2.2210-16
accuracy
inf Infinity
0/0, 0, / NaN Undefined mathematical
operation
Largest floating-point realmax 1.7977e+308
number before overflow
Smallest floating-point realmin 2.2251e-308
number before underflow

Copyright Edward B. Magrab 2009 33


An Engineers Guide to MATLAB Chapter 1

MATLAB Trigonometric and Hyperbolic Functions

Trigonometric Hyperbolic
Function (radians) (degrees) Inverse Inverse
sine sin(x) sind(x) asin(x) sinh(x) asinh(x)
cosine cos(x) cosd(x) acos(x) cosh(x) acosh(x)
tangent tan(x) tand(x) atan(x) tanh(x) atanh(x)
secant sec(x) secd(x) asec(x) sech(x) asech(x)
cosecant csc(x) cscd(x) acsc(x) csch(x) acsch(x)
cotangent cot(x) cotd(x) acot(x) coth(x) acoth(x)

atan2(y, x) is the four quadrant version.

Copyright Edward B. Magrab 2009 34


An Engineers Guide to MATLAB Chapter 1

Several Specialized Mathematical Functions

Mathematical MATLAB Description


function Expression
Ai(x) airy(0,x) Airy function
Bi(x) airy(2,x) Airy function
I(x) besseli(nu, x) Modified Bessel function of first kind
J(x) besselj(nu, x) Bessel function of first kind
K(x) besselk(nu, x) Modified Bessel function of second kind
Y(x) bessely(nu, x) Bessel function of second kind
B(x,w) beta(x, w) Beta function
K(m), E(m) ellipke(m) Complete elliptic integrals of 1st & 2nd kind
erf(x), erfc(x) erf(x), erfc(x) Error and complementary error function
E1(z) expint(x) Exponential integral
(a) gamma(a) Gamma function
Pnm ( x) legendre(n, x) Associated Legendre function

Copyright Edward B. Magrab 2009 35


An Engineers Guide to MATLAB Chapter 1

Several Specialized Statistical Functions

Mathematical function MATLAB Description


Expression
maximum value of x max(x) Largest element(s) in an array
mean(x) Average or mean value of an array
median median(x) Median value of an array
minimum value of x min(x) Smallest element(s) in an array
mode mode(x) Most frequent values in an array
or s std(x) Standard deviation of an array
or s
2 2
var(x) Variance of an array of values

Copyright Edward B. Magrab 2009 36


An Engineers Guide to MATLAB Chapter 1

MATLAB Relational Operators

Conditional Mathematical MATLAB


symbol symbol
equal = ==
not equal ~=
less than < <
greater than > >
less than or equal <=
greater than or equal >=

Copyright Edward B. Magrab 2009 37


An Engineers Guide to MATLAB Chapter 1

Example
For x = 0.1 and a = 0.5, determine the value of y when

e
- x
y= - sin( x )/cosh(a ) - lne ( 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 Engineers Guide to MATLAB Chapter 1

Decimal-to-Integer Conversion Functions

MATLAB x y Description
function
2.7 2.0000
y = fix(x) 1.9 1.0000 Round toward
2.49-2.51j 2.0000 2.0000i zero
2.7 3.0000
y = round(x) 1.9 2.0000 Round to nearest
2.492.51j 2.0000 3.0000i integer
2.7 3.0000
y = ceil(x) 1.9 1.0000 Round toward
2.49 2.51j 3.0000 - 2.0000i infinity
2.7 2.0000
y = floor(x) 1.9 2.0000 Round toward
2.49 2.51j 2.0000 3.0000i minus infinity

Copyright Edward B. Magrab 2009 39


An Engineers Guide to MATLAB Chapter 1

Complex Number Manipulation Functions

MATLAB function z y Description


z = complex(a, b) a + b*j - Form complex number;
a and b real
y = abs(z) 3 + 4j 5 Absolute value: a 2 b2
y = conj(z) 3 + 4j 3 4j 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 Engineers 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 Engineers 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 Engineers 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 Engineers 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 Engineers 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 Strings
in violet

Copyright Edward B. Magrab 2009 45


An Engineers 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 Engineers Guide to MATLAB Chapter 1

Additional Reasons -
Enabling M-Lint from the Preferences menu

Copyright Edward B. Magrab 2009 47


An Engineers 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 Engineers Guide to MATLAB Chapter 1

Additional Reasons
Enabling the cell feature of the Editor

Copyright Edward B. Magrab 2009 49


An Engineers Guide to MATLAB Chapter 1

Illustration of Editing Cells

Run the
highlighted
cell

Run the Selected cell is


highlighted highlighted
cell and
advance to
the next cell Second cell

Third cell

Copyright Edward B. Magrab 2009 50


An Engineers 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 Engineers 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 Engineers 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 Engineers 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 Engineers 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 Engineers Guide to MATLAB Chapter 1

Example - Flow in a circular channel

d/2 2 d/2
23/2 Dc5/2 g - 0.5sin 2
3/2

Q=
8 sin 1 - cos
5/2

Dc
d
Dc 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 Engineers Guide to MATLAB Chapter 1

The various
MATLAB windows
after executing the
program

Copyright Edward B. Magrab 2009 57


An Engineers Guide to MATLAB Chapter 1

On-Line Help: Getting Started

Copyright Edward B. Magrab 2009 58


An Engineers Guide to MATLAB Chapter 1

On-Line Help: Desktop

Copyright Edward B. Magrab 2009 59


An Engineers Guide to MATLAB Chapter 1

On-Line Help:
Command Window

Copyright Edward B. Magrab 2009 60


An Engineers Guide to MATLAB Chapter 1

On-Line Help: When Function Name is Known


Type in
function name

Copyright Edward B. Magrab 2009 61


An Engineers 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 Engineers 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 MATLABs 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 Engineers 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 Engineers 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 Engineers Guide to MATLAB Chapter 1

Consider the expression


- a2
f = 11.92e + 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= Note that:
298/25*exp(-a^2)+5/21*b 21/5 = 4.2
where f is a symbolic object. 298/25 = 11.92

Copyright Edward B. Magrab 2009 66


An Engineers 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;
- a2
f = vpa(11.92*exp(-a^2)+b/d, 5) f = 11.92e + b/d

Copyright Edward B. Magrab 2009 67


An Engineers Guide to MATLAB Chapter 1

which yields Note:


f= 1/d = 1/4.2 = 0.2381
11.920*exp(-1.*a^2)+.23810*b

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 Engineers 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.6881171155030521043

Copyright Edward B. Magrab 2009 69


An Engineers 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 Engineers 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 Engineers 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 Engineers 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 Engineers 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 Engineers Guide to MATLAB Chapter 1

The script is 2a b
Lim
a
3a 4
syms a b
Lim = limit((2*a+b)/(3*a-4), a, inf)
where inf =

Example
Determine the limit of
x
y
Lim 1
x
x

Copyright Edward B. Magrab 2009 75


An Engineers Guide to MATLAB Chapter 1

The script is x
y
Lim 1
syms y x x
x
Lim = limit((1+y/x)^x, x, inf)
Upon execution, we obtain
Lim =
exp(y)
In other words, the limit is ey.

Copyright Edward B. Magrab 2009 76


An Engineers 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)

k 0
( x a)k

k!
The function that performs this operation is
taylor(f, n, a, x)

Copyright Edward B. Magrab 2009 77


An Engineers 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
cos o sin o x o cos o x o sin o x o
2 3

2 6

Copyright Edward B. Magrab 2009 78


An Engineers 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 Engineers 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 Engineers 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
e t
1 2

sin t 1 2

Copyright Edward B. Magrab 2009 81


An Engineers 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


xy y x

x 2 y 2
3/ 2

where the prime denoted the derivative with respect to t.


The script is

Copyright Edward B. Magrab 2009 82


An Engineers 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

-1/4/(2-2*cos(3*t))^(1/2)/b 4b 2 2cos3t
Copyright Edward B. Magrab 2009 83
An Engineers 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

-1/8/sin(3/2*t)/b 8b sin(3t / 2)

Copyright Edward B. Magrab 2009 84

Вам также может понравиться