matlab symbolic math toolbox
TRANSCRIPT
-
8/6/2019 MATLAB Symbolic Math Toolbox
1/300
Computation
Visualization
Programming
For Use with MATLAB
Users Gu ideVersion 2
Symbolic MathToolbox
-
8/6/2019 MATLAB Symbolic Math Toolbox
2/300
How to Contact The MathWorks:
508-647-7000 P h on e
508-647-7001 F a x
Th e Ma th Wor ks, In c. Ma il
24 Prime Park Way
Natick, MA 01760-1500
http://www.mathworks.com Web
ftp.mathworks.com Anonymous FTP server
comp.soft-sys.matlab Newsgroup
[email protected] Techn ical support
[email protected] Product enhancement suggestions
[email protected] Bug reports
[email protected] Documentation error reports
[email protected] Subscribing user registration
[email protected] Order status, license renewals, passcodes
[email protected] Sales, pricing, an d genera l informa tion
S ymb olic Mat h T oolbox Users Guid e
COPYRIGHT 1993 - 1998 by The MathWorks, Inc.The softwar e described in this document is furnished un der a license agreement. The software m ay be usedor copied only under the t erms of the license agreement. No part of this manu al ma y be photocopied or repro-duced in a ny form without pr ior wr itten consent from The MathWorks, Inc.
U.S. GOVERNMENT: If Licensee is acquiring the Programs on behalf of any un it or agency of the U.S.Government , the following shall apply: (a) For un its of the Depart ment of Defense: the Governm ent sh allhave only the rights specified in t he license u nder which the commercial computer softwar e or commer cialsoftware documentat ion was obtained, as set forth in su bparagra ph (a) of the Rights in CommercialComput er Software or Commer cial Software Document ation Clause at DFARS 227.7202-3, therefore t herights set forth h erein shall apply; and (b) For an y other unit or agency: NOTICE: Notwithst anding anyother lease or license a greement t hat may pert ain t o, or a ccompany th e delivery of, the computer softwar e
and accompanying document ation, the r ights of the Governm ent r egarding its u se, reproduction, and disclo-sure are as set forth in Clause 52.227-19 (c)(2) of the FAR.
MATLAB, Simulink, Stat eflow, Han dle Graphics, and Real-Time Workshop are r egistered t radema rks, an dTarget Language Compiler is a trademark of The MathWorks, Inc.
Other product or brand names are trademarks or registered trademarks of their respective holders.
P r i n t in g H i st or y : Au g u s t 1 99 3 F i r st p r in t i n g
O ct ob er 1 99 4 S econ d p r in t i n g
M a y 1 99 7 T h ir d p r in t i n g for S ym b ol ic M a t h T ool box 2 .0
September 1998 Updated for Release 11 (online only)
-
8/6/2019 MATLAB Symbolic Math Toolbox
3/300
i
Contents
1
T u t o r i a l
I n t r o d u c t i o n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
G e t t i n g H e l p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4
G e t t i n g S t a r t e d . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5
Symbolic Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5Creating Symbolic Variables an d Expressions . . . . . . . . . . . . . 1-6
Symbolic and N um eric Conversions . . . . . . . . . . . . . . . . . . . . . . 1-7
Constr ucting Real a nd Complex Variables . . . . . . . . . . . . . . 1-9
Creating Abstr act Fu nctions . . . . . . . . . . . . . . . . . . . . . . . . 1-10
Using sym to Access Ma ple Fu nctions . . . . . . . . . . . . . . . . . 1-11
Exam ple: Crea ting a Symbolic Mat rix . . . . . . . . . . . . . . . . . 1-11
The Default Symbolic Var iable . . . . . . . . . . . . . . . . . . . . . . 1-13
Creating Symbolic Math Fu nctions . . . . . . . . . . . . . . . . . . . . . 1-15
Using S ymbolic Expr essions . . . . . . . . . . . . . . . . . . . . . . . . . 1-15
Creating a n M-File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-16
C a l c u l u s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-17
Differentia tion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-17
Limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-21
Integra tion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-23Integra tion with Real Consta nts . . . . . . . . . . . . . . . . . . . . . 1-26
Real Varia bles via sym . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-28
Symbolic Summ at ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-30
Taylor Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-31
Extended Calculus E xample . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-33
Plotting Symbolic Fun ctions . . . . . . . . . . . . . . . . . . . . . . . . . 1-33
-
8/6/2019 MATLAB Symbolic Math Toolbox
4/300
i i
S i m p l i f i c a t i o n s a n d S u b s t i t u t i o n s . . . . . . . . . . . . . . . . . . . . . 1-47
Simplificat ions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-47
collect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-48
expand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-49horner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-49
factor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-50
simplify . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-52
simple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-52
Substitut ions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-56
subexpr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-56
subs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-59
V a ri a bl e-P reci s i o n A ri thm eti c . . . . . . . . . . . . . . . . . . . . . . . . . 1-64
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-64
Example: Using th e Different Kinds of Arithm etic . . . . . . . . . 1-65
Rat iona l Arithm etic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-65
Var iable-Pr ecision Num bers . . . . . . . . . . . . . . . . . . . . . . . . . 1-66
Converting to Floating-Point . . . . . . . . . . . . . . . . . . . . . . . . 1-67
Another E xample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-67
Li nea r A l g ebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-69
Basic Algebra ic Opera tions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-69
Linear Algebraic Operat ions . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-70
Eigenvalues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-74
J orda n Canonical F orm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-81
Singular Value Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . 1-82
Eigenvalue Tr ajectories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-86
S o l v i n g E q u a t i o n s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-96
Solving Algebra ic Equ at ions . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-96
Several Algebra ic Equ at ions . . . . . . . . . . . . . . . . . . . . . . . . . . 1-104
Single Differen tial E qua tion . . . . . . . . . . . . . . . . . . . . . . . . . . 1-107
Exam ple 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-108
Exam ple 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-108Exam ple 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-109
Several Differential E quat ions . . . . . . . . . . . . . . . . . . . . . . . . 1-109
I n t e g r a l T r a n s f o r m s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-112
The Fourier and In verse Fourier Tra nsforms . . . . . . . . . . . . 1-112
The Laplace and In verse Laplace Transforms . . . . . . . . . . . . 1-120
-
8/6/2019 MATLAB Symbolic Math Toolbox
5/300
-
8/6/2019 MATLAB Symbolic Math Toolbox
6/300
iv Contents
-
8/6/2019 MATLAB Symbolic Math Toolbox
7/300
1
Tutorial
I n t r o d u c t i o n . . . . . . . . . . . . . . . . . . . . 1-2
G e t t i n g H e l p . . . . . . . . . . . . . . . . . . . . 1-4
Ge tt i n g S t a rte d . . . . . . . . . . . . . . . . . . 1-5
C a l c u l u s . . . . . . . . . . . . . . . . . . . . . . 1-17
S i m p l i f i c a t i o n s a n d S u b s t i t u t i o n s . . . . . . . . . . 1-47
Va ri a b le -P re ci s io n Ari th m e tic . . . . . . . . . . . 1-64
Li nea r A l g ebra . . . . . . . . . . . . . . . . . . . 1-69
S o l v i n g E q u a t i o n s . . . . . . . . . . . . . . . . . 1-96
I n t e g r a l T r a n s f o r m s . . . . . . . . . . . . . . . 1-112
S p e c i a l M a t h e m a t i c a l F u n c t i o n s . . . . . . . . . . 1-130
U s i n g M a p l e F u n c t i o n s . . . . . . . . . . . . . . 1-136
E x t e n d e d S y m b o l i c Ma t h T o o l b o x . . . . . . . . . 1-143
-
8/6/2019 MATLAB Symbolic Math Toolbox
8/300
1 Tutorial
1-2
IntroductionThe Symbolic Math Toolboxes incorpora te symbolic computa tion int o
MATLABs nu mer ic envir onmen t. Th ese t oolboxes su ppleme nt MATLABs
numer ic and gra phical facilities with several oth er t ypes of mat hema tical
computation:
The computational engine underlying the toolboxes is the kernel of Maple, asystem developed primarily at the University of Waterloo, Canada, and, more
recently, at the Eidgenssiche Technische Hochschule, Zrich, Switzerland.Maple is mar keted a nd supported by Waterloo Maple, Inc.
These versions of the Symbolic Mat h Toolboxes a re designed to work with
MATLAB 5 a nd Maple V Release 4.
There are two toolboxes. The basic Symbolic Math Toolbox is a collection of
more than one-hundred MATLAB functions that provide access to the Maple
Facility Covers
C alcu lu s Diffe ren t ia t ion , in t egr a t ion , lim it s, s um m a tion ,
and Taylor series
L in e a r Alg eb r a I n ve r s es , d e t er m i n a n t s, e ige n va l u es , s in gu l a r
value decomposition, an d canonical form s of
symbolic ma tr ices
Sim plification M ethods of sim plifying algebraic expressions
Solution of
Equations
Symbolic and numerical solutions to algebraic and
differential equations
Variable-Precision
Arithmetic
Numer ical evaluation of ma thema tical expressions
to a ny specified a ccur acy
Tr an sfor ms F ou rier , La pla ce, z-tran sform, an d corr esponding
inverse t ra nsforms
Special
Mathematical
Functions
Special functions of classical a pplied ma th ema tics
-
8/6/2019 MATLAB Symbolic Math Toolbox
9/300
Introduction
1-3
kernel using a synta x and st yle tha t is a nat ura l extension of the MATLABlan gua ge. The ba sic toolbox also allows you t o access fun ctions in Ma ples
linear algebra package. The Extended Symbolic Math Toolbox augments this
functiona lity to include a ccess t o all nongra phics Maple packa ges, Maple
program ming featu res, a nd user -defined pr ocedures. With both toolboxes, you
can wr ite your own M-files t o access Maple fun ctions an d t he Ma ple work space.
The following sections of th is Tut orial pr ovide explan at ion an d exam ples on
how to u se t he toolboxes.
Cha pter 2, Referen ce, provides det ailed descriptions of each of the functions
in the toolboxes.
Section Covers
Gettin g Help How to get online h elp for Symbolic Mat h
Toolbox functions
Getting Sta rt ed Basic symbolic ma th opera tions
Calculus How to differentiate and integrate symbolicexpressions
Simplifications and
Substitutions
How to simplify an d su bstitute values into
expressions
Variable-Precision
Arithmetic
How to cont rol th e pr ecision of
computations
Linear Algebra Exam ples usin g th e t oolbox functions
Solving Equ at ions How to solve symbolic equations
Integral Tran sforms Four ier, Lapla ce, an d z-transforms
Special Mathematical
Functions
How to a ccess Ma ples special ma th
functions
Using Maple Functions How to us e Ma ple s h elp, debugging, and
user-defined procedur e fun ctions
Exten ded S ymbolic Mat h
Toolbox
Featur es of the Extended Symbolic Math
Toolbox
-
8/6/2019 MATLAB Symbolic Math Toolbox
10/300
1 Tutorial
1-4
Getting HelpTher e ar e two ways t o find inform at ion on usin g Symbolic Mat h Toolbox
fun ctions. On e, of cour se, is to rea d t his m an ua l! The oth er is t o use MATLABs
comman d line help syst em. Gener ally, you can obta in help on MATLAB
fun ctions simply by typing
help function
where function is the name of the MATLAB function for which you need help.This is n ot su fficient , however, for s ome Symbolic Mat h Toolbox functions. Th e
rea son? The Symbolic Ma th Toolbox overloads ma ny of MATLABs n um er ic
fun ctions. Tha t is, it provides symbolic-specific implement at ions of th e
functions, using the same function name. To obtain help for the symbolic
version of an overloaded function, type
help sym/function
where function is th e overloaded functions n am e. For exam ple, to obta in h elpon the symbolic version of the overloaded function, diff, type
help sym/diff
To obtain information on the numeric version, on the other hand, simply type
help diff
How can you tell whether a function is overloaded? The help for the numeric
version t ells you so. For example, th e help for th e diff function contains thesection
Overloaded methods
help char/diff.m
help sym/diff.m
This tells you t hat ther e ar e two other diff comma nds t hat operat e on
expressions of class char and class sym, respectively. See t he next section for
inform at ion on class sym. For m ore inform at ion on overloaded comm an ds, see
Chapt er 14 of the U s i n g M A T L A B guide.
You can use the mhelp command to obtain help on Maple commands. For
example, to obtain help on the Maple diff comma nd, type mhelp diff. This
retur ns t he help page for t he Maple diff fun ction. For m ore inform at ion on th e
-
8/6/2019 MATLAB Symbolic Math Toolbox
11/300
Getting Started
1-5
mhelp command, type help mhelp or rea d th e section Using Ma ple Fu nctionsin th is Tutorial.
Getting Started
This section describes how to crea te an d u se symbolic objects. It also describes
the default symbolic variable. If you are familiar with version 1 of the Symbolic
Math Toolbox, please note that version 2 uses substantially different and
simpler syntax.
(If you already have a copy of the Maple V Release 4 library, please see the
reference pa ge for mapleinit before proceeding.)
To get a quick online introduction to the Symbolic Math Toolbox, type demos a t
th e MATLAB comm an d line. MATLAB displays t he MATLAB Dem os dialog
box. Select Sy m bo l i c Ma t h (in t he left list box) an d th en Int r o duc t i o n (in the
right list box).
Symbolic ObjectsThe S ymbolic Math Toolbox defines a new MATLAB da ta type called a
symbolic object or sym (see Chapter 14 in U s in g M A T L A B for a n int roduction
-
8/6/2019 MATLAB Symbolic Math Toolbox
12/300
1 Tutorial
1-6
to MATLAB classes a nd objects). Int ern ally, a sym bolic object is a dat astr uctu re th at s tores a str ing represen ta tion of th e symbol. The Symbolic Mat h
Toolbox us es symbolic objects to re pr esen t symbolic var iables, express ions , an d
matrices.
Creating Symbolic Variables and ExpressionsTh e sym command lets you construct symbolic variables and expressions. For
example, th e comma nds
x = sym('x')
a = sym('alpha')
create a symbolic variable x t h a t p r i n t s a s x and a symbolic variable a t h a t
prints as alpha.
Suppose you want to use a symbolic variable to represent the golden ra tio
The comma nd
rho = sym('(1 + sqrt(5))/2')
achieves this goal. Now you can perform various mathematical operations on
rho. For example
f = rho^2 rho 1f =
(1/2+1/2*5^(1/2))^2-3/2-1/2*5^(1/2)
simplify(f)
r e t u r n s
0
Now suppose you want to study t he qu adra tic fun ction f = ax2 + bx + c. The
statem ent
f = sym('a*x^2 + b*x + c')
assigns th e symbolic expression ax2 + bx + c to the variable f. Observe tha t in
th is case, th e Symbolic Mat h Toolbox does n ot creat e var iables corr esponding
1 5+2-----------------=
-
8/6/2019 MATLAB Symbolic Math Toolbox
13/300
Getting Started
1-7
to the term s of the expression, a, b, c, a n d x. To perform symbolic mat hopera tions (e.g., integra tion, different iation, subst itut ion, et c.) on f, you need
to create the variables explicitly. You can do this by typing
a = sym('a')
b = sym('b')
c = sym('c')
x = sym('x')
or simplysyms a b c x
In genera l, you can use sym or syms to creat e symbolic var iables. We
recommend you use syms because it requires less typing.
Symbolic and Numeric Conversions
Lets ret urn to the golden ra tio
Th e sym function has four options for returning a symbolic representation of
the num eric value rho = (1 + sqrt(5)/2). The 'f' option
sym(rho,'f')
returns a symbolic floating-point representation
'1.9e3779b97f4a8'*2^(0)
Th e 'r' option
sym(rho,'r')
returns the rational form
7286977268806824*2^(52)
1 5+
2-----------------=
-
8/6/2019 MATLAB Symbolic Math Toolbox
14/300
1 Tutorial
1-8
This is the default setting for sym. That is, calling sym without a secondargum ent is the sam e as using sym with t he 'r' option.
sym(rho)
ans =
7286977268806824*2^(52)
sym(.25)
ans =
1/4
The third option 'e' returns the rational form ofrho plus t he d ifference
between the theoretical rational expression for rho and its actual (machine)
float ing-point value in ter ms ofeps (th e float ing-point rela tive a ccur acy)
sym(rho,'e')
ans =
7286977268806824*2^(52)
In this case, the theoretical and actual floating-point values for rho a r e t h e
sam e. For 1/3, however, we obta in
sym(1/3,'e')
ans =1/3-eps/12
The four th option 'd' retu rns the decimal expansion ofrho up to the n um ber
of significant digits specified by digits.
sym(rho,'d')
ans =
1.6180339887498949025257388711907
-
8/6/2019 MATLAB Symbolic Math Toolbox
15/300
Getting Started
1-9
The default va lue ofdigits is 32 (hence, sym(rho,'d') return s a num ber with32 significant digits), but if you pr efer a s hort er r epresen ta tion, use the digits
command as follows.
digits(7)
sym(rho,'d')
ans =
1.618034
A par ticularly effective u se ofsym is to convert a mat rix from nu meric to
symbolic form . Th e comm an d
A = hilb(3)
generates the 3-by-3 Hilbert m atr ix.
A =
1.0000 0.5000 0.33330.5000 0.3333 0.2500
0.3333 0.2500 0.2000
By applying sym t oA
A = sym(A)
you can obtain the (infinitely precise) symbolic form of the 3-by-3 Hilbert
m atrix.
A =
[ 1, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
Constructing Real and Complex VariablesTh e sym command allows you to specify the mathematical properties ofsymbolic varia bles by using t he 'real' option. That is, the st at ements
x = sym('x','real'); y = sym('y','real');
-
8/6/2019 MATLAB Symbolic Math Toolbox
16/300
1 Tutorial
1-10
or more efficientlysyms x y real
z = x + i*y
crea te symbolic var iables x a n d y tha t h ave the added m ath em atical property
of being real variables. Specifically this means that the expression
f = x^2 + y^2
is strictly nonnegative. Hence, z is a (formal) complex var iable an d can bemanipulated as such. Thus, the commands
conj(x), conj(z), expand(z*conj(z))
return the complex conjugates of the variables
x, x i*y, x^2 + y^2
Th e conj comm an d is th e complex conjugat e operat or for th e t oolbox. If
conj(x) == x return s 1, then x is a r eal variable.
To clear x of its rea l propert y, you mu st type
syms x unreal
or
x = sym('x','unreal')
The comma nd
clear x
does n ot m a k e x a n onr eal variable.
Creating Abstract FunctionsIf you want to creat e a n abstr act (i.e., indetermina nt) function f(x), type
f = sym('f(x)')
Then f acts like f(x) and can be ma nipulated by t he toolbox comma nds. To
constr uct t he first difference ra tio, for example, type
df = (subs(f,'x','x+h') f)/'h'
-
8/6/2019 MATLAB Symbolic Math Toolbox
17/300
Getting Started
1-11
orsyms x h
df = (subs(f,x,x+h)f)/h
which returns
df =
(f(x+h)-f(x))/h
This a pplicat ion ofsym is useful when comput ing Fourier, Laplace, andz-transforms (see the section Int egra l Tran sforms).
Using sym to Access Maple FunctionsSimilarly, you can access Maples factorial function k!, using sym.
kfac = sym('k!')
To comp ut e 6! or n!, t ype
syms k n
subs(kfac,k,6), subs(kfac,k,n)
ans =
720
ans =
n!
Or, if you wan t to compu te, for example, 12!, simply use t he prod function
prod(1:12)
Example: Creating a Symbolic MatrixA circulan t ma tr ix ha s the pr opert y tha t each r ow is obta ined from th e previous
one by cyclically permuting the entries one step forward. We create the
circulant matrixA whose elements are a, b, a n d c, using the comma nds
syms a b c
A = [a b c; b c a; c a b]
-
8/6/2019 MATLAB Symbolic Math Toolbox
18/300
1 Tutorial
1-12
which returnA =
[ a, b, c ]
[ b, c, a ]
[ c, a, b ]
SinceA is circulant , the s um over ea ch row and column is the sa me. Lets check
this for the first row and second column. The command
sum(A(1,:))
r e t u r n s
ans =
a+b+c
The comma nd
sum(A(1,:)) == sum(A(:,2)) % This is a logical test.
r e t u r n s
ans =
1
Now replace th e (2,3) entr y ofA with beta and the variable b with alpha. The
commands
syms alpha beta;A(2,3) = beta;
A = subs(A,b,alpha)
r e t u r n
A =
[ a, alpha, c]
[ alpha, c, beta]
[ c, a, alpha]
From this example, you can see that using symbolic objects is very similar to
using regular MATLAB n um eric objects.
-
8/6/2019 MATLAB Symbolic Math Toolbox
19/300
Getting Started
1-13
The Default Symbolic VariableWhen m an ipulating ma thema tical functions, th e choice of the independentvariable is often clear from context. For example, consider the expressions in
the table below.
If we ask for th e derivat ives of th ese expressions, with out specifying th e
independent var iable, then by mat hemat ical convention we obtain f' = nxn ,
g' = a cos(a t + b), an d h ' = Jv(z)(v/z)Jv+1(z). Lets a ssume t ha t the independent
variables in t hese th ree expressions a re x, t, a n d z , resp ectively. The other
symbols, n , a , b, and v , are usu ally regar ded as consta nts or para meters. If,
however, we wanted to differentiate the first expression with respect to n , for
example, we could wr ite
or
to get xn ln x.
By mathematical convention, independent variables are often lower-case
letters found near the end of the Latin alphabet (e.g., x, y, or z). This is th e idea
behind findsym, a utility function in the toolbox used to determine default
symbolic varia bles. Defau lt symbolic varia bles ar e u tilized by t he calculus,
simplificat ion, equ at ion-solving, a nd tr an sform functions. To apply th is ut ility
to the example discussed above, type
syms a b n nu t x z
f = x^n; g = sin(a*t + b); h = besselj(nu,z);
This creates the symbolic expressions f, g, a n d h to mat ch t he example. To
differentiate these expressions, we use diff.
diff(f)
Mathematical Function MATLAB Command
f = xn f = x^n
g = sin(at+b) g = sin(a*t + b)
h = J v(z) h = besselj(nu,z)
d
d n-------f x( )
d
d n-------x
n
-
8/6/2019 MATLAB Symbolic Math Toolbox
20/300
1 Tutorial
1-14
r e t u r n sans =
x^n*n/x
See t he section Differentiation for a more det ailed discussion of
different iation an d th e diff command.
Her e, as a bove, we did not specify the varia ble with respect t o different iation.
How did the toolbox determine that we wanted to differentiate with respect to
x? The answer is the findsym command.
findsym(f,1)
which returns
ans =
x
Similarly, findsym(g,1) a n d findsym(h,1) r e t u r n t a n d z, respectively. Her e
the second a rgumen t offindsym denotes the number of symbolic variables we
wan t to find in t he symbolic object f, using the findsym rule (see below). The
absence of a second argument in findsym resu lts in a list of all symbolic
varia bles in a given symbolic expression. We see th is demonstr at ed below. The
command
findsym(g)
returns t he result
ans =
a, b, t
findsym Rule: The defau lt symbolic var iable in a symbolic expression is th eletter tha t is closest t o 'x' alph abet ically. If ther e ar e t wo equa lly close, th e
lett er later in the a lphabet is chosen.
-
8/6/2019 MATLAB Symbolic Math Toolbox
21/300
Getting Started
1-15
Here a re some exam ples:
Creating Symbolic Math FunctionsThere a re two ways to creat e functions:
Use symbolic expressions
Create an M-file
Using Symbolic ExpressionsThe sequ ence of comman ds
syms x y z
r = sqrt(x^2 + y^2 + z^2)
t = atan(y/x)
f = sin(x*y)/(x*y)
generates the symbolic expressions r, t, and f. You can use diff, int, subs,an d other Symbolic Mat h Toolbox fun ctions to ma nipulat e such express ions.
Expression Variable Returned Byfindsym
x^n x
sin(a*t+b) t
besselj(nu,z) z
w*y + v*z y
exp(i*theta) theta
log(alpha*x1) x1
y*(4+3*i) + 6*j y
sqrt(pi*alpha) alpha
-
8/6/2019 MATLAB Symbolic Math Toolbox
22/300
1 Tutorial
1-16
Creating an M-FileM-files perm it a more gener al u se of functions. Su ppose, for example, you wa ntto create the sinc function sin(x)/x. To do this, create an M-file in the @sym
directory.
function z = sinc(x)
%SINC The symbolic sinc function
% sin(x)/x. This function
% accepts a sym as the input argument.
if is equal(x,sym(0))z = 1;
else
z = sin(x)/x;
end
You can extend such examples to functions of several variables. For a more
detailed discussion on object-oriented programming, see Chapter 14 of the
U s in g M A T L A B guide.
-
8/6/2019 MATLAB Symbolic Math Toolbox
23/300
Calculus
1-17
CalculusThe Symbolic Math Toolboxes pr ovide functions to do t he basic opera tions of
calculus; differentiation, limits, integration, summation, and Taylor series
expansion. The following sections out line t hese functions.
DifferentiationLet s crea te a symbolic expre ssion.
syms a x
f = sin(a*x)
Then
df = diff(f)
differentiates f with respect to its symbolic variable (in this case x), as
determined by findsym.df =
cos(a*x)*a
To differentiat e with respect to th e var iable a, type
dfa = diff(f,a)
which returns d f / d a
dfa=
cos(a*x)*x
Mathematical Function MATLAB Command
f = xn
f' = nxn 1
f = x^n
diff(f) or diff(f,x)
g = acos(at+b)
g' = acos(at+b)
g = acos(a*t + b)
diff(g) or diff(g,t)
h = Jv(z)
h ' = Jv(z)(v/z) Jv+1 (z)
h = besselj(nu, z)
diff(h) or diff(h,z)
-
8/6/2019 MATLAB Symbolic Math Toolbox
24/300
1 Tutorial
1-18
To calculate the second derivatives with respect to x a n d a, r espectively, t ypediff(f,2) % or diff(f,x,2)
which returns
ans =
sin(a*x)*a^2
a n d
diff(f,a,2)
which returns
ans =
sin(a*x)*x^2
Define a, b, x, n, t, and thet a in th e MATLAB workspace, using the sym
comma nd. The table below illustr at es th e diff command.
To differentiate the Bessel function of the first kind, besselj(nu,z), with
respect t o z, type
syms nu z
b = besselj(nu,z);
db = diff(b)
which returns
db =besselj(nu+1,z)+nu/z*besselj(nu,z)
f diff(f)
x^n x^n*n/x
sin(a*t+b) a*cos(a*t+b)
exp(i*theta) i*exp(i*theta)
-
8/6/2019 MATLAB Symbolic Math Toolbox
25/300
Calculus
1-19
Th e diff fun ction can a lso ta ke a symbolic ma tr ix as its inpu t. In th is case, th edifferentiation is done element-by-element. Consider the example
syms a x
A = [cos(a*x),sin(a*x);sin(a*x),cos(a*x)]
which returns
A =
[ cos(a*x), sin(a*x)]
[ sin(a*x), cos(a*x)]
The comma nd
dy = diff(A)
r e t u r n s
dy =
[ sin(a*x)*a, cos(a*x)*a]
[ cos(a*x)*a, sin(a*x)*a]
You can a lso perform differentia tion of a column vector with respect t o a r ow
vector. Consider t he tr an sform at ion from Euclidean (x, y, z) to spherical (r, , )coordina tes a s given by x = r cos cos , y = r cos si n , and z = r si n . Notet h a t corresponds to elevation or latitude while denotes azimuth orlongitude.
z
y
x
(x,y,z)
r
-
8/6/2019 MATLAB Symbolic Math Toolbox
26/300
1 Tutorial
1-20
To calculate the J acobian m at rix,J
, of this tr ansforma tion, use the jacobianfunction. The mathematical notation for J is
=
For t he pur poses of toolbox synta x, we use l for a n d f for . The comma nds
syms r l f
x = r*cos(l)*cos(f); y = r*cos(l)*sin(f); z = r*sin(l);
J = jacobian([x; y; z], [r l f])
return the J acobian
J =
[ cos(l)*cos(f), r*sin(l)*cos(f), r*cos(l)*sin(f)]
[ cos(l)*sin(f), r*sin(l)*sin(f), r*cos(l)*cos(f)]
[ sin(l), r*cos(l), 0]
and t he com m an d
detJ = simple(det(J))
r e t u r n s
detJ =
cos(l)*r^2
Notice that the first argument of the jacobian function must be a column
vector an d th e second a rgum ent a row vector. Moreover, since th e determ ina nt
of the Jacobian is a rather complicated trigonometric expression, we used the
simple comma nd to ma ke tr igonometric substitutions an d r eductions
(simplifications). Th e se ction Simplifications and Substitutions discusses
simplificat ion in m ore deta il.
J x y x, ,( )r , ,( )-----------------------
-
8/6/2019 MATLAB Symbolic Math Toolbox
27/300
Calculus
1-21
A table summar izing diff a n d jacobian follows.
LimitsThe fundamental idea in calculus is to make calculations on functions as a
varia ble gets close to or a pproaches a cert ain va lue. Recall th at th e definition
of th e der ivative is given by a limit
provided this limit exists. The Symbolic Math Toolbox allows you to computethe limits of functions in a direct man ner. The comma nds
syms h n x
dc = limit( (cos(x+h) cos(x))/h,h,0 )
Mathematical Operator MATLAB Command
f(x) = exp(ax + b)
syms a b x
f = exp(a*x + b)
diff(x) or diff(f,x)
diff(f,a)
diff(f,b,2)
r = u 2 + v2
t = arctan (v/ u )
syms r t u v
r = u^2 + v^2
t = atan(v/u)
J = jacobian([r:t],[u,v])
xd
df
ad
df
b2
2
d
d f
Jr t,( )u v,( )-----------------=
f x( )f x h+( ) f x( )
h----------------------------------
h 0lim=
-
8/6/2019 MATLAB Symbolic Math Toolbox
28/300
-
8/6/2019 MATLAB Symbolic Math Toolbox
29/300
Calculus
1-23
while th e comma nd
limit(1/x,x,0,'right')
r e t u r n s
ans =
inf
Observe tha t t he defau lt case, limit(f) is the sam e as limit(f,x,0). Explore
the options for the limit command in this table. Here, we assume that f is afunction of t he symbolic object x.
IntegrationIff is a symbolic expression, th en
int(f)
attempts to find another symbolic expression, F, so that diff(F) = f. That is,
int(f) returns the indefinite integral or antiderivative off (provided one exist s
in closed form ). Similar to differen tiat ion,
int(f,v)
Mathematical Operation MATLAB Command
limit(f)
limit(f,x,a) or
limit(f,a)
limit(f,x,a,'left')
limit(f,x,a,'right')
f x( )x 0lim
f x( )x alim
f x( )x a
lim
f x( )x a
+lim
-
8/6/2019 MATLAB Symbolic Math Toolbox
30/300
1 Tutorial
1-24
uses the symbolic object v as t he variable of integration, ra ther than the
variable determined by findsym. See h ow int works by looking at this table.
In cont ra st t o differen tiat ion, symbolic integr at ion is a m ore complicat ed ta sk.
A number of difficulties can arise in computing the integral. The
antiderivative, F, ma y not exist in closed form ; it ma y define an un familiar
fun ction; it ma y exist, but t he softwa re can t find the a nt iderivative; th e
softwa re could find it on a la rger compu ter , but r un s out of time or m emory onthe available machine. Nevertheless, in many cases, MATLAB can perform
symbolic integra tion successfully. For exa mple, creat e t he symbolic varia bles
syms a b theta x yn x1 u
This table illustrates integration of expressions containing those variables.
Mathematical Operation MATLAB Command
int(x^n) or
int(x^n,x)
int(sin(2*x),0,pi/2) orint(sin(2*x),x,0,pi/2)
g = cos(a*t + b)
int(g) or
int(g,t)
int(besselj(1,z)) or
int(besselj(1,z),z)
f int(f)
x^n x^(n+1)/(n+1)
y^(1) log(y)
n^x 1/log(n)*n^x
xn
xd xn 1+
n 1+-------------=
2x( )sin xd
0
2
1=
g a t b+( )cos=
g t( ) td a t b+( )si n a=
J1 z( ) d z J 0 z( )=
-
8/6/2019 MATLAB Symbolic Math Toolbox
31/300
Calculus
1-25
The last example shows wha t h appen s if th e toolbox can t find th e
an tiderivat ive; it simply return s t he comma nd, including th e var iable of
integration, unevaluated.
Definite int egrat ion is also possible. The comm an ds
int(f,a,b)
a n d
int(f,v,a,b)
ar e u sed t o find a symbolic expression for
a n d
respectively.
Here ar e some additiona l exam ples.
sin(a*theta+b) cos(a*theta+b)/a
exp(x1^2) 1/2*pi^(1/2)*erf(x1)
1/(1+u^2) atan(u)
besselj(nu,z) int(besselj(nu,z),z)
f a, b int(f,a,b)
x^7 0, 1 1/8
1/x 1, 2 log(2)
log(x)*sqrt(x) 0, 1 4/9exp(x^2) 0, inf 1/2*pi^(1/2)
bessel(1,z) 0, 1 besselj(0,1)+1
f int(f)
f x( )a
b
d x f v( ) vda
b
-
8/6/2019 MATLAB Symbolic Math Toolbox
32/300
1 Tutorial
1-26
For the Bessel function (besselj) example, it is possible to compu te a
numer ical a pproximation to the value of the integra l, using the double
function. The command
a = int(besselj(1,z),0,1)
r e t u r n s
a =
besselj(0,1)+1
and t he com m an d
a = double(a)
r e t u r n s
a =
0.23480231344203
Integration with Real ConstantsOne of the subt leties involved in symbolic integra tion is t he value of various
par ameter s. For example, it would seem evident t ha t t he expression
is the positive, bell shaped curve t hat tends to 0 as x tends to for a ny real
number k. An exam ple of th is curve is depicted below with
and genera ted, using these comma nds.
syms x
k = sym(1/sqrt(2));
f = exp((k*x)^2);
ezplot(f)
ek x( ) 2
k1
2-------=
-
8/6/2019 MATLAB Symbolic Math Toolbox
33/300
-
8/6/2019 MATLAB Symbolic Math Toolbox
34/300
1 Tutorial
1-28
result in the output
Definite integration: Can't determine if the integral is
convergent.
Need to know the sign of --> k^2
Will now try indefinite integration and then take limits.
Warning: Explicit integral could not be found.
ans =
int(exp(k^2*x^2),x= inf..inf)
In t he n ext section, you well see how to make k a r eal variable an d ther efore k2
positive.
Real Variables via symNotice th at Maple is not able to determ ine th e sign of the expression k^2. How
does one sur mount t his obsta cle? The an swer is to ma ke k a r eal variable, using
t h e sym comma nd. One part icularly u seful featur e ofsym, nam ely the realoption, allows you to declare k to be a real var iable. Consequently, the integra l
above is compu ted, in th e t oolbox, using t he sequence
syms k real % Be sure that x has been declared a sym.
int(f,x,inf,inf)
which returns
ans =
signum(k)/k*pi^(1/2)
Notice t ha t k is now a symbolic object in t he MATLAB workspa ce and a rea l
variable in th e Maple kern el workspa ce. By typing
clear k
you only clear k in the MATLAB workspace. To ensure that k ha s no forma l
propert ies (tha t is, to ensure k is a purely formal variable), type
syms k unreal
This variation of the syms command clears k in t he Ma ple work space. You can
also declar e a sequen ce of symbolic var iables w , y, x, z to be real, using
syms w x y z real
-
8/6/2019 MATLAB Symbolic Math Toolbox
35/300
Calculus
1-29
In this case, all of the var iables in between t he words syms a n d real a r e
assigned the property real. That is, they are r eal variables in th e Maple
workspace.
Mathematical Operation MATLAB Commands
f(x) = ekx syms k x
f = exp(k*x)
int(f) or int(f,x)
int(f,k)
int(f,x,0,1) or int(f,0,1)
syms k real
g = exp((k*x)^2)
int(g,x,inf,inf) or
int(g,inf,inf)
f x( ) xd
f k( ) kd
f x( ) xd0
1
g x( ) e k x( )2
=
g x( ) xd
1
-
8/6/2019 MATLAB Symbolic Math Toolbox
36/300
1 Tutorial
1-30
Symbolic SummationYou can compute symbolic summations, when they exist, by using the symsumcommand. For example, the p-series
adds to 2/6, while th e geometric series 1 + x +x2 + ... adds to 1/(1-x), pr ovided| x| < 1. Three summ at ions a re demonstra ted below.
syms x k
s1 = symsum(1/k^2,1,inf)
s2 = symsum(x^k,k,0,inf)
s1 =
1/6*pi^2
s2 =
-1/(x-1)
11
22
------1
32
------ + + +
-
8/6/2019 MATLAB Symbolic Math Toolbox
37/300
Calculus
1-31
Taylor SeriesThe statem ent
T = taylor(f,8)
r e t u r n s
T =
1/9+2/81*x^2+5/1458*x^4+49/131220*x^6
which is all the t erm s up t o, but n ot including, order eight (O(x8)) in t he Ta ylorseries for f(x).
Technically, T is a MacLaurin series, since its basepoint is a = 0.
These comma nds
syms x
g = exp(x*sin(x))
t = taylor(g,12,2)
generate the first 12 nonzero terms of the Taylor series for g about x = 2.
x a( )n
n 0=
fn( )
a( )n !
-----------------
1
-
8/6/2019 MATLAB Symbolic Math Toolbox
38/300
1 Tutorial
1-32
Lets plot th ese functions together to see how well this Ta ylor appr oximation
compar es t o the actua l function g.
xd = 1:0.05:3; yd = subs(g,x,xd);
ezplot(t, [1,3]); hold on;
plot(xd, yd, 'r-.')
title('Taylor approximation vs. actual function');
legend('Function','Taylor')
Special thanks to Professor Gunnar Bckstrm of UMEA in Sweden for this
example.
Then the command
pretty(T)
prints T in a forma t r esembling typeset ma thema tics.
2 4 49 6
1/9 + 2/81 x + 5/1458 x + ------ x
131220
1 1.2 1.4 1.6 1.8 2 2.2 2.4 2.6 2.8 3
1
2
3
4
5
6
x
Taylor approximation vs. actual function
FunctionTaylor
-
8/6/2019 MATLAB Symbolic Math Toolbox
39/300
Calculus
1-33
Extended Calculus ExampleThe function
provides a starting point for illustrating several calculus operations in the
toolbox. It is also an interesting function in its own right. The statements
syms x
f = 1/(5+4*cos(x))
store t he symbolic expression defining t he fun ction in f.
Plotting Symbolic FunctionsThe Symbolic Math Toolbox offers a set of easy-to-use commands for plotting
symbolic expressions, including plan ar curves (ezplot), cont our s (ezcontour
a n d ezcontourf), surfaces (ezsurf, ezsurfc, ezmesh, and ezmeshc), polar
coordin at es (ezpolar), and parametrically defined curves (ezplot a n d
ezplot3) and sur faces (ezsurf). See Chapter 2, Reference for a detailed
description of these functions. The rest of this section illustrates the use of
ezplot to gra ph functions of th e form y=f(x).
f x( )1
5 4 x( )cos+------------------------------=
1
http://-/?-http://-/?- -
8/6/2019 MATLAB Symbolic Math Toolbox
40/300
1 Tutorial
1-34
The fun ction ezplot(f) produces th e plot off(x) as shown below.
Th e ezplot fun ction t ries to ma ke r easona ble choices for t he r an ge of the x-axis
and for the resulting scale of the y-axis. Its choices can be overr idden by a n
additional input argum ent, or by subsequentaxis
commands. The defaultdomain for a function displayed by ezplot is 2 x 2. To alter the domain,type
ezplot(f,[a b])
This produces a graph off(x) for a x b.
Lets n ow look at th e second derivat ive of th e function f.
f2 = diff(f,2)
f2 =
32/(5+4*cos(x))^3*sin(x)^2+4/(5+4*cos(x))^2*cos(x)
6 4 2 0 2 4 6
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1
x
1/(5+4*cos(x))
-
8/6/2019 MATLAB Symbolic Math Toolbox
41/300
1 T l
-
8/6/2019 MATLAB Symbolic Math Toolbox
42/300
1 Tutorial
1-36
compute f' ' '(x) an d display it in a more reada ble forma t.
3
sin(x) sin(x) cos(x) sin(x)
384 --------------- + 96 --------------- 4 ---------------
4 3 2
(5 + 4 cos(x)) (5 + 4 cos(x)) (5 + 4 cos(x))
We can simplify and th is expression using the stat ements
f3 = simple(f3);
pretty(f3)
2 2
sin(x) (96 sin(x) + 80 cos(x) + 80 cos(x) 25)
4 -------------------------------------------------
4
(5 + 4 cos(x))
Now use th e solve function to find th e zeros off' ' '(x).
z = solve(f3)
returns a 5-by-1 symbolic matrix
z =
[ 0]
[ atan((25560*19^(1/2))^(1/2),10+3*19^(1/2))][ atan((25560*19^(1/2))^(1/2),10+3*19^(1/2))]
[ atan((255+60*19^(1/2))^(1/2)/(103*19^(1/2)))+pi]
[ atan((255+60*19^(1/2))^(1/2)/(103*19^(1/2)))pi]
each of whose en tr ies is a zero off'''(x). The comma nd
format; % Default format of 5 digits
zr = double(z)
-
8/6/2019 MATLAB Symbolic Math Toolbox
43/300
Calculus
1-37
converts the zeros to double form.
zr =
0
0+ 2.4381i
0 2.4381i
2.4483
2.4483
So far , we have foun d th ree r eal zeros and two complex zeros. However, a graph
off3 shows that we have not yet found all its zeros.
ezplot(f3)
hold on;
plot(zr,0*zr,'ro')
plot([2*pi,2*pi], [0,0],'g-.');
title('Zeros of f3')
6 4 2 0 2 4 6
3
2
1
0
1
2
3
x
Zeros of f3
1 T t i l
-
8/6/2019 MATLAB Symbolic Math Toolbox
44/300
1 Tutorial
1-38
This occurs becau se f'''(x) cont ains a factor of sin (x), which is zero at integer
mult iples of. The fun ction, solve(sin(x)), however, only reports t he zer o atx = 0.
We can obtain a complete list of the real zeros by translating zr
zr = [0 zr(4) pi 2*pizr(4)]
by mu ltiples of 2
zr = [zr2*pi zr zr+2*pi];
Now lets plot th e tr an sform ed zr on our graph for a complete picture of the
zeros off3.
plot(zr,0*zr,'kX')
The first zero off'''(x) found by solve is at x = 0. We substitute 0 for the
symbolic variable in f2
f20 = subs(f2,x,0)
6 4 2 0 2 4 6
3
2
1
0
1
2
3
x
Zeros of f3
l l
-
8/6/2019 MATLAB Symbolic Math Toolbox
45/300
Calculus
1-39
to compute the corresponding value off ''(0).
f20 =
0.0494
A look at the graph off''(x) shows that this is only a local minimum, which we
demonstr at e by replott ing f2.
clf
ezplot(f2)
axis([2*pi 2*pi 4.25 1.25])ylabel('f2');
title('Plot of f2 = f''''(x)')
hold on
plot(0,double(f20),'ro')
text(1,0.25,'Local minimum')
The resulting plot
6 4 2 0 2 4 6
4
3.5
3
2.5
2
1.5
1
0.5
0
0.5
1
x
Plot of f2 = f(x)
f2
Local minimum
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
46/300
1 Tutorial
1-40
indicates tha t the global minima occur near x = - a n d x = . We candemonstr at e th at they occur exactly at x= , u sing t he following sequen ce ofcomma nds. First we tr y substituting - a n d into f'''(x).
simple([subs(f3,x,pi),subs(f3,x,pi)])
The result
ans =
[ 0, 0]
shows tha t - a n d ha ppen t o be crit ical points off'''(x). We can see th at - a n d are global minima by plotting f2(pi) a n d f2(pi) against f2(x).
m1 = double(subs(f2,x,-pi)); m2 = double(subs(f2,x,pi));
plot(-pi,m1,'go',pi,m2,'go')
text(-1,-4,'Global minima')
The actual m inim a a re m1, m2
ans =[ 4, 4]
as shown in the plot on the following page.
C l l
-
8/6/2019 MATLAB Symbolic Math Toolbox
47/300
Calculus
1-41
The foregoing analysis confirms part of our original guess that the range of
f''(x) is [-4, 1]. We can confirm t he other pa rt by exam ining th e four th zero of
f'''(x) found by solve. First extract th e fourt h zero from z and assign it to a
separate variable
s = z(4)
to obtain
s =
atan((255+60*19^(1/2))^(1/2)/(103*19^(1/2)))+pi
Executing
sd = double(s)
displays the zeros corresponding numeric value.
sd =
2.4483
6 4 2 0 2 4 6
4
3.5
3
2.5
2
1.5
1
0.5
0
0.5
1
x
Plot of f2 = f(x)
f2
Local minimum
Global minima
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
48/300
1 Tutorial
1-42
Plotting the point (s, f2(s)) against f2, using
M1 = double(subs(f2,x,s));
plot(sd,M1,'ko')
text(-1,1,'Global maximum')
visually confirms that s is a maximum.
The maximum is M1 = 1.0051.
Therefore, our guess that the m aximum off''(x) is [4, 1] was close, but
incorr ect. The a ctu al r an ge is [4, 1.0051].
Now, lets s ee if integr at ing f''(x) twice with respect to x recovers our originalfunction f(x) = 1/(5 + 4 cos x). The command
g = int(int(f2))
6 4 2 0 2 4 6
4
3.5
3
2.5
2
1.5
1
0.5
0
0.5
1
x
Plot of f2 = f(x)
f2
Local minimum
Global minima
Global maximum
Calculus
-
8/6/2019 MATLAB Symbolic Math Toolbox
49/300
Calculus
1-43
r e t u r n s
g =
8/(tan(1/2*x)^2+9)
This is certa inly not th e origina l expression for f(x). Lets look a t t he d ifferen ce
f(x) g(x).
d = f g
pretty(d)
1 8
[ + ]
5 + 4 cos(x) 2
tan(1/2 x) + 9
We can simplify this u sing simple(d) or simplify(d). Either command
produces
ans =1
This illustrates the concept that differentiating f(x) twice, then integrat ing the
result twice, produces a function that may differ from f(x) by a linear function
of x.
Finally, integrat e f(x) once more.
F = int(f)
The result
F =
2/3*atan(1/3*tan(1/2*x))
involves the arctangent function.
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
50/300
1 Tutorial
1-44
Though F(x) is the antiderivative of a continuous function, it is itself
discontinuous as the following plot shows.
ezplot(F)
Note th at F(x) has jum ps at x = . This occurs because tan x is singular atx = .
6 4 2 0 2 4 6
1
.8
.6
.4
.2
0
.2
.4
.6
.8
1
x
2/3*atan(1/3*tan(1/2*x))
Calculus
-
8/6/2019 MATLAB Symbolic Math Toolbox
51/300
Calculus
1-45
In fact, as
ezplot(atan(tan(x)))
shows, th e n umerical value ofatan(tan(x))differ s from x by a piecewise
consta nt function t ha t h as jumps at odd multiples of/2.
To obtain a representation ofF(x) th at does not h ave jumps at these points, we
must introduce a second function, J (x), tha t compensat es for t he
discontinu ities. Then we add the appr opriate multiple ofJ(x) t o F(x).
J = sym('round(x/(2*pi))');
c = sym('2/3*pi');
F1 = F+c*J
F1 =
2/3*atan(1/3*tan(1/2*x))+2/3*pi*round(1/2*x/pi)
6 4 2 0 2 4 6
1.5
1
0.5
0
0.5
1
1.5
x
atan(tan(x))
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
52/300
1-46
and plot the result.
ezplot(F1,[6.28,6.28])
This representa tion does have a continu ous gra ph.
Notice that we use the domain [6.28, 6.28] in ezplot rath er than the default
doma in [2, 2]. The reason for this is to prevent an evaluation ofF1 = 2/3 atan(1/3 tan 1/2 x) at th e singular points x = a n d x = where the
jumps in F a n d J do not can cel out one an oth er. The pr oper h an dling of bra nch
cut discont inuities in mu ltivalued fun ctions like ar ctan x is a deep and difficult
problem in sym bolic compu ta tion. Although MATLAB a nd Maple cann ot do
this entirely automatically, they do provide the tools for investigating such
questions.
6 4 2 0 2 4 6
2.5
2
1.5
1
0.5
0
0.5
1
1.5
2
2.5
x
2/3*atan(1/3*tan(1/2*x))+2/3*pi*round(1/2*x/pi)
-
8/6/2019 MATLAB Symbolic Math Toolbox
53/300
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
54/300
1-48
This toolbox provides several functions that apply various algebraic and
trigonometric identities to transform one representation of a function into
another, possibly simpler, r epresentat ion. These functions ar e collect,
expand, horner, factor, simplify, a n d simple.
collectThe statem ent
collect(f)
views f as a polynomial in its symbolic variable, say x, an d collects all th e
coefficients with th e sa me power ofx. A second argument can specify the
var iable in which to collect t erm s if th ere is more tha n one can didat e. Here ar e
a few examples:
f collect(f)
(x1)*(x2)*(x3) x^36*x^2+11*x6
x*(x*(x6)+11)6 x^36*x^2+11*x6
(1+x)*t + x*t 2*x*t+t
Simplifications and Substitutions
-
8/6/2019 MATLAB Symbolic Math Toolbox
55/300
p
1-49
expandThe statem ent
expand(f)
distr ibutes pr oducts over su ms a nd a pplies oth er ident ities involving functions
of sums. For example,
hornerThe statem ent
horner(f)
tr an sform s a symbolic polynomial f into its H orner , or nested, representa tion.
For example,
f expand(f)
a(x + y) ax + ay
(x1)(x2)(x3) x^36x^2+11x6
x(x(x6)+11)6 x^36x^2+11x6
exp(a+b) exp(a)exp(b)
cos(x+y) cos(x)*cos(y)sin(x)*sin(y)
cos(3acos(x)) 4x^3 3x
f horner(f)
x^36x^2+11x6 6+(11+(6+x)*x)*x
1.1+2.2x+3.3x^2 11/10+(11/5+33/10*x)*x
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
56/300
1-50
factorIff is a polynomial with rational coefficients, the statement
factor(f)
expresses f as a product of polynomials of lower degree with r at iona l
coefficients. Iff can not be factored over t he r at iona l numbers, th e result is f
itself. For example,
Here is another example involving factor. It factors polynomials of the form
x^n + 1. This code
syms x;
n = 1:9;
x = x(ones(size(n)));
p = x.^n + 1;
f = factor(p);
[p; f].'
retur ns a mat rix with the polynomials in its first column a nd t heir factoredforms in its second:
[ x+1, x+1 ]
[ x^2+1, x^2+1 ]
[ x^3+1, (x+1)*(x^2x+1) ]
[ x^4+1, x^4+1 ]
[ x^5+1, (x+1)*(x^4x^3+x^2x+1) ]
[ x^6+1, (x^2+1)*(x^4x^2+1) ]
[ x^7+1, (x+1)*(1x+x^2x^3+x^4x^5+x^6) ]
[ x^8+1, x^8+1 ]
[ x^9+1, (x+1)*(x^2x+1)*(x^6x^3+1) ]
f factor(f)
x^36x^2+11x6 (x1)(x2)(x3)
x^36x^2+11x5 x^36x^2+11x5
x^6+1 (x^2+1)(x^4x^2+1)
Simplifications and Substitutions
-
8/6/2019 MATLAB Symbolic Math Toolbox
57/300
p
1-51
As an aside at t his point, we mention t hat factor can also factor symbolic
objects containing integers. This is an alternative to using the factor functionin MATLABs specfun directory. F or exa mple, t he following code segmen t
one = '1'
for n = 1:11
N(n,:) = sym(one(1,ones(1,n)));
end
[N factor(N)]
displays t he factors of symbolic integers consistin g of 1s.
[ 1, 1 ]
[ 11, (11) ]
[ 111, (3)*(37) ]
[ 1111, (11)*(101) ]
[ 11111, (41)*(271) ]
[ 111111, (3)*(7)*(11)*(13)*(37) ][ 1111111, (239)*(4649) ]
[ 11111111, (11)*(73)*(101)*(137) ]
[ 111111111, (3)^2*(37)*(333667) ]
[ 1111111111, (11)*(41)*(271)*(9091) ]
[ 11111111111, (513239)*(21649) ]
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
58/300
1-52
simplifyTh e simplify function is a powerful, general purpose tool that applies a
number of algebraic identities involving sums, integral powers, square roots
and other fractional powers, as well as a number of functional identities
involving t rig fun ctions, exponen tia l a nd log functions, Bessel functions,
hypergeometr ic functions, a nd the gamma function. H ere a re some examples.
simpleTh e simple function has the unorthodox mathematical goal of finding a
simplification of an expression that has the fewest number of characters. Of
course, there is little mathematical justification for claiming that one
expression is simpler than another just because its ASCII representation is
shorter, but this often proves satisfactory in practice.
Th e simple function achieves its goal by independently applying simplify,
collect, factor, and other simplification functions to an expression and
keeping tr ack of the length s of the results. The simple function then returns
the shortest result.
f simplify(f)
x(x(x6)+11)6 x^36x^2+11x6
(1x^2)/(1x) x + 1
(1/a^3+6/a^2+12/a+8)^(1/3) ((2*a+1)^3/a^3)^(1/3)
syms x y positive
log(xy) log(x) + log(y)
exp(x) exp(y) exp(x+y)besselj(2,x) ...
2*besselj(1,x)/x +
besselj(0,x)
0
gamma(x+1)x*gamma(x) 0
cos(x)^2 + sin(x)^2 1
Simplifications and Substitutions
-
8/6/2019 MATLAB Symbolic Math Toolbox
59/300
1-53
Th e simple function ha s several forms, ea ch retu rn ing different outpu t. The
form
simple(f)
displays each tr ial simplificat ion a nd t he simplification fun ction t ha t pr oduced
it in th e MATLAB comma nd window. The simple function then returns the
shortest r esult. For example, the comma nd
simple(cos(x)^2 + sin(x)^2)
displays th e following alt ern at ive simplifications in t he MATLAB comm an d
window
simplify:
1
radsimp:
cos(x)^2+sin(x)^2
combine(trig):
1
factor:
cos(x)^2+sin(x)^2
expand:
cos(x)^2+sin(x)^2
convert(exp):
(1/2*exp(i*x)+1/2/exp(i*x))^21/4*(exp(i*x)1/exp(i*x))^2
convert(sincos):
cos(x)^2+sin(x)^2
convert(tan):
(1tan(1/2*x)^2)^2/(1+tan(1/2*x)^2)^2+4*tan(1/2*x)^2/
(1+tan(1/2*x)^2)^2
collect(x):
cos(x)^2+sin(x)^2
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
60/300
1-54
a n d r e t u r n s
ans =
1
This form is useful when you wa nt to check, for example, wheth er t he sh ort est
form is indeed the simplest. If you are not interested in how simple achieves
its result, use t he form
f = simple(f)
This form simply retu rn s th e shortest expression found. F or example, the
statem ent
f = simple(cos(x)^2+sin(x)^2)
r e t u r n s
f =
1
If you want to know which simplificat ion retu rned the shortest r esult, use t he
multiple output form
[F, how] = simple(f)
This form retu rn s the shortes t resu lt in th e first var iable and the simplificat ion
method used t o achieve th e resu lt in t he second var iable. For example, the
statem ent
[f, how] = simple(cos(x)^2+sin(x)^2)
r e t u r n s
f =
1
how =
combine(trig)
Th e simple function sometimes improves on the result returned by simplify,
one of the simplifications that it tries. For example, when applied to the
Simplifications and Substitutions
-
8/6/2019 MATLAB Symbolic Math Toolbox
61/300
1-55
examples given for simplify, simple returns a simpler (or at least shorter)
result in two cases:
In some cases, it is advant ageous to apply simple twice to obta in t he effect of
two different simplification functions. For example, the statements
f = (1/a^3+6/a^2+12/a+8)^(1/3);
simple(simple(f))
r e t u r n
1/a+2
The first application, simple(f), uses radsimp to pr oduce (2*a+1)/a; the
second a pplicat ion uses combine(trig) to transform this to 1/a+2.
Th e simple function is particularly effective on expressions involving
trigonometric functions. Here are some examples:
f simplify(f) simple(f)
(1/a^3+6/a^2+12/a+8)^(1/3) ((2*a+1)^3/a^3)^(1/3) (2*a+1)/a
syms x y positive
log(xy) log(x)+log(y) log(x*y)
f simple(f)
cos(x)^2+sin(x)^2 1
2cos(x)^2sin(x)^2 3cos(x)^21
cos(x)^2sin(x)^2 cos(2x)
cos(x)+(sin(x)^2)^(1/2) cos(x)+isin(x)
cos(x)+isin(x) exp(ix)
cos(3acos(x)) 4x^33x
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
62/300
1-56
SubstitutionsThere are two functions for symbolic substitution: subexpr a n d subs.
subexprThese comma nds
syms a x
s = solve(x^3+a*x+1)
solve th e equa tion x^3+a*x+1 = 0 for x.
s =
[ (1/2+1/18*(12*a^3+81)^(1/2))^(1/3)
1/3*a/(1/2+1/18*(12*a^3+81)^(1/2))^(1/3) ]
[ 1/2*(1/2+1/18*(12*a^3+81)^(1/2))^(1/3)+
1/6*a/(1/2+1/18*(12*a^3+81)^(1/2))^(1/3)+
1/2*i*3^(1/2)*((1/2+1/18*(12*a^3+81)^(1/2))^(1/3)+
1/3*a/(1/2+1/18*(12*a^3+81)^(1/2))^(1/3)) ]
[ 1/2*(1/2+1/18*(12*a^3+81)^(1/2))^(1/3)+
1/6*a/(1/2+1/18*(12*a^3+81)^(1/2))^(1/3)
1/2*i*3^(1/2)*((1/2+1/18*(12*a^3+81)^(1/2))^(1/3)+
1/3*a/(1/2+1/18*(12*a^3+81)^(1/2))^(1/3)) ]
Simplifications and Substitutions
-
8/6/2019 MATLAB Symbolic Math Toolbox
63/300
1-57
Use th e prett y fun ction to display s in a more reada ble form.
pretty(s)
s =
[ 1/3 a ]
[ %1 1/3 ----- ]
[ 1/3 ]
[ %1 ]
[ ]
[ 1/3 a 1/2 / 1/3 a \ ]
[ 1/2 %1 + 1/6 ----- + 1/2 i 3 |%1 + 1/3 -----| ]
[ 1/3 | 1/3| ]
[ %1 \ %1 / ]
[ ]
[ 1/3 a 1/2 / 1/3 a \ ]
[ 1/2 %1 + 1/6 ----- 1/2 i 3 |%1 + 1/3 -----| ]
[ 1/3 | 1/3| ]
[ %1 \ %1 / ]
3 1/2
%1 := 1/2 + 1/18 (12 a + 81)
Th e pretty command inherits the %n (n, an integer) notation from Maple to
denote subexpressions that occur multiple times in the symbolic object. The
subexpr function allows you to sa ve th ese common s ubexpressions a s well as
the symbolic object rewritten in terms of the subexpressions. Thesubexpressions are saved in a column vector called sigma.
Continu ing with the example
r = subexpr(s)
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
64/300
1-58
r e t u r n s
sigma =
108+12*(12*a^3+81)^(1/2)
r =
[ 1/6*sigma^(1/3)2*a/sigma^(1/3)]
[ 1/12*sigma^(1/3)+a/sigma^(1/3)+
1/2*i*3^(1/2)*(1/6*sigma^(1/3)+2*a/sigma^(1/3))]
[ 1/12*sigma^(1/3)+a/sigma^(1/3)
1/2*i*3^(1/2)*(1/6*sigma^(1/3)+2*a/sigma^(1/3))]
Notice t ha t subexpr creat es the var iable sigma in t he MATLAB workspa ce.
You can verify t his by t yping whos, or t he comma nd
sigma
which returns
sigma =108+12*(12*a^3+81)^(1/2)
Simplifications and Substitutions
-
8/6/2019 MATLAB Symbolic Math Toolbox
65/300
1-59
subsLets find t he eigenvalues a nd eigenvectors of a circulant ma tr ixA.
syms a b c
A = [a b c; b c a; c a b];
[v,E] = eig(A)
v =
[ (a+(b^2b*ac*bc*a+a^2+c^2)^(1/2)b)/(ac),
(a(b^2b*ac*bc*a+a^2+c^2)^(1/2)b)/(ac), 1]
[ (bc(b^2b*ac*bc*a+a^2+c^2)^(1/2))/(ac),
(bc+(b^2b*ac*bc*a+a^2+c^2)^(1/2))/(ac), 1]
[ 1,
1, 1]
E =
[ (b^2b*ac*b
c*a+a^2+c^2)^(1/2), 0, 0]
[ 0, (b^2b*ac*b
c*a+a^2+c^2)^(1/2), 0]
[ 0, 0, b+c+a]
Suppose we wan t to replace th e ra ther lengthy expression
(b^2b*ac*bc*a+a^2+c^2)^(1/2)
throughout v a n d E. We first use subexpr:
v = subexpr(v,'S')
which returns
S =
(b^2b*ac*bc*a+a^2+c^2)^(1/2)
v =
[ (a+Sb)/(ac), (aSb)/(ac), 1]
[ (bcS)/(ac), (bc+S)/(ac), 1]
[ 1, 1, 1]
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
66/300
1-60
Next, substitute the symbol S into E with
E = subs(E,S,'S')
E =
[ S, 0, 0]
[ 0, S, 0]
[ 0, 0, b+c+a]
Now suppose we wan t t o evaluat e v a t a = 10. We can do this using the subs
command:
subs(v,a,10)
This r eplaces all occurr ences ofa in v with 10
[ (10+Sb)/(10c), (10Sb)/(10c), 1]
[ (bcS)/(10c), (bc+S)/(10c), 1]
[ 1, 1, 1]
Notice, however, tha t t he symbolic express ion r epresen ted by S is unaffected bythis substitu tion. Tha t is, the symbol a in S is not replaced by 10. The subs
comman d is a lso a useful function for subst itut ing in a variety of values for
several var iables in a pa rt icular expression. Lets look at S. Suppose tha t in
addition to substituting a = 10, we also wan t to substitu te th e values for 2 an d
10 for b a n d c, respectively. The way t o do th is is to set values for a, b, and c in
the workspace. Then subs evaluat es its input using th e existing symbolic and
double variables in the current workspace. In our example, we first set
a = 10; b = 2; c = 10;
subs(S)
ans =
64^(1/2)
Simplifications and Substitutions
-
8/6/2019 MATLAB Symbolic Math Toolbox
67/300
1-61
To look at the contents of our workspace, type whos, which gives
Name Size Bytes Class
A 3x3 878 sym object
E 3x3 888 sym object
S 1x1 186 sym object
a 1x1 8 double array
ans 1x1 140 sym object
b 1x1 8 double array
c 1x1 8 double array
v 3x3 982 sym object
a, b, and c ar e now var iables of class doublewhileA, E, S, an d v rem ain symbolic
expressions (class sym).
If you want to preserve a, b, and c as symbolic variables, but still alter their
value within S, use t his procedure.
syms a b csubs(S,{a,b,c},{10,2,10})
ans =
64^(1/2)
Typing whos reveals that a, b, a n d c rem ain 1-by-1 sym objects.
Th e subs command can be combined with double to evaluate a symbolic
expression numerically. Suppose we have
syms t
M = (1t^2)*exp(1/2*t^2);
P = (1t^2)*sech(t);
and want to see how M a n d P differ graphically.
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
68/300
1-62
One appr oach is to type
ezplot(M); hold on; ezplot(P)
but this plot
does not readily help us identify the curves.
6 4 2 0 2 4 6
0.8
0.6
0.4
0.2
0
0.2
0.4
0.6
0.8
1
t
(1t^2)*sech(t)
-
8/6/2019 MATLAB Symbolic Math Toolbox
69/300
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
70/300
1-64
Variable-Precision Arithmetic
OverviewThere are three different kinds of arithmetic operations in this toolbox.
Numer ic MATLABs float ing-point ar ithmetic
Rational M aples exact sym bolic ari thm etic
VP A M a ple s va r i a bl e-p r e ci si on a r i t h m et i c
For example, the MATLAB sta tement s
format long
1/2+1/3
use numeric computation to produce
0.83333333333333
With the Symbolic Math Toolbox, the statement
sym(1/2)+1/3
uses symbolic computa tion t o yield
5/6
And, also with the toolbox, the statements
digits(25)vpa(1/2+1/3)
use variable-precision ar ithmetic to ret urn
.8333333333333333333333333
The float ing-point opera tions used by numer ic ar ithm etic ar e the fast est of th e
three, and require the least computer memory, but the results are not exact.
The n um ber of digits in th e prin ted out put of MATLABs double quan tities iscontrolled by th e format statement, but the internal representation is always
the eight-byte floating-point representation provided by the particular
computer hardware.
In t he comput at ion of th e numer ic result a bove, th ere ar e actually three
roundoff errors, one in th e division of 1 by 3, one in th e a ddition of 1/2 to th e
Variable-Precision Arithmetic
-
8/6/2019 MATLAB Symbolic Math Toolbox
71/300
1-65
result of the division, and one in the binary to decimal conversion for the
printed output. On computers that use IEEE floating-point standardar ithmetic, th e resulting intern al value is th e binary expansion of 5/6,
tru ncated t o 53 bits. This is a pproximately 16 decimal digits. But , in t his
part icular case, th e print ed output shows only 15 digits.
The symbolic operat ions used by rat ional ar ithmetic are potent ially th e m ost
expensive of th e thr ee, in term s of both compu ter t ime and memory. The resu lts
ar e exact, a s long as enough time a nd m emory a re a vailable to complete th e
computations.
Variable-precision arithmetic falls in between the other two in terms of both
cost a nd a ccur acy. A global pa ra met er, set by the fun ction digits, contr ols th e
nu mber of significan t decimal digits. Increasing t he n um ber of digits in creases
the a ccur acy, but a lso increases both th e time an d memory requirements. The
default valu e ofdigits is 32, corresponding roughly to floating-point accuracy.
The Maple docum ent at ion uses th e term ha rdwa re floating-point for wha t we
ar e calling nu mer ic or float ing-point an d uses th e t erm float ing-point
ar ithm etic for wha t we ar e calling var iable-precision a rith met ic.
Example: Using the Different Kinds of Arithmetic
Rational ArithmeticBy defau lt, the Symbolic Mat h Toolbox uses ra tional ar ithm etic operat ions, i.e.,
Maples exact symbolic ar ithm etic. Rat iona l ar ithm etic is invoked wh en you
create symbolic variables using the sym function.
Th e sym function convert s a double mat rix to its symbolic form. F or example, if
the double mat rix is
A =
1.1000 1.2000 1.3000
2.1000 2.2000 2.3000
3.1000 3.2000 3.3000
its symbolic form, S = sym(A), is
S =
[11/10, 6/5, 13/10]
[21/10, 11/5, 23/10]
[31/10, 16/5, 33/10]
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
72/300
1-66
For t his m atrixA, it is possible to discover tha t the elements ar e th e r atios of
small integers, so the symbolic representation is formed from those integers.On the other ha nd, the statem ent
E = [exp(1) sqrt(2); log(3) rand]
r e t u r n s a m a t r i x
E =
2.71828182845905 1.41421356237310
1.09861228866811 0.21895918632809
whose elements a re n ot the ra tios of small integers, so sym(E) reproduces th e
float ing-point repr esent at ion in a symbolic form.
[3060513257434037*2^(50), 3184525836262886*2^(51)]
[2473854946935174*2^(51), 3944418039826132*2^(54)]
Variable-Precision Numbers
Variable-precision numbers are distinguished from the exact rationalrepr esent at ion by th e pr esence of a decimal point. A power of 10 scale factor,
denoted by 'e', is allowed. To use var iable-precision inst ead of ra tional
ar ithmetic, creat e your variables using the vpa function.
For ma tr ices with pu rely double entries, the vpa function genera tes th e
representation that is used with variable-precision arithmetic. Continuing on
with our example, and u sing digits(4), applying vpa to the m atrix S
vpa(S)
generates the output
S =
[1.100, 1.200, 1.300]
[2.100, 2.200, 2.300]
[3.100, 3.200, 3.300]
and with digits(25)F = vpa(E)
Variable-Precision Arithmetic
-
8/6/2019 MATLAB Symbolic Math Toolbox
73/300
1-67
generates
F =
[2.718281828459045534884808, 1.414213562373094923430017]
[1.098612288668110004152823, .2189591863280899719512718]
Converting to Floating-PointTo convert a rational or variable-precision number to its MATLAB
floating-point representation, use the double function.
In our example, both double(sym(E)) a n d double(vpa(E)) r e t u r n E.
Another ExampleThe next example is perhaps more interesting. Start with the symbolic
expression
f = sym('exp(pi*sqrt(163))')
The statem ent
double(f)
produces the printed floating-point value
2.625374126407687e+17
Using the second a rgument ofvpa to specify th e nu mber of digits,
vpa(f,18)
r e t u r n s
262537412640768744.
whereas
vpa(f,25)
r e t u r n s
262537412640768744.0000000
We suspect t hat f might actually have an integer value. This suspicion is
reinforced by th e 30 digit value, vpa(f,30)
262537412640768743.999999999999
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
74/300
1-68
Finally, the 40 digit value, vpa(f,40)
262537412640768743.9999999999992500725944
shows that f is very close to, but n ot exactly equa l to, an in teger.
Linear Algebra
-
8/6/2019 MATLAB Symbolic Math Toolbox
75/300
1-69
Linear Algebra
Basic Algebraic OperationsBasic algebraic operations on symbolic objects are the same as operations on
MATLAB objects of class double. This is illustrated in the following example.
The Givens transformation produces a plane rotation through the angle t. The
statem ents
syms t;G = [cos(t) sin(t); sin(t) cos(t)]
create this transformation matrix:
G =
[ cos(t), sin(t) ]
[ sin(t), cos(t) ]
Applying th e Givens t ra nsform at ion t wice should simply be a r otat ion t hr oughtwice the angle. The corresponding matrix can be computed by multiplying G
by itself or by ra ising G to th e second power. Both
A = G*G
a n d
A = G^2
produce
A =
[cos(t)^2sin(t)^2, 2*cos(t)*sin(t)]
[ 2*cos(t)*sin(t), cos(t)^2sin(t)^2]
Th e simple function
A = simple(A)
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
76/300
1-70
uses a trigonometric identity to retu rn th e expected form by trying several
different ident ities a nd picking th e one tha t pr oduces th e shortestrepresentation:
A =
[ cos(2*t), sin(2*t)]
[sin(2*t), cos(2*t)]
A Givens rotat ion is an orth ogonal m at rix, so its tr an spose is its inverse.
Confirming this by
I = G.' *G
which produces
I =
[cos(t)^2+sin(t)^2, 0]
[ 0, cos(t)^2+sin(t)^2]
a n d t h e n
I = simple(I)
I =
[1, 0]
[0, 1]
Linear Algebraic OperationsLets do severa l basic linear algebraic operat ions.
The comma nd
H = hilb(3)
generates th e 3-by-3 H ilbert mat rix. With format short, MATLAB pr ints
H =
1.0000 0.5000 0.3333
0.5000 0.3333 0.25000.3333 0.2500 0.2000
Linear Algebra
-
8/6/2019 MATLAB Symbolic Math Toolbox
77/300
1-71
The computed elements ofH ar e float ing-point nu mbers th at ar e the r atios of
small integers. Indeed, H is a MATLAB a rr ay of class double. Converting H t oa symbolic matrix
H = sym(H)
gives
[ 1, 1/2, 1/3]
[1/2, 1/3, 1/4]
[1/3, 1/4, 1/5]
This a llows su bsequent symbolic opera tions on H to produce results tha t
correspond to the infinitely precise Hilbert matrix, sym(hilb(3)), not its
floating-point appr oximat ion, hilb(3). Ther efore,
inv(H)
produces
[ 9, 36, 30][36, 192, 180]
[ 30, 180, 180]
a n d
det(H)
yields
1/2160
We can use the backslash operator to solve a system of simultaneous linear
equations. The comma nds
b = [1 1 1]'
x = H\b % Solve Hx = b
produce th e solut ion
[ 3]
[24]
[ 30]
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
78/300
1-72
All three of these r esults, the inverse, the determina nt , and t he solution to the
linear system, ar e t he exact r esults corr esponding to t he infinitely precise,ra tiona l, Hilbert m at rix. On th e other ha nd, using digits(16), the comma nd
V = vpa(hilb(3))
r e t u r n s
[ 1., .5000000000000000, .3333333333333333]
[.5000000000000000, .3333333333333333, .2500000000000000]
[.3333333333333333, .2500000000000000, .2000000000000000]The decimal points in t he repr esentat ion of the individual element s ar e the
signal to use variable-precision arithmetic. The result of each arithmetic
operation is rounded to 16 significant decimal digits. When inverting the
mat rix, these err ors ar e ma gnified by the mat rix condition num ber, which for
hilb(3) is about 500. Consequently,
inv(V)
which returns
[ 9.000000000000082, 36.00000000000039, 30.00000000000035]
[36.00000000000039, 192.0000000000021, 180.0000000000019]
[ 30.00000000000035, 180.0000000000019, 180.0000000000019]
shows t he loss of two digits. So d oes
det(V)
which gives
.462962962962958e3
a n d
V\b
which is
[ 3.000000000000041]
[24.00000000000021]
[ 30.00000000000019]
Since H is nonsingular, the null space ofH
null(H)
Linear Algebra
-
8/6/2019 MATLAB Symbolic Math Toolbox
79/300
1-73
and the column space ofH
colspace(H)
produce an empty matrix and a permutation of the identity matrix,
respectively. To ma ke a more inter esting exam ple, lets t ry t o find a value s for
H(1,1) t h a t m a k e s H singular . The comma nds
syms s
H(1,1) = s
Z = det(H)
sol = solve(Z)
produce
H =
[ s, 1/2, 1/3]
[1/2, 1/3, 1/4]
[1/3, 1/4, 1/5]
Z =
1/240*s1/270
sol =
8/9
Then
H = subs(H,s,sol)
substitut es th e comput ed value ofsol for s in H to give
H =
[8/9, 1/2, 1/3]
[1/2, 1/3, 1/4]
[1/3, 1/4, 1/5]
Now, th e comma nd
det(H)
r e t u r n s
ans =
0
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
80/300
1-74
a n d
inv(H)
produces an error m essage
??? error using ==> inv
Error, (in inverse) singular matrix
because H is singular. For th is matr ix, Z = null(H) a n d C = colspace(H) a r e
nontrivial.
Z =
[ 1]
[ 4]
[10/3]
C =
[ 0, 1]
[ 1, 0][6/5, 3/10]
It should be pointed out that even though H is singular , vpa(H) is not. For an y
integer value d, setting
digits(d)
and then computing
det(vpa(H))inv(vpa(H))
results in a determina nt of size 10^(d) and an inverse with elements on the
order of10^d.
EigenvaluesThe symbolic eigenvalu es of a squ ar e ma tr ixA or t he symbolic eigenvalues a nd
eigenvectors ofA are computed, respectively, using the commands
E = eig(A)
[V,E] = eig(A)
-
8/6/2019 MATLAB Symbolic Math Toolbox
81/300
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
82/300
1-76
r e t u r n
Td =
1.0000 1.6497 -1.2837
-4.0000 1.0000 1.0000
3.3333 0.7051 1.5851
Ed =
0 0 0
0 1.3344 0
0 0 0.0878
The first eigenvalue is zero. The corresponding eigenvector (the first column of
Ts) is th e sam e as t he basis for t he nu ll space found in th e last section. The
other two eigenvalues a re t he r esult of applying the quadr atic formu la to
x^264/45*x+253/2160
which is the quadratic factor in factor(poly(H)).
syms xg = simple(factor(poly(H))/x);
solve(g)
Closed form symbolic expressions for t he eigenvalu es a re possible only when
the characteristic polynomial can be expressed as a product of rational
polynomials of degree four or less. The Rosser m at rix is a class ic nu mer ical
analysis test m atr ix that happens to i llustrate th is requirem ent. The
statem ent
R = sym(gallery('rosser'))
generates
R =
[ 611 196 192 407 8 52 49 29]
[ 196 899 113 192 71 43 8 44]
[192 113 899 196 61 49 8 52]
[ 407 192 196 611 8 44 59 23][ 8 71 61 8 411 599 208 208]
[ 52 43 49 44 599 411 208 208]
[ 49 8 8 59 208 208 99 911]
[ 29 44 52 23 208 208 911 99]
Linear Algebra
-
8/6/2019 MATLAB Symbolic Math Toolbox
83/300
1-77
The comma nds
p = poly(R);
pretty(factor(p))
produce
2 2 2
[x (x 1020) (x 1020 x + 100)(x 1040500) (x 1000) ]
The cha ra cteristic polynomial (of degree 8) factors nicely into th e product of two
linear terms and three quadratic terms. We can see immediately that four ofth e eigenvalues a re 0, 1020, an d a double root a t 1000. The oth er four roots a re
obtained from t he r emaining quadra tics. Use
eig(R)
to find a ll these values
[ 0]
[ 1020][510+100*26^(1/2)]
[510100*26^(1/2)]
[ 10*10405^(1/2)]
[ 10*10405^(1/2)]
[ 1000]
[ 1000]
The Rosser ma tr ix is not a typical example; it is rar e for a full 8-by-8 mat rix to
have a characteristic polynomial that factors into such simple form. If we
change t he t wo corn er elemen ts ofR from 29 to 30 with the comma nds
S = R; S(1,8) = 30; S(8,1) = 30;
a n d t h e n t r y
p = poly(S)
we findp =
40250968213600000+51264008540948000*x
1082699388411166000*x^2+4287832912719760*x^3
5327831918568*x^4+82706090*x^5+5079941*x^6
4040*x^7+x^8
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
84/300
1-78
We also find that factor(p) is p itself. That is, the characteristic polynomial
cannot be factored over the rationals.
For this modified Rosser matrix
F = eig(S)
r e t u r n s
F =
[ 1020.0532142558915165931894252600]
[ .17053529728768998575200874607757][ .21803980548301606860857564424981]
[ 999.94691786044276755320289228602]
[ 1000.1206982933841335712817075454]
[ 1019.5243552632016358324933278291]
[ 1019.9935501291629257348091808173]
[ 1020.4201882015047278185457498840]
Notice that these values are close to the eigenvalues of the original Rossermat rix. Fur ther , the numer ical values ofF ar e a r esu lt of Map les float ing-point
ar ithm etic. Consequ ent ly, differen t set tings ofdigits do not alter th e num ber
of int egers t o the r ight of th e decima l place.
It is a lso possible to try t o compu te eigenva lues of symbolic ma tr ices, but closed
form solutions a re r ar e. The Givens tr ansforma tion is generat ed as t he ma tr ix
exponential of the elementar y mat rix
The Symbolic Math Toolbox commands
syms t
A = sym([0 1; 1 0]);
G = expm(t*A)
r e t u r n
[ cos(t), sin(t)]
[ sin(t), cos(t)]
A 0 1
1 0=
Linear Algebra
-
8/6/2019 MATLAB Symbolic Math Toolbox
85/300
1-79
Next, the comma nd
g = eig(G)
produces
g =
[ cos(t)+(cos(t)^21)^(1/2)]
[ cos(t)(cos(t)^21)^(1/2)]
We can use simple to simplify this form ofg. Indeed, repeated application of
simple
for j = 1:4
[g,how] = simple(g)
end
produces th e best r esult
g =
[ cos(t)+(sin(t)^2)^(1/2)][ cos(t)(sin(t)^2)^(1/2)]
how =
simplify
g =
[ cos(t)+i*sin(t)]
[ cos(t)i*sin(t)]
how =
radsimp
g =
[ exp(i*t)]
[ 1/exp(i*t)]
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
86/300
1-80
how =
convert(exp)
g =
[ exp(i*t)]
[ exp(i*t)]
how =
simplify
Notice t he first applicat ion ofsimple uses simplify to produce a sum of sines
an d cosines. Next, simple invokes radsimp to pr oduce cos(t) + i*sin(t) for
the first eigenvector. The third application ofsimple uses convert(exp) t o
cha nge t he sines an d cosines t o complex exponen tia ls. The last applicat ion of
simple uses simplify to obtain the final form.
Linear Algebra
-
8/6/2019 MATLAB Symbolic Math Toolbox
87/300
1-81
Jordan Canonical FormThe J orda n canonical form results from at tempts to diagona lize a m atr ix by a
similarity tr ansforma tion. For a given mat rixA, find a n onsingular m atr ix V,
so tha t inv(V)*A*V, or, more succinctly, J = V\A*V, is as close to diagonal as
possible. For almost all matrices, the Jordan canonical form is the diagonal
mat rix of eigenvalues and th e columns of the tr an sforma tion m atr ix are th e
eigenvectors. This always ha ppens if the mat rix is symmetric or if it ha s
distinct eigenvalues. Some nonsymmetric matrices with multiple eigenvalues
cannot be diagonalized. The Jordan form has the eigenvalues on its diagonal,
but some of th e superdia gona l element s ar e one, instea d of zero. The sta tem ent
J = jordan(A)
computes the Jordan canonical form ofA. The statem ent
[V,J] = jordan(A)
also computes the similarity transformation. The columns ofV a r e t h e
genera lized eigenvectors ofA.
The J ordan form is extrem ely sensitive to pert ur bat ions. Almost an y cha nge in
A causes its J ordan form to be diagona l. This mak es it very difficult to comput e
the Jordan form reliably with floating-point arithmetic. It also implies thatA
mu st be k nown exactly (i.e., without r oun d-off err or, etc.). Its element s mu st be
integers, or ratios of small integers. In particular, the variable-precision
calculation, jordan(vpa(A)), is not allowed.
For example, let
A = sym([12,32,66,116;25,76,164,294;
21,66,143,256;6,19,41,73])
A =
[ 12, 32, 66, 116]
[ 25, 76, 164, 294]
[ 21, 66, 143, 256]
[ 6, 19, 41, 73]
Then
[V,J] = jordan(A)
1 Tutorial
-
8/6/2019 MATLAB Symbolic Math Toolbox
88/300
1-82
produces
V =
[ 4, 2, 4, 3]
[ 6, 8, 11, 8]
[ 4, 7, 10, 7]
[ 1, 2, 3, 2]
J =
[ 1, 1, 0, 0]
[ 0, 1, 0, 0][ 0, 0, 2, 1]
[ 0, 0, 0, 2]
ThereforeA has a double eigenvalue at 1, with a single Jordan block, and a
double eigenvalue at 2, also with a single Jordan block. The matrix has only
two eigenvectors, V(:,1) a n d V(:,3). They satisfy
A*V(:,1) = 1*V(:,1)
A*V(:,3) = 2*V(:,3)
The other two columns ofV are generalized eigenvectors of grade 2. They
satisfy
A*V(:,2) = 1*V(:,2) + V(:,1)
A*V(:,4) = 2*V(:,4) + V(:,3)
In m ath emat ical notation, with vj = v(:,j), th e column s ofV and eigenvalues
satisfy t he relationships
Singular Val