MATLAB 2023b Symbolic Math Toolbox
MATLAB 2023b Symbolic Math Toolbox
User's Guide
R2023b
How to Contact MathWorks
Phone: 508-647-7000
Getting Started
1
Symbolic Math Toolbox Product Description . . . . . . . . . . . . . . . . . . . . . . . 1-2
v
Symbolic Computations in MATLAB
2
Find Symbolic Variables in Expressions, Functions, and Matrices . . . . . . 2-2
Find a Default Symbolic Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Change Output Display Format of Symbolic Results in the Live Editor . 2-11
vi Contents
The Physics of the Damped Harmonic Oscillator . . . . . . . . . . . . . . . . . . . 2-78
Mathematics
3
Solve Algebraic Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Solve an Equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Return the Full Solution to an Equation . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Work with the Full Solution, Parameters, and Conditions Returned by solve
...................................................... 3-4
Visualize and Plot Solutions Returned by solve . . . . . . . . . . . . . . . . . . . . . 3-5
Simplify Complicated Results and Improve Performance . . . . . . . . . . . . . . 3-6
vii
Solve a Second-Order Differential Equation Numerically . . . . . . . . . . . . 3-52
viii Contents
Explore Single-Period Asset Arbitrage . . . . . . . . . . . . . . . . . . . . . . . . . . 3-156
Differentiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-171
Derivatives of Expressions with Several Variables . . . . . . . . . . . . . . . . . 3-172
More Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-173
Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-176
Integration with Real Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-178
Integration with Complex Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . 3-179
High-Precision Numerical Integration Using Variable-Precision Arithmetic
.................................................... 3-180
Limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-209
One-Sided Limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-209
Differentiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-227
Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-235
ix
Symbolic Matrix Computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-267
Eigenvalues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-282
Graphics
4
Create Plots of Symbolic Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
x Contents
Simulate the Motion of the Periodic Swing of a Pendulum . . . . . . . . . . . 4-38
Code Generation
5
Generate C or Fortran Code from Symbolic Expressions . . . . . . . . . . . . . . 5-2
xi
MuPAD to MATLAB Migration
6
MuPAD Engines and MATLAB Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Functions
7
xii Contents
1
Getting Started
Symbolic Math Toolbox provides functions for solving, plotting, and manipulating symbolic math
equations. You can create, run, and share symbolic math code. In the MATLAB Live Editor, you can
get next-step suggestions for symbolic workflows. The toolbox provides functions in common
mathematical areas such as calculus, linear algebra, algebraic and differential equations, equation
simplification, and equation manipulation.
Symbolic Math Toolbox lets you analytically perform differentiation, integration, simplification,
transforms, and equation solving. You can perform dimensional computations and convert between
units. Your computations can be performed either analytically or using variable-precision arithmetic,
with the results displayed in mathematical typeset.
You can share your symbolic work with other MATLAB users as live scripts or convert them to HTML,
Word, LaTex or PDF documents. You can generate MATLAB functions, Simulink® Function blocks, and
Simscape™ equations directly from symbolic expressions.
1-2
Create Symbolic Numbers, Variables, and Expressions
This example shows how to create symbolic numbers, variables, and expressions. To learn how to
work with symbolic math, see “Perform Symbolic Computations” on page 1-28.
You can create symbolic numbers by using sym. Symbolic numbers are exact representations, unlike
floating-point numbers.
Create symbolic numbers by using sym and compare them to the same floating-point numbers.
a1Sym = sym(1/3)
a1Sym =
1
3
a1 = 1/3
a1 = 0.3333
a2Sym = sym(pi)
a2Sym = π
a2 = pi
a2 = 3.1416
The symbolic numbers are represented in exact rational form, while the floating-point numbers are
decimal approximations.
Calculations on symbolic numbers are exact. Demonstrate this exactness by finding sin(pi)
symbolically and numerically. The symbolic result is exact, while the numeric result is an
approximation.
bSym = sin(sym(pi))
bSym = 0
b = sin(pi)
b = 1.2246e-16
When you use sym on a numeric input, the numeric expression is first evaluated to the MATLAB®
default double-precision number that can be less accurate. Then, sym is applied on that double-
precision number. To represent an exact number without evaluating it to double precision, use a
character vector with quotes. For example, create a symbolic number to represent a very large
integer exactly.
inaccurateNum = sym(123456789012345678)
inaccurateNum = 123456789012345680
accurateNum = sym('123456789012345678')
accurateNum = 123456789012345678
1-3
1 Getting Started
You can also create symbolic complex numbers, by specifying the imaginary part of a number as 1i,
2i, and so on.
sym('1234567 + 1i')
ans = 1234567 + i
To learn more about symbolic representation of numbers, see “Numeric to Symbolic Conversion” on
page 2-29.
You can create symbolic numbers with variable-precision floating-point arithmetic by using vpa. By
default, vpa calculates values to 32 significant digits.
piVpa = vpa(pi)
piVpa = 3.1415926535897932384626433832795
When you use vpa on a numeric expression, such as log(2), the expression is first evaluated to the
MATLAB default double-precision number that has less than 32 significant digits. Then, vpa is
applied on that double-precision number, which can be less accurate. For more accurate results,
convert double-precision numbers in an expression to symbolic numbers with sym and then use vpa
to evaluate the results with variable precision. For example, find log(2) with 17- and 20- digit
precision.
vpaOnDouble = vpa(log(2))
vpaOnDouble = 0.69314718055994528622676398299518
vpaOnSym_17 = vpa(log(sym(2)),17)
vpaOnSym_17 = 0.69314718055994531
vpaOnSym_20 = vpa(log(sym(2)),20)
vpaOnSym_20 = 0.69314718055994530942
When you convert large numbers, use quotes to represent them exactly.
inaccurateNum = vpa(123456789012345678)
inaccurateNum = 123456789012345680.0
accurateNum = vpa('123456789012345678')
accurateNum = 123456789012345678.0
You can create symbolic variables using either syms or sym. Typical uses of these functions include:
• sym – Create numbered symbolic variables, symbolic variables in MATLAB functions, or symbolic
numbers whose values differ from their names in the MATLAB workspace.
• syms – Create fresh symbolic variables for interactive symbolic workflows, that is, for symbolic
variable creation at the MATLAB command line or in MATLAB live scripts. A fresh symbolic
variable does not have any assumptions.
1-4
Create Symbolic Numbers, Variables, and Expressions
The syms command is shorthand for the sym syntax, but the two functions handle assumptions
differently. syms clears the assumptions when creating variables. However, recreating a variable
using sym does not clear its assumptions. For more details about the differences of these two
functions, see “Choose syms or sym Function” on page 2-4.
Create the symbolic variables x and y using syms and sym, respectively.
syms x
y = sym('y')
y = y
The first command creates a symbolic variable x in the MATLAB workspace with the value x assigned
to the variable x. The second command creates a symbolic variable y with the value y.
With syms, you can create multiple variables in one command. Create the variables a, b, and c.
syms a b c
If you want to create a MATLAB array of numbered symbolic variables, you can use the sym or the
syms syntax.
Use sym to create an array of many numbered symbolic variables. Clear the workspace. Create a row
vector containing the symbolic variables a1, …, a10 and assign it to the MATLAB variable A. Display
the variable in the MATLAB workspace.
clear
A = sym('a',[1 10])
A = a1 a2 a3 a4 a5 a6 a7 a8 a9 a10
whos
A 1x10 8 sym
Use syms to create many fresh symbolic variables with corresponding variable names in the MATLAB
workspace. Clear the workspace. Create the fresh symbolic variables a1, ..., a10. Display the
variables in the MATLAB workspace.
clear
syms a [1 10]
whos
a 1x10 8 sym
a1 1x1 8 sym
a10 1x1 8 sym
a2 1x1 8 sym
a3 1x1 8 sym
a4 1x1 8 sym
1-5
1 Getting Started
a5 1x1 8 sym
a6 1x1 8 sym
a7 1x1 8 sym
a8 1x1 8 sym
a9 1x1 8 sym
The MATLAB workspace contains 10 MATLAB variables in the workspace that are symbolic variables.
The syms command is a convenient shorthand for the sym syntax, and its typical use is to create fresh
symbolic variables for interactive symbolic workflows. Use the sym syntax to create the following:
1+ 5
Suppose you want to use a symbolic variable to represent the golden ratio φ = 2
.
phi = (1 + sqrt(sym(5)))/2;
Now you can perform various mathematical operations on phi. For example:
f = phi^2 - phi - 1
f =
5 1 2 5 3
+ − −
2 2 2 2
Next, suppose you want to study the quadratic function f = ax2 + bx + c. First, create the symbolic
variables a, b, c, and x.
syms a b c x
Then, create a symbolic expression f that represents the arithmetical expression ax2 + bx + c.
f = a*x^2 + b*x + c
f = a x2 + b x + c
x_0 =
2
b+ b −4ac
−
2a
2
b− b −4ac
−
2a
1-6
Create Symbolic Numbers, Variables, and Expressions
You can also apply a mathematical function to an arithmetical expression. For example, apply the
Bessel function of the first kind J0 to the arithmetical expression f and find its derivative with respect
to x.
J_0 = besselj(0,f)
J_0 = J0 a x2 + b x + c
DJ_0 = diff(J_0,x)
DJ_0 = − J1 a x2 + b x + c b + 2 a x
To create a symbolic number in a symbolic expression, use sym. Do not use syms to create a symbolic
expression that is a constant. For example, to create an expression whose value is 5, enter f =
sym(5). The command f = 5 does not define f as a symbolic expression.
You can also create symbolic expressions from strings by using str2sym when reading expressions
from text files or when specifying numbers exactly.
If you set a variable equal to a symbolic expression and then apply the syms command to the
variable, MATLAB removes the previously defined expression from the variable.
syms a b
f = a + b
f = a+b
If you recreate f, then MATLAB removes the value a + b from the expression f.
syms f
f
f = f
You can use the syms command to clear variables of definitions that you previously assigned to them
in your MATLAB session. syms clears the assumptions of the variables. These assumptions (which can
be real, integer, rational, and positive) are stored separately from the symbolic object. However,
recreating a variable using sym does not clear its assumptions. For more information, see “Use
Assumptions on Symbolic Variables” on page 1-41.
See Also
sym | syms | vpa
More About
• “Create Symbolic Functions” on page 1-9
• “Create Symbolic Matrices” on page 1-11
• “Create Symbolic Matrix Variables” on page 1-13
• “Use Symbolic Objects to Represent Mathematical Objects” on page 1-20
1-7
1 Getting Started
1-8
Create Symbolic Functions
Note Symbolic functions must be functions of symbolic variables. The Symbolic Math Toolbox
currently does not support composite symbolic functions, or symbolic functions that are functions of
another symbolic functions.
Create a symbolic function f with variables x and y by using syms. Creating f automatically creates
x and y.
syms f(x,y)
f(x,y) = x^2*y
f(x, y) =
x^2*y
f(3,2)
ans =
18
Symbolic functions accept array inputs. Calculate f for multiple values of x and y.
xVal = 1:5;
yVal = 3:7;
f(xVal,yVal)
ans =
[ 3, 16, 45, 96, 175]
You can differentiate symbolic functions, integrate or simplify them, substitute their arguments with
values, and perform other mathematical operations. For example, find the derivative of f(x,y) with
respect to x. The result dfx is also a symbolic function.
dfx = diff(f,x)
dfx(x,y) =
2*x*y
Calculate df(x,y) at x = y + 1.
dfx(y+1,y)
ans =
2*y*(y + 1)
If you are creating a constant function, such as f(x,y) = 1, you must first create f(x,y). If you do
not create f(x,y), then the assignment f(x,y) = 1 throws an error.
1-9
1 Getting Started
See Also
More About
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Create Symbolic Matrices” on page 1-11
• “Create Symbolic Matrix Variables” on page 1-13
• “Use Symbolic Objects to Represent Mathematical Objects” on page 1-20
• “Perform Symbolic Computations” on page 1-28
• “Use Assumptions on Symbolic Variables” on page 1-41
1-10
Create Symbolic Matrices
syms a b c
A = [a b c; c a b; b c a]
A =
[ a, b, c]
[ c, a, b]
[ b, c, a]
Since matrix A is circulant, the sum of elements over each row and each column is the same. Find the
sum of all the elements of the first row:
sum(A(1,:))
ans =
a + b + c
To check if the sum of the elements of the first row equals the sum of the elements of the second
column, use the isAlways function:
isAlways(sum(A(1,:)) == sum(A(:,2)))
ans =
logical
1
From this example, you can see that using symbolic objects is very similar to using regular MATLAB
numeric objects.
1-11
1 Getting Started
A = sym('A', [2 4])
A =
[ A1_1, A1_2, A1_3, A1_4]
[ A2_1, A2_2, A2_3, A2_4]
To control the format of the generated names of matrix elements, use %d in the first argument:
A = sym('A%d%d', [2 4])
A =
[ A11, A12, A13, A14]
[ A21, A22, A23, A24]
A = hilb(3)
A =
1.0000 0.5000 0.3333
0.5000 0.3333 0.2500
0.3333 0.2500 0.2000
By applying sym to A
A = sym(A)
you can obtain the precise symbolic form of the 3-by-3 Hilbert matrix:
A =
[ 1, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
For more information on numeric to symbolic conversions, see “Numeric to Symbolic Conversion” on
page 2-29.
See Also
More About
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Create Symbolic Functions” on page 1-9
• “Create Symbolic Matrix Variables” on page 1-13
• “Use Symbolic Objects to Represent Mathematical Objects” on page 1-20
• “Perform Symbolic Computations” on page 1-28
• “Use Assumptions on Symbolic Variables” on page 1-41
1-12
Create Symbolic Matrix Variables
Since R2021a
Symbolic matrix variables represent matrices, vectors, and scalars in compact matrix notation. When
mathematical formulas involve matrices and vectors, writing them using symbolic matrix variables is
more concise and clear than writing them componentwise. When you do this, you can take vector-
based expressions and equations from textbooks, enter them in Symbolic Math Toolbox™, perform
mathematical operations on them, and derive further equations from them.
Derived equations involving symbolic matrix variables are displayed in typeset as they would be in
textbooks. For example, create three symbolic matrix variables A, x, and y by using syms. Find the
differential of the expression yT Ax with respect to the vector x.
syms A [3 4] matrix
syms x [4 1] matrix
syms y [3 1] matrix
eq = y.'*A*x
eq = yT A x
D = diff(eq,x)
D = yT A
Comparison Between Matrix of Symbolic Scalar Variables and Symbolic Matrix Variables
Symbolic matrix variables are an alternative to symbolic scalar variables. The two options are of
different types and displayed differently.
For example, create two 2-by-3 matrices of symbolic scalar variables by using syms. For brevity,
matrices of symbolic scalar variables are sometimes called symbolic matrices. These matrices are
displayed by listing their components.
syms A B [2 3]
A
A =
A1, 1 A1, 2 A1, 3
A2, 1 A2, 2 A2, 3
B =
B1, 1 B1, 2 B1, 3
B2, 1 B2, 2 B2, 3
class(A)
ans =
'sym'
1-13
1 Getting Started
Applying symbolic math operations to these matrices can result in a complex solution expressed in
terms of the matrix components. For example, multiply the matrices A and B'.
C = A*B'
C =
A1, 1 B1, 1 + A1, 2 B1, 2 + A1, 3 B1, 3 A1, 1 B2, 1 + A1, 2 B2, 2 + A1, 3 B2, 3
A2, 1 B1, 1 + A2, 2 B1, 2 + A2, 3 B1, 3 A2, 1 B2, 1 + A2, 2 B2, 2 + A2, 3 B2, 3
To create symbolic matrix variables of the same size, use the syms command followed by the variable
names, their size, and the matrix keyword. Symbolic matrix variables are displayed in bold to
distinguish them from symbolic scalar variables.
syms A B [2 3] matrix
A
A = A
B = B
class(A)
ans =
'symmatrix'
Applying symbolic math operations to symbolic matrix variables results in a concise display. For
example, multiply A and B'.
C = A*B'
T
C = A B
Symbolic matrix variables are recognized as noncommutative objects. They support common math
operations, and you can use these operations to build symbolic matrix variable expressions.
syms A B [2 2] matrix
A*B - B*A
ans = A B − B A
For example, check the commutation relation for multiplication between two symbolic matrix
variables.
isequal(A*B,B*A)
ans = logical
0
isequal(A+B,B+A)
1-14
Create Symbolic Matrix Variables
ans = logical
1
If an operation has any arguments of type symmatrix, the result is automatically converted to type
symmatrix. For example, multiply a matrix A that is represented by symbolic matrix variable and a
scalar c that is represented by symbolic scalar variable. The result is of type symmatrix.
syms A [2 2] matrix
syms c
class(A)
ans =
'symmatrix'
class(c)
ans =
'sym'
M = c*A
M = cA
class(M)
ans =
'symmatrix'
Multiply three matrices that are represented by symbolic matrix variables. The result X is a
symmatrix object.
syms V [2 1] matrix
X = V.'*A*V
X = VT A V
class(X)
ans =
'symmatrix'
You can pass symmatrix objects as arguments to math functions. For example, perform a
mathematical operation to X by taking the differential of X with respect to V.
diff(X,V)
ans = V T AT + V T A
You can convert an array of symbolic scalar variables to a single symbolic matrix variable using the
symmatrix function. Symbolic matrix variables that are converted in this way are displayed
elementwise.
syms A [3 4]
class(A)
ans =
'sym'
1-15
1 Getting Started
B = symmatrix(A)
B =
Σ1
where
class(B)
ans =
'symmatrix'
You can create symbolic matrix variables, derive equations, and then convert the result to arrays of
symbolic scalar variables using the symmatrix2sym function.
For example, find the matrix product of two symbolic matrix variables A and B. The result X is of type
symmatrix.
syms A B [2 2] matrix
X = A*B
X = AB
class(X)
ans =
'symmatrix'
Convert the symbolic matrix variable X to array of symbolic scalar variables. The converted matrix Y
is of type sym.
Y = symmatrix2sym(X)
Y =
A1, 1 B1, 1 + A1, 2 B2, 1 A1, 1 B1, 2 + A1, 2 B2, 2
A2, 1 B1, 1 + A2, 2 B2, 1 A2, 1 B1, 2 + A2, 2 B2, 2
class(Y)
ans =
'sym'
Check that the product obtained by converting symbolic matrix variables is equal to the product of
two arrays of symbolic scalar variables.
syms A B [2 2]
isequal(Y,A*B)
ans = logical
1
1-16
Create Symbolic Matrix Variables
Indexing into a symbolic matrix variable returns corresponding matrix elements in the form of
another symbolic matrix variable.
syms A [2 3] matrix
a = A(2,3)
a = A2, 3
class(a)
ans =
'symmatrix'
Alternatively, convert the symbolic matrix variable A to a matrix of symbolic scalar variables. Then,
index into that matrix.
Asym = symmatrix2sym(A)
Asym =
A1, 1 A1, 2 A1, 3
A2, 1 A2, 2 A2, 3
asym = Asym(2,3)
asym = A2, 3
class(asym)
ans =
'sym'
isequal(a,symmatrix(asym))
ans = logical
1
Matrices like those returned by eye, zeros, and ones often have special meaning with specific
notation in symbolic workflows. Declaring these matrices as symbolic matrix variables display the
matrices in bold along with the matrix dimensions.
symmatrix(eye(3))
ans = I3
symmatrix(zeros(2,3))
ans = 02, 3
symmatrix(ones(3,5))
ans = 13, 5
1-17
1 Getting Started
If the inputs to a componentwise operation in MATLAB® are symbolic matrix variables, so is the
output. These operations are displayed in special notations which follow conventions from textbooks.
syms A B [3 3] matrix
A.*B
ans = A ⊙ B
A./B
ans = A ⊘ B
A.\B
ans = B ⊘ A
A.*hilb(3)
ans =
A ⊙ Σ1
where
1 1
1
2 3
1 1 1
Σ1 =
2 3 4
1 1 1
3 4 5
A.^(2*ones(3))
∘ 2 13, 3
ans = A
A.^B
ans = A ∘ B
kron(A,B)
ans = A ⊗ B
adjoint(A)
ans = adj A
trace(A)
ans = Tr A
See Also
syms | symmatrix | symmatrix2sym
More About
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Create Symbolic Functions” on page 1-9
1-18
Create Symbolic Matrix Variables
1-19
1 Getting Started
• symbolic number
• symbolic scalar variable, function, and expression
• symbolic equation
• symbolic vector and matrix
• symbolic matrix variable
• symbolic matrix function
Symbolic Number
Defining a number as a symbolic number instructs MATLAB to treat the number as an exact form
instead of using a numeric approximation. For example, use a symbolic number to represent the
−1
argument of an inverse trigonometric function θ = sin (1/ 2).
a = sym(1/sqrt(2))
a =
2^(1/2)/2
Find the inverse sine of a. The result is the symbolic number pi/4.
thetaSym = asin(a)
thetaSym =
pi/4
You can convert a symbolic number to variable-precision arithmetic by using vpa. The result is a
decimal number with 32 significant digits.
thetaVpa = vpa(thetaSym)
thetaVpa =
0.78539816339744830961566084581988
To convert the symbolic number to a double-precision number, use double. For more information
about whether to use numeric or symbolic arithmetic, see “Choose Numeric or Symbolic Arithmetic”
on page 2-32.
thetaDouble = double(thetaSym)
thetaDouble =
0.7854
1-20
Use Symbolic Objects to Represent Mathematical Objects
Create a symbolic scalar variable x using syms. You can also use sym to create a symbolic scalar
variable. For more information about whether to use syms or sym, see “Choose syms or sym
Function” on page 2-4.
Define a symbolic expression x^2 + x - 2 to represent the right side of the quadratic equation and
assign it to f(x). The identifier f(x) now refers to a symbolic function that represents the quadratic
function. A symbolic function accepts scalars as input arguments.
syms x
f(x) = x^2 + x - 2
f(x) =
x^2 + x -2
You can then evaluate the quadratic function by providing its input argument inside the parentheses.
For example, evaluate f(2).
fVal = f(2)
fVal =
4
You can also solve the quadratic equation f (x) = 0. Use solve to find the roots of the quadratic
equation. solve returns the two solutions as a vector of two symbolic numbers.
sols = solve(f)
sols =
-2
1
Symbolic Equation
Defining a mathematical equation as a symbolic equation enables you to find the solution of the
equation. For example, use a symbolic equation to solve the trigonometric problem 2sin(t)cos(t) = 1.
Create a symbolic function g(t) using syms. Assign the symbolic expression 2*sin(t)*cos(t) to
g(t).
syms g(t)
g(t) = 2*sin(t)*cos(t)
1-21
1 Getting Started
g(t) =
2*cos(t)*sin(t)
To define the equation, use the == operator and assign the mathematical relation g(t) == 1 to eqn.
The identifier eqn is a symbolic equation that represents the trigonometric problem.
eqn = g(t) == 1
eqn =
2*cos(t)*sin(t) == 1
sol = solve(eqn)
sol =
pi/4
x + 2y = u
4x + 5y = v
You can represent the system of equations as a vector of two symbolic equations. You can also
represent the system of equations as a matrix problem involving a matrix of symbolic numbers and a
vector of symbolic variables. For brevity, any vector of symbolic objects is called a symbolic vector
and any matrix of symbolic objects is called a symbolic matrix.
Create two symbolic equations eq1 and eq2. Combine the two equations into a symbolic vector.
syms u v x y
eq1 = x + 2*y == u;
eq2 = 4*x + 5*y == v;
eqns = [eq1, eq2]
eqns =
[x + 2*y == u, 4*x + 5*y == v]
Use solve to find the solutions of the system of equations represented by eqns. solve returns a
structure S with fields named after each of the variables in the equations. You can access the
solutions using dot notation, as S.x and S.y.
S = solve(eqns);
S.x
ans =
(2*v)/3 - (5*u)/3
S.y
1-22
Use Symbolic Objects to Represent Mathematical Objects
ans =
(4*u)/3 - v/3
Another way to solve the system of linear equations is to convert it to matrix form. Use
equationsToMatrix to convert the system of equations to matrix form and assign the output to A
and b. Here, A is a symbolic matrix and b is a symbolic vector. Solve the matrix problem by using the
matrix division \ operator.
[A,b] = equationsToMatrix(eqns,x,y)
A =
[1, 2]
[4, 5]
b =
u
v
sols = A\b
sols =
(2*v)/3 - (5*u)/3
(4*u)/3 - v/3
α = yTAx
∂α
= y TA
∂x
∂α
= xTA T
∂y
Symbolic matrix variables represent matrices, vectors, and scalars in compact matrix notation.
Symbolic matrix variables offer a concise display in typeset and show mathematical formulas with
more clarity. You can enter vector- and matrix-based expressions as symbolic matrix variables in
Symbolic Math Toolbox.
Create three symbolic matrix variables x, y, and A using the syms command with the matrix syntax.
Nonscalar symbolic matrix variables are displayed as bold characters in the Command Window and in
the Live Editor.
syms x [4 1] matrix
syms y [3 1] matrix
syms A [3 4] matrix
1-23
1 Getting Started
x
y
A
x =
x
y =
y
A =
A
Define alpha. Find the differential of alpha with respect to the vectors x and y that are represented
by the symbolic matrix variables x and y.
alpha = y.'*A*x
alpha =
y.'*A*x
Dx = diff(alpha,x)
Dx =
y.'*A
Dy = diff(alpha,y)
Dy =
x.'*A.'
Substitute y with [1; 2; 3] in Dx and substitute x with [-1; 2; 0; 1] in Dy using subs. When
evaluating a symbolic expression, you must substitute values that have the same size as the defined
symbolic matrix variables.
Dx = subs(Dx,y,[1; 2; 3])
Dx =
symmatrix([1;2;3]).'*A
Dy = subs(Dy,x,[-1; 2; 0; 1])
Dx =
symmatrix([-1;2;0;1]).'*A.'
f (A) = A2 − 3A + I2
1-24
Use Symbolic Objects to Represent Mathematical Objects
Create a 2-by-2 symbolic matrix variable A using the syms command with the matrix syntax. Create
a symbolic matrix function f(A) that accepts A as an input argument using the syms command with
the matrix keepargs syntax to keep the previous definition of A.
syms A 2 matrix
syms f(A) 2 matrix keepargs
f(A) =
Evaluate the function for the matrix value A = [1 2; -2 -1]. When evaluating a symbolic matrix
function, you must substitute values that have the same size as the defined input arguments.
fEval =
Convert the evaluated function from the symmatrix data type to the sym data type.
fSym = symmatrix2sym(fEval)
fSym =
[-4, -6]
[ 6, 2]
a =
2^(1/2)/2
theta =
pi/4
Symbolic scalar variable syms x y u v 1-by-1 sym
1-25
1 Getting Started
expr =
x^2 + x - 2
expr2 =
2*cos(x)*sin(x)
Symbolic equation syms u v x y 1-by-1 sym
eq1 = x + 2*y == u
eq2 = 4*x + 5*y == v
eq1 =
x + 2*y == u
eq2 =
4*x + 5*y == v
Symbolic vector syms u v 1-by-n or m-by-1, sym
b = [u v] where m is the row
size and n is the
b =
[u, v]
column size
1-26
Use Symbolic Objects to Represent Mathematical Objects
A(:,:,2) =
A1_2
A2_2
Symbolic matrix variable syms A B [2 3] matrix m-by-n, where m is symmatrix
A the row size and n
(since R2021a) B is the column size
A =
A
B =
B
Symbolic matrix function syms X Y [2 2] matrix • Size of • Data type of
syms f(X,Y) [2 2] matrix keepargs
unevaluated unevaluated
(since R2022a) f(X,Y) = X*Y - Y*X matrix function, matrix function,
f(X, Y) =
such as such as
X*Y - Y*X size(f), is 1- class(f), is
by-1. symfunmatrix
• Size of .
evaluated • Data type of
function, such evaluated
as function, such
size(f(X,Y)) as
, is m-by-n, class(f(X,Y)
where m is the ), is
row size and n symmatrix.
is the column
size.
See Also
syms | sym | symfun | symmatrix | symfunmatrix | symfunmatrix2symfun | symmatrix2sym |
str2sym
More About
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Create Symbolic Functions” on page 1-9
• “Create Symbolic Matrices” on page 1-11
• “Create Symbolic Matrix Variables” on page 1-13
• “Choose syms or sym Function” on page 2-4
• “Choose Numeric or Symbolic Arithmetic” on page 2-32
1-27
1 Getting Started
In this section...
“Differentiate Symbolic Expressions” on page 1-28
“Integrate Symbolic Expressions” on page 1-29
“Solve Equations” on page 1-30
“Simplify Symbolic Expressions” on page 1-32
“Substitutions in Symbolic Expressions” on page 1-33
“Plot Symbolic Functions” on page 1-35
For in-depth information on taking symbolic derivatives see “Differentiation” on page 3-171.
To differentiate a symbolic expression, use the diff command. The following example illustrates how
to take a first derivative of a symbolic expression:
syms x
f = sin(x)^2;
diff(f)
ans =
2*cos(x)*sin(x)
Partial Derivatives
For multivariable expressions, you can specify the differentiation variable. If you do not specify any
variable, MATLAB chooses a default variable by its proximity to the letter x:
syms x y
f = sin(x)^2 + cos(y)^2;
diff(f)
ans =
2*cos(x)*sin(x)
For the complete set of rules MATLAB applies for choosing a default variable, see “Find a Default
Symbolic Variable” on page 2-2.
1-28
Perform Symbolic Computations
syms x y
f = sin(x)^2 + cos(y)^2;
diff(f, y)
ans =
-2*cos(y)*sin(y)
To take a second derivative of the symbolic expression f with respect to a variable y, enter:
syms x y
f = sin(x)^2 + cos(y)^2;
diff(f, y, 2)
ans =
2*sin(y)^2 - 2*cos(y)^2
You get the same result by taking derivative twice: diff(diff(f, y)). To take mixed derivatives,
use two differentiation commands. For example:
syms x y
f = sin(x)^2 + cos(y)^2;
diff(diff(f, y), x)
ans =
0
For in-depth information on the int command including integration with real and complex
parameters, see “Integration” on page 3-176.
Suppose you want to integrate a symbolic expression. The first step is to create the symbolic
expression:
syms x
f = sin(x)^2;
int(f)
ans =
x/2 - sin(2*x)/4
If the expression depends on multiple symbolic variables, you can designate a variable of integration.
If you do not specify any variable, MATLAB chooses a default variable by the proximity to the letter x:
1-29
1 Getting Started
syms x y n
f = x^n + y^n;
int(f)
ans =
x*y^n + (x*x^n)/(n + 1)
For the complete set of rules MATLAB applies for choosing a default variable, see “Find a Default
Symbolic Variable” on page 2-2.
You also can integrate the expression f = x^n + y^n with respect to y
syms x y n
f = x^n + y^n;
int(f, y)
ans =
x^n*y + (y*y^n)/(n + 1)
syms x y n
f = x^n + y^n;
int(f, n)
ans =
x^n/log(x) + y^n/log(y)
Definite Integrals
To find a definite integral, pass the limits of integration as the final two arguments of the int
function:
syms x y n
f = x^n + y^n;
int(f, 1, 10)
ans =
piecewise(n == -1, log(10) + 9/y, n ~= -1,...
(10*10^n - 1)/(n + 1) + 9*y^n)
syms x
int(sin(sinh(x)))
ans =
int(sin(sinh(x)), x)
Solve Equations
You can solve different types of symbolic equations including:
1-30
Perform Symbolic Computations
For in-depth information on solving symbolic equations including differential equations, see “Equation
Solving”.
Use the double equal sign (==) to define an equation. Then you can solve the equation by calling
the solve function. For example, solve this equation:
syms x
solve(x^3 - 6*x^2 == 6 - 11*x)
ans =
1
2
3
If you do not specify the right side of the equation, solve assumes that it is zero:
syms x
solve(x^3 - 6*x^2 + 11*x - 6)
ans =
1
2
3
If an equation contains several symbolic variables, you can specify a variable for which this equation
should be solved. For example, solve this multivariable equation with respect to y:
syms x y
solve(6*x^2 - 6*x^2*y + x*y^2 - x*y + y^3 - y^2 == 0, y)
ans =
1
2*x
-3*x
If you do not specify any variable, you get the solution of an equation for the alphabetically closest to
x variable. For the complete set of rules MATLAB applies for choosing a default variable see “Find a
Default Symbolic Variable” on page 2-2.
syms x y z
[x, y, z] = solve(z == 4*x, x == y, z == x^2 + y^2)
x =
0
2
y =
0
1-31
1 Getting Started
z =
0
8
phi = (1 + sqrt(sym(5)))/2;
f = phi^2 - phi - 1
returns
f =
(5^(1/2)/2 + 1/2)^2 - 5^(1/2)/2 - 3/2
simplify(f)
ans =
0
syms x
f = (x ^2- 1)*(x^4 + x^3 + x^2 + x + 1)*(x^4 - x^3 + x^2 - x + 1);
expand(f)
ans =
x^10 - 1
The factor simplification function shows the polynomial roots. If a polynomial cannot be factored
over the rational numbers, the output of the factor function is the standard polynomial form. For
example, to factor the third-order polynomial, enter:
syms x
g = x^3 + 6*x^2 + 11*x + 6;
factor(g)
ans =
[ x + 3, x + 2, x + 1]
The nested (Horner) representation of a polynomial is the most efficient for numerical evaluations:
1-32
Perform Symbolic Computations
syms x
h = x^5 + x^4 + x^3 + x^2 + x;
horner(h)
ans =
x*(x*(x*(x*(x + 1) + 1) + 1) + 1)
For a list of Symbolic Math Toolbox simplification functions, see “Choose Function to Rearrange
Expression” on page 3-119.
You can substitute a symbolic variable with a numeric value by using the subs function. For example,
evaluate the symbolic expression f at the point x = 1/3:
syms x
f = 2*x^2 - 3*x + 1;
subs(f, 1/3)
ans =
2/9
f =
2*x^2 - 3*x + 1
When your expression contains more than one variable, you can specify the variable for which you
want to make the substitution. For example, to substitute the value x = 3 in the symbolic expression
syms x y
f = x^2*y + 5*x*sqrt(y);
subs(f, x, 3)
ans =
9*y + 15*y^(1/2)
You also can substitute one symbolic variable for another symbolic variable. For example to replace
the variable y with the variable x, enter
subs(f, y, x)
ans =
x^3 + 5*x^(3/2)
1-33
1 Getting Started
You can also substitute a matrix into a symbolic polynomial with numeric coefficients. There are two
ways to substitute a matrix into a polynomial: element by element and according to matrix
multiplication rules.
Element-by-Element Substitution
syms x
f = x^3 - 15*x^2 - 24*x + 350;
A = [1 2 3; 4 5 6];
subs(f,A)
ans =
[ 312, 250, 170]
[ 78, -20, -118]
If you want to substitute a matrix into a polynomial using standard matrix multiplication rules, a
matrix must be square. For example, you can substitute the magic square A into a polynomial f:
syms x
f = x^3 - 15*x^2 - 24*x + 350;
2 Create the magic square matrix:
A = magic(3)
A =
8 1 6
3 5 7
4 9 2
3 Get a row vector containing the numeric coefficients of the polynomial f:
b = sym2poly(f)
b =
1 -15 -24 350
4 Substitute the magic square matrix A into the polynomial f. Matrix A replaces all occurrences of
x in the polynomial. The constant times the identity matrix eye(3) replaces the constant term of
f:
ans =
-10 0 0
0 -10 0
0 0 -10
The polyvalm command provides an easy way to obtain the same result:
polyvalm(b,A)
1-34
Perform Symbolic Computations
ans =
-10 0 0
0 -10 0
0 0 -10
To substitute a set of elements in a symbolic matrix, also use the subs command. Suppose you want
to replace some of the elements of a symbolic circulant matrix A
syms a b c
A = [a b c; c a b; b c a]
A =
[ a, b, c]
[ c, a, b]
[ b, c, a]
To replace the (2, 1) element of A with beta and the variable b throughout the matrix with variable
alpha, enter
alpha = sym('alpha');
beta = sym('beta');
A(2,1) = beta;
A = subs(A,b,alpha)
For more information, see “Substitute Elements in Symbolic Matrices” on page 3-142.
Create a 2-D line plot by using fplot. Plot the expression x3 − 6x2 + 11x − 6.
syms x
f = x^3 - 6*x^2 + 11*x - 6;
fplot(f)
1-35
1 Getting Started
Add labels for the x- and y-axes. Generate the title by using texlabel(f). Show the grid by using
grid on. For details, see “Add Title and Axis Labels to Chart”.
xlabel('x')
ylabel('y')
title(texlabel(f))
grid on
1-36
Perform Symbolic Computations
4 2
Plot the equation (x2 + y2) = (x2 − y2) over −1 < x < 1.
syms x y
eqn = (x^2 + y^2)^4 == (x^2 - y^2)^2;
fimplicit(eqn, [-1 1])
1-37
1 Getting Started
3-D Plot
x = t2sin(10t)
y = t2cos(10t)
z = t.
syms t
fplot3(t^2*sin(10*t), t^2*cos(10*t), t)
1-38
Perform Symbolic Computations
syms x y
fsurf(x^2 + y^2)
1-39
1 Getting Started
See Also
More About
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Create Symbolic Functions” on page 1-9
• “Create Symbolic Matrices” on page 1-11
• “Use Assumptions on Symbolic Variables” on page 1-41
1-40
Use Assumptions on Symbolic Variables
You can set mathematical assumptions or conditions on symbolic variables to restrict the domain and
range of the variables. This example shows how to set, check, and clear assumptions.
Default Assumption
In Symbolic Math Toolbox™, symbolic variables are complex variables by default. For example, if you
create z as a symbolic variable, then Symbolic Math Toolbox assumes that z is a complex variable.
syms z
assumptions(z)
ans =
Set Assumptions
To set mathematical assumptions or conditions on symbolic variables, use the assume function. For
example, assume that the variable x is larger than 2.
syms x
assume(x > 2)
assume replaces all previous assumptions on the variable with the new assumption. If you want to
add a new assumption to the existing assumptions, then use assumeAlso. For example, add the
assumption that x is also an integer. Now the variable x is an integer larger than 2.
assumeAlso(x,"integer")
assume and assumeAlso let you state that a variable or an expression belongs to these sets: real
numbers, rational numbers, integers, and positive numbers. You can also use assume and
assumeAlso to set mathematical conditions on symbolic variables or expressions, such as x > 2.
Alternatively, you can set assumptions when declaring symbolic variables using sym or syms, where
the assumptions are limited to these sets: real numbers, rational numbers, integers, and positive
numbers. For example, create the real symbolic variables a and b, and the positive symbolic variable
c using sym.
a = sym("a","real");
b = sym("b","real");
c = sym("c","positive");
You can also use syms to create these symbolic variables with assumptions.
syms a b real
syms c positive
1-41
1 Getting Started
To see all assumptions set on a symbolic variable, use the assumptions function with the name of
the variable as an input argument. For example, this command returns the assumptions currently set
on the variable x.
assumptions(x)
ans = x ∈ ℤ 2 < x
To see all assumptions set on all symbolic variables in the MATLAB® workspace, use assumptions
without input arguments.
assumptions
Symbolic objects and their assumptions are stored separately. When you set an assumption that the
symbolic variable x is real, you actually create a symbolic object x and the assumption that the object
is real. The object is stored in the MATLAB workspace, and the assumption is stored in the symbolic
engine. When you delete a symbolic object from the MATLAB workspace using clear, the
assumption that x is real stays in the symbolic engine.
syms x
assume(x,"real")
clear x
If you recreate a variable using sym, then the existing assumptions apply. If you recreate a variable
using syms, then the existing assumptions on that variable are cleared.
For example, the assumption that x is real causes the polynomial x^2 + 1 == 0 to have no roots.
x = sym("x");
solve(x^2 + 1 == 0, x)
ans =
The complex roots of this polynomial do not appear as solutions because the symbolic variable x still
has the assumption that x is real stored in the symbolic engine. To clear the assumption, recreate the
variable using syms.
syms x
solve(x^2 + 1 == 0, x)
ans =
−i
i
1-42
Use Assumptions on Symbolic Variables
If you want to delete both the symbolic object and its assumption, first clear the assumption on the
symbolic object using assume(x,"clear") and then clear the object using clear x.
assume(x,"clear")
clear x
For details on clearing symbolic variables, see “Clear Assumptions and Reset the Symbolic Engine”
on page 3-314.
See Also
More About
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Create Symbolic Functions” on page 1-9
• “Create Symbolic Matrices” on page 1-11
• “Perform Symbolic Computations” on page 1-28
1-43
1 Getting Started
This example provides an overview of the Symbolic Math Toolbox™ which offers a complete set of
tools for computational and analytical mathematics.
For more details see “Get Started with Symbolic Math Toolbox”. For more details on documenting and
sharing your mathematics see “Create Live Scripts in the Live Editor”.
Variables in MATLAB® are by default double-precision. The Symbolic Math Toolbox extends this by
allowing you to express numbers in exact symbolic form using sym and with variable-precision using
vpa.
1-44
Computational Mathematics in Symbolic Math Toolbox
pi/6 + pi/4
ans = 1.3090
sym(pi/6) + sym(pi/4)
ans =
5π
12
vpa(pi/6) + vpa(pi/4)
ans = 1.3089969389957471826927680763665
Symbolic variables can be used in mathematical expressions, functions and equations including
trigonometric, logarithmic, exponential, and special functions. You can create symbolic expressions
and perform mathematical calculations on them.
syms x y
log(x) + exp(y)
ans = ey + log x
y(x) =
−1 if x < 0
1 if 0 < x
Create and evaluate “Create Symbolic Functions” on page 1-9. Find the value of f at x = − 5.
syms f(x)
f(x) = x^4-2*x^3+6*x^2-2*x+10
f(x) = x4 − 2 x3 + 6 x2 − 2 x + 10
f(-5)
ans = 1045
Find the intersection between lines y1 and y2 using solve. Equate the lines using the == operator.
syms y1 y2
y1 = x+3; y2 = 3*x;
solve(y1 == y2)
ans =
3
2
Make assume on symbolic variables. There are 4 solutions to x4 = 1, two real and two complex.
Assuming that x is real and x > 0, there is only one solution.
syms x
solve(x^4 == 1)
ans =
1-45
1 Getting Started
−1
1
−i
i
assume(x,'real')
assumeAlso( x > 0)
assumptions(x)
ans = x ∈ ℝ 0 < x
solve(x^4 == 1)
ans = 1
assume(x,'clear')
The Symbolic Math Toolbox supports evaluation of mathematical functions by substituting for any
part of an expression using subs. You can substitute numeric values, other symbolic variables or
expressions, vectors, or matrices. The Symbolic Math Toolbox supports the solving of equations and
systems of equations using solve. It supports solving multivariate equations, solving inequalities and
solving with assumptions. Solutions can be found symbolically or numerically with high precision by
using variable-precision arithmetic.
syms x xo
subs(x^2+1,x,xo-1)
2
ans = xo − 1 +1
Substitute multiple values. For example, evaluate cos(a) + sin(b) − e2C by substituting
π π
a = , b = , c = − 1.
2 4
syms a b c
subs(cos(a) + sin(b) - exp(2*c), [a b c], [pi/2 pi/4 -1])
ans =
2
− e−2
2
solve(9*x^2 - 1 == 0)
ans =
1
−
3
1
3
Solve the general quadratic equation ax2 + bx + c = 0 and use subs to evaluate that solution for
a = 9, b = 0, c = − 1.
1-46
Computational Mathematics in Symbolic Math Toolbox
sol =
2
b+ b −4ac
−
2a
2
b− b −4ac
−
2a
ans =
1
−
3
1
3
Solve equations symbolically or with variable-precision arithmetic when exact results or high
precision is needed. The graph of f x = 6x7 − 2x6 + 3x3 − 8 is very flat near its root.
syms x f(x)
assume(x>0)
f(x) = 6*x^7-2*x^6+3*x^3-8;
fplot(f)
xlim([-10 10])
ylim([-1e3 1e3])
1-47
1 Getting Started
1.0240 + 0.0000i
0.7652 + 0.8319i
0.7652 - 0.8319i
-0.8808 + 0.5043i
-0.8808 - 0.5043i
-0.2297 + 0.9677i
-0.2297 - 0.9677i
symsSol = solve(f) % exact. The roots object stores the zeros for symbolic computations
symsSol =
z6 z3 4
root z7 − + − , z, 5
3 2 3
vpaSol =
1.0240240759053702941448316563337
−0.88080620051762149639205672298326 + 0.50434058840127584376331806592405 i
−0.88080620051762149639205672298326 − 0.50434058840127584376331806592405 i
−0.22974795226118163963098570610724 + 0.96774615576744031073999010695171 i
−0.22974795226118163963098570610724 − 0.96774615576744031073999010695171 i
0.7652087814927846556172932675903 + 0.83187331431049713218367239317121 i
0.7652087814927846556172932675903 − 0.83187331431049713218367239317121 i
The Symbolic Math Toolbox supports the “Formula Manipulation and Simplification” of mathematical
functions. Most mathematical expressions can be represented in different, but mathematically
equivalent forms and the Symbolic Math Toolbox supports a number of operations, including
factoring or expanding expressions, combining terms, rewriting or rearranging expressions, and
simplification based on assumptions.
ans = x12 − 1
1 − cos(2x)
Apply trigonometric identities to simplifications, for example sin2(x) = .
2
ans = sin 2 x + 1
syms x y
factor(y^6-x^6)
1-48
Computational Mathematics in Symbolic Math Toolbox
ans = −1 x − y x + y x2 + x y + y2 x2 − x y + y2
ans = y3 − 3 y2 + 3 y + 6
h(x) = 1 − log x
The Symbolic Math Toolbox has a full set of calculus tools for applied mathematics. It can perform
multivariate symbolic integration and differentiation. It can generate, manipulate, and perform
calculations with series.
d
Find the derivative of sin(x) .
dx
diff(sin(x))
ans = cos x
d 2
Find the derivative of x + sin(2x4) + 1 using the chain rule.
dx
diff(x^2+sin(2*x^4)+1,x)
ans = 2 x + 8 x3 cos 2 x4
−x2
Find the indefinite integral ∫ f (x) dx for f (x) = e 2 .
int(exp(-x^2/2),x)
ans =
2x
2 π erf 2
2
∫
b
Find the definite integral f (x) dx for f (x) = xlog(1 + x) from 0 to 1.
a
int(x*log(1+x),0,1)
ans =
1
4
(n)
sin(x) n f (a)
Show that = 1 at x = 0 by computing the Taylor series expansion ∑ (x − a) for
x n!
sin(x)
f (x) = around the point x = 0.
x
1-49
1 Getting Started
syms x
T = taylor(sin(x)/x)
T =
x4 x2
− +1
120 6
subs(T,x,0)
ans = 1
π
Show that tan(x) is discontinuous at x = by showing that the left and right limits are not equal.
2
lim tan(x) ≠ lim tan(x).
π+ π−
x→ x→
2 2
limit(tan(x),x,pi/2,'left')
ans = ∞
limit(tan(x),x,pi/2,'right')
ans = − ∞
limit(tan(x),x,pi/2)
ans = NaN
Differential Equations
The Symbolic Math Toolbox can analytically solve systems of “Solve a System of Differential
Equations” on page 3-47 using dsolve.
dy
Solve the first order ODE = − ay.
dx
syms a b y(x)
dsolve(diff(y) == -a*y)
ans = C1 e−a x
dsolve(diff(y)== -a*y,y(0)==b)
ans = b e−a x
dx dy
Solve the system of coupled first order ODEs = y and = − x.
dt dt
C1 cos t + C2 sin t
C2 cos t − C1 sin t
1-50
Computational Mathematics in Symbolic Math Toolbox
Linear Algebra
The Symbolic Math Toolbox can work with symbolic vectors and matrices. It can compute eig of
symbolic matrices.
a b
Perform matrix multiplicationAx = b where A = and x = x1, x2]
c d
syms a b c d
syms x1 x2
x = [x1; x2];
A = [a b ; c d];
b = A*x
b =
a x1 + b x2
c x1 + d x2
det(A)
ans = a d − b c
lambda = eig(A)
lambda =
2
a d a2 − 2 a d + d + 4 b c
+ −
2 2 2
2
a d a2 − 2 a d + d + 4 b c
+ +
2 2 2
Graphics
fplot(tan(x))
1-51
1 Getting Started
syms t
x = t*sin(5*t);
y = t*cos(5*t);
fplot(x, y)
grid on
1-52
Computational Mathematics in Symbolic Math Toolbox
|t| |t|
Plot the 3D parametric curve x(t) = e 10 sin(5 | t | ), y(t) = e 10 cos(5 | t | ) and z(t) = t from [-10,10]
with a dashed red line.
syms t
xt = exp(abs(t)/10).*sin(5*abs(t));
yt = exp(abs(t)/10).*cos(5*abs(t));
zt = t;
h = fplot3(xt,yt,zt, [-10,10],'--r');
1-53
1 Getting Started
syms x y
fsurf(sin(x) + cos(y))
1-54
Computational Mathematics in Symbolic Math Toolbox
fcontour(sin(x) + cos(y))
1-55
1 Getting Started
1-56
Next Step Suggestions for Symbolic Workflows in Live Editor
Starting in R2021b, when you run code that generates a symbolic output in the Live Editor, Live
Editor provides a context menu with next step suggestions that are specific to the output. To open the
suggestion menu, you can point your mouse to the symbolic output and click the three-dot icon , or
you can right-click the symbolic output. When reopening your symbolic workflow live script, run the
code again to get the next step suggestions.
Starting in R2023b, you can also use keyboard shortcuts to navigate to the next step suggestions
after you run your code. To move between code and output in the Live Editor, use the Up/Down
Arrow when the output is inline, or use Ctrl+Shift+O (on macOS systems, use Option+Command
+O instead) when the output is on the right. Activate the symbolic output by pressing the Return
key. Use the shortcut Shift+F10 to open the suggestion menus.
Using these suggestion menus, you can insert and execute function calls or Live Editor tasks into live
scripts. Typical uses of these suggestion menus include:
2
expr = π + 2
Click Run to see the result, which is a symbolic output. When you first run code that generates a
symbolic output, Live Editor shows the three-dot icon for suggested next steps with a pop-up
notification. You can also point to the symbolic output to bring up the three-dot icon. To suppress the
pop-up notification in the rest of your workflow, select Don't show again.
Click the three-dot icon located to the right of the output to bring up the suggestion menu. When
you point to a menu item, Live Editor gives you a preview of what happens when you select the menu
1-57
1 Getting Started
item. For instance, if you point to Approximate numerically, you see the new line of code it
suggests.
Select Approximate numerically to add the suggested new line of code. Live Editor inserts the vpa
function into the code region and automatically runs the current section to evaluate the expression
numerically.
var = vpa(expr)
var = 26.435975015448531572685064532994
As another example, create a symbolic equation. Run a live script to generate the symbolic output.
Solve the equation numerically using symbolic suggestions for next steps.
syms x a
eqn = (2*x^2 + a)/(x + 1) == 3
eqn =
2 x2 + a
=3
x+1
To open the suggestion menu, you can also right-click the symbolic output. Select Solving equations
> Solve equation numerically.
1-58
Next Step Suggestions for Symbolic Workflows in Live Editor
When you click the Solve equation numerically suggestion, Live Editor inserts the vpasolve
function into the code region. Live Editor then automatically runs the current section to solve the
equation numerically.
var2 = vpasolve(eqn,x)
var2 =
0.75 − 0.25 33.0 − 8.0 a
0.25 33.0 − 8.0 a + 0.75
The following sections provide more examples showing how to use the interactive suggestion menus
in symbolic workflows.
Create a symbolic expression that contains exponential functions and imaginary numbers. Run the
following code to generate the symbolic output.
syms x
expr = 1i*(exp(-1i*x) - exp(1i*x))/(exp(-1i*x) + exp(1i*x))
expr =
e−x i i − ex i i
e−x i + ex i
To simplify the expression, right-click the symbolic output and select Rewriting and simplifying
expressions > Simplify expression.
1-59
1 Getting Started
Live Editor inserts and applies the Simplify Symbolic Expression live task to interactively simplify
or rearrange symbolic expressions. Change the computational effort to Medium to get a simpler
result.
1-60
Next Step Suggestions for Symbolic Workflows in Live Editor
Create a quadratic equation with coefficients a, b, and c. Run the following code to generate the
symbolic output.
syms a b c x
eqn = a*x^2 + b*x + c == 0
eqn = a x2 + b x + c = 0
To substitute the coefficients in the equation, right-click the output and select Substitute variables.
Live Editor inserts the subs function to substitute the coefficients and variables in the equations. For
the subs function, Live Editor does not run the function automatically. To substitute a = 3, b = 2, and
c = 0, change the second and third arguments of the subs function to [a,b,c] and [3,2,0]. Run
the Live Editor section afterwards to apply the subs function.
var3 = subs(eqn,[a,b,c],[3,2,0])
var3 = 3 x2 + 2 x = 0
To solve the quadratic equation, right-click the output and select Solve equation analytically.
1-61
1 Getting Started
Live Editor inserts and applies the Solve Symbolic Equation live task to interactively find analytic
solutions of symbolic equations.
1-62
Next Step Suggestions for Symbolic Workflows in Live Editor
Create three symbolic variables x, y, and z and a sinusoidal function. Run the following code to
generate the symbolic output.
syms x y z
f = sin(2*x)
f = sin 2 x
To plot the sinusoidal function, right-click the output and select Plotting functions > Plot function.
1-63
1 Getting Started
fplot(f)
1-64
Next Step Suggestions for Symbolic Workflows in Live Editor
Next, create an equation that represents a hyperbola. Run the following code to generate the
symbolic output.
eqn = x2 − y2 = 1
To plot the sinusoidal function, right-click the output and select Plotting functions > Plot implicit
equation in 2-D.
1-65
1 Getting Started
fimplicit(eqn)
1-66
Next Step Suggestions for Symbolic Workflows in Live Editor
Next, create a symbolic function that represents a torus. Run the following code to generate the
symbolic output.
2
f(x, y, z) = x2 + y2 + z2 + 5 − 36 x2 − 36 y2
To plot the torus, right-click the output and select Plot implicit equation in 3-D.
1-67
1 Getting Started
fimplicit3(f)
1-68
Next Step Suggestions for Symbolic Workflows in Live Editor
Create three symbolic variables x, y, and z and a symbolic matrix. Run the following code to generate
the symbolic output.
syms x y z
M1 = sym([x^2 + a, x; y + 2, 3*y^2])
M1 =
x2 + a x
y + 2 3 y2
To invert the matrix, right-click the output and select Applying matrix functions > Invert matrix.
Note that the Applying matrix functions > Invert matrix suggestion is available only if the
symbolic output is a symbolic matrix.
1-69
1 Getting Started
Live Editor inserts and applies the inv function to invert the matrix.
var4 = inv(M1)
var4 =
3 y2 x
−
σ1 σ1
y+2 x2 + a
−
σ1 σ1
where
σ1 = −3 x2 y2 + x y + 2 x − 3 a y2
Next, create a 1-by-3 symbolic vector. Run the following code to generate the symbolic output.
M2 = x y z y2 x + z
To compute the Jacobian of the vector, right-click the output and select Applying matrix functions
> Compute Jacobian matrix of vector. Note that the Applying matrix functions > Compute
Jacobian matrix of vector suggestion is available only if the symbolic output is a symbolic vector.
1-70
Next Step Suggestions for Symbolic Workflows in Live Editor
Live Editor inserts and applies the jacobian function to compute the Jacobian of the vector.
var5 = jacobian(M2)
var5 =
yz xz xy
0 2y 0
1 0 1
Next, create another 1-by-3 symbolic vector. Run the following code to generate the symbolic output.
M3 = x2 y 2 x z
To compute the curl of the vector, right-click the output and select Applying matrix functions >
Compute curl of vector field.
1-71
1 Getting Started
Live Editor inserts and applies the curl function to compute the curl of the vector.
var6 = curl(M3)
var6 =
0
0
2 − x2
Create a second-order differential equation. Run the following code to generate the symbolic output.
syms f(x) s
eqn = diff(f,x,x) == -9*f
eqn(x) =
∂2
f x = −9 f x
∂x2
To solve the differential equation, right-click the output and select Solve differential equation. Note
that the Solve differential equation suggestion is available only if the symbolic output is a
differential equation.
1-72
Next Step Suggestions for Symbolic Workflows in Live Editor
Live Editor inserts and applies the dsolve function to solve the differential equation.
var7 = dsolve(eqn)
Next, find the Laplace transform of the solution. Right-click the output of dsolve and select
Computing integral transforms > Compute Laplace transform.
1-73
1 Getting Started
Live Editor inserts and applies the laplace function to compute the Laplace transform.
var8 = laplace(var7)
var8 =
C1 s 3 C2
− 2
s2 + 9 s +9
Finally, find the poles of the Laplace transform. Right-click the output of the Laplace transform and
select Applying calculus functions > Compute poles of function.
1-74
Next Step Suggestions for Symbolic Workflows in Live Editor
Live Editor inserts and applies the poles function to compute the poles.
var9 = poles(var8,s)
var9 =
−3 i
3 i
Create a ratio of two lengths with different units. Run the following code to generate the symbolic
output.
u = symunit;
ratio = (7*u.mi)/(420*u.ft)
ratio =
1 mi
60 ft
Convert the units to the meter-gram-second system. Right-click the output and select Applying
physical unit functions > Convert units. Note that the Applying physical unit functions
suggestion is available only if the symbolic output contains symbolic units.
1-75
1 Getting Started
Live Editor inserts and applies the unitConvert function to convert the units to the meter-gram-
second system.
var10 = unitConvert(ratio,[symunit('m'),symunit('g'),symunit('s')])
var10 = 88
Next, create two symbolic expressions x and y that describe the x- and y-coordinates of a moving
projectile. Create a symbolic equation r that compares the units of x and y to the length units m and
ft. Run the following code to generate the symbolic output.
syms theta ts x y r
g = 9.81*u.m/u.s^2;
v = 10*u.m/u.s;
t = ts*u.s;
x = v*cos(theta)*t;
y = v*sin(theta)*t + (-g*t^2)/2;
r = [x == u.m y == u.ft]
r =
981 ts2
10 ts cos θ m = m 10 ts sin θ m − m = ft
200
Check the consistency of units in r. Right-click the output and select Applying physical unit
functions > Check consistency of units.
1-76
Next Step Suggestions for Symbolic Workflows in Live Editor
Live Editor inserts and applies the checkUnits function to check the consistency and compatibility
of the units in r.
The checkUnits function returns a structure containing the fields Consistent and Compatible.
The Consistent field returns logical 1(true) if all terms in r have the same dimension and same
unit with a conversion factor of 1. The Compatible field returns logical 1(true) if all terms have
the same dimension, but not necessarily the same unit.
var11 = checkUnits(r)
1-77
2
ans =
[ n, x]
Here, symvar sorts all returned variables alphabetically. Similarly, you can find the symbolic
variables in g by entering:
symvar(g)
ans =
[ a, b, t]
symvar also can return the first n symbolic variables found in a symbolic expression, matrix, or
function. To specify the number of symbolic variables that you want symvar to return, use the second
parameter of symvar. For example, return the first two variables found in symbolic expression g:
symvar(g, 2)
ans =
[ b, t]
Notice that the first two variables in this case are not a and b. When you call symvar with two
arguments, it finds symbolic variables by their proximity to x before sorting them alphabetically.
When you call symvar on a symbolic function, symvar returns the function inputs before other
variables.
syms x y w z
f(w, z) = x*w + y*z;
symvar(f)
ans =
[ w, z, x, y]
When called with two arguments for symbolic functions, symvar also follows this behavior.
symvar(f, 2)
ans =
[ w, z]
2-2
Find Symbolic Variables in Expressions, Functions, and Matrices
syms s t
f = s + t;
symvar(f, 1)
ans =
t
syms sx tx
f = sx + tx;
symvar(f, 1)
ans =
tx
For more information on choosing the default symbolic variable, see symvar.
2-3
2 Symbolic Computations in MATLAB
In Symbolic Math Toolbox™, you can create symbolic objects by using either syms or sym. These two
functions are conceptually different.
• The syms function creates a symbolic object that is automatically assigned to a MATLAB®
variable with the same name.
• The sym function refers to a symbolic object that can be assigned to a MATLAB variable with the
same name or a different name.
The following examples discuss the differences between the syms and sym functions. For more
examples on the use cases of each function, see syms or sym.
The syms function creates a variable dynamically. For example, the command syms x creates the
symbolic variable x and automatically assigns it to a MATLAB variable with the same name.
syms x
x
x = x
You can then use the variable x in the MATLAB workspace for symbolic workflow, such as finding the
roots of a polynomial.
f = x^2 + x - 6
f = x2 + x − 6
x0 = solve(f)
x0 =
−3
2
The sym function refers to a symbolic variable, which you can then assign to a MATLAB variable with
a different name. For example, the command f1 = sym('x') refers to the symbolic variable x and
assigns it to the MATLAB variable f1.
clear
f1 = sym('x')
f1 = x
You can then use the variable f1 in the MATLAB workspace for symbolic workflow, such as finding
the zeros of a sine function.
f2 = sin(f1)
f2 = sin x
[solx,parameters,conditions] = solve(f2,f1,'ReturnConditions',true)
solx = π k
parameters = k
2-4
Choose syms or sym Function
conditions = k ∈ ℤ
Use the syms function to create a symbolic variable x and automatically assign it to a MATLAB
variable x. When you assign a number to the MATLAB variable x, the number is represented in
double-precision and this assignment overwrites the previous assignment to a symbolic variable. The
class of x becomes double.
syms x
x = 1/33
x = 0.0303
class(x)
ans =
'double'
Use the sym function to refer to an exact symbolic number without floating-point approximation. You
can then assign this number to the MATLAB variable x. The class of x is sym.
x = sym('1/33')
x =
1
33
class(x)
ans =
'sym'
When you create a symbolic variable with an assumption, MATLAB stores the symbolic variable and
its assumption separately.
Use syms to create a symbolic variable that is assigned to a MATLAB variable with the same name.
You get a fresh symbolic variable with no assumptions. If you declare a variable using syms, existing
assumptions are cleared.
syms x positive
syms x
assumptions
ans =
Use sym to refer to an existing symbolic variable. If this symbolic variable was used in your MATLAB
session before, then sym refers to it and its current assumption. If it was not used before, then sym
creates it with no assumptions.
syms x positive
x = sym('x');
assumptions
2-5
2 Symbolic Computations in MATLAB
ans = 0 < x
To create many symbolic variables simultaneously, using the syms function is more convenient. You
can create multiple variables in one line of code.
syms a b c
When you use sym, you have to declare MATLAB variables one by one and refer them to the
corresponding symbolic variables.
a = sym('a');
b = sym('b');
c = sym('c');
To declare a symbolic array that contains symbolic variables as its elements, you can use either syms
or sym.
The command syms a [1 3] creates a 1-by-3 symbolic array a and the symbolic variables a1, a2,
and a3 in the workspace. The symbolic variables a1, a2, and a3 are automatically assigned to the
symbolic array a.
clear
syms a [1 3]
a
a = a1 a2 a3
whos
a 1x3 8 sym
a1 1x1 8 sym
a2 1x1 8 sym
a3 1x1 8 sym
The command a = sym('a',[1 3]) refers to the symbolic variables a1, a2, and a3, which are
assigned to the symbolic array a in the workspace. The elements a1, a2, and a3 are not created in
the workspace.
clear
a = sym('a',[1 3])
a = a1 a2 a3
whos
a 1x3 8 sym
To create a symbolic variable in each worker for parallel computation, use sym. For example, you can
create a symbolic variable k in a parfor loop that performs sums of series using symsum.
2-6
Choose syms or sym Function
S = zeros(1,10);
parfor i = 1:10
k = sym('k');
S(i) = symsum(1/k^i,k,1,Inf);
end
You cannot use syms to create a symbolic variable in a parfor loop because it modifies the global
state of the workspace.
To declare a symbolic variable within a function, use sym. For example, you can explicitly define a
MATLAB variable x in the parent function workspace and refer x to a symbolic variable with the same
name.
function primaryFx
x = sym('x')
function nestedFx
...
end
end
Functions make the workspace static, so you cannot dynamically add variables using syms.
See Also
Related Examples
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Find Symbolic Variables in Expressions, Functions, and Matrices” on page 2-2
• “Use Assumptions on Symbolic Variables” on page 1-41
2-7
2 Symbolic Computations in MATLAB
Symbolic Math Toolbox™ enables you to perform analytical calculations by using symbolic numbers,
variables, functions, and expressions to represent mathematical objects in their exact form. You can
also use variable-precision arithmetic to specify the significant digits used in symbolic computations.
However, symbolic outputs in their analytical form can be long and complicated. You can change the
display format of symbolic outputs by setting preferences for the toolbox.
• Use sym and syms to create symbolic numbers, variables, functions, and expressions to perform
analytical calculations.
• Use digits and vpa to evaluate symbolic objects with variable-precision arithmetic to specified
significant digits.
• Use sympref to set the output display format of symbolic objects to a short, fixed-decimal format
with four digits after the decimal point, without affecting the precision used in symbolic
computations.
If you want to use the results of your symbolic computations in numeric computations using
MATLAB® (without Symbolic Math Toolbox), you can convert symbolic values to numeric values by
using the double and matlabFunction functions.
Symbolic Arithmetic
Symbolic Math Toolbox provides the sym and syms functions to create symbolic objects for symbolic
computations. In symbolic arithmetic, you can perform analytical computations involving numbers
and variables in their exact form, such as 5/11, pi, or x^(1/2).
11
For example, create the number 35
in its exact form by using sym.
a = sqrt(sym(11)/35)
a =
11 35
35
Create a symbolic variable x using syms. Create a symbolic function y(x) that takes the variable x
as an input argument.
syms x
y(x) = a*x^2
y(x) =
11 35 x2
35
y_eval = y(sqrt(35))
y_eval = 11 35
2-8
Change Output Format of Symbolic and Variable-Precision Arithmetic
Variable-Precision Arithmetic
To specify the number of significant digits when performing calculations in Symbolic Math Toolbox
with variable-precision arithmetic, you can use the digits and vpa functions.
For example, specify 10 significant digits and evaluate the previous symbolic values and functions to
the specified precision.
digits(10)
a_vpa = vpa(a)
a_vpa = 0.5606119106
y_vpa(x) = vpa(y)
y_vpa(x) = 0.5606119106 x2
y_vpaeval = y_vpa(sqrt(35))
y_vpaeval = 19.62141687
The results of symbolic computations in their analytical form can be long and complicated. To change
the display format of symbolic results, you can use the sympref function. This function sets the
preferences used in symbolic computations.
For example, set the "FloatingPointOutput" preference to true. Then display the values and
functions from the previous symbolic and variable-precision arithmetic examples. The output of all
symbolic calculations are now in the short, fixed-decimal format with four digits after the decimal
point.
sympref("FloatingPointOutput",true);
a
a = 0.5606
a_vpa
a_vpa = 0.5606
y(x) = 0.5606 x2
y_vpa
y_vpa(x) = 0.5606 x2
y_eval
y_eval = 19.6214
y_vpaeval
y_vpaeval = 19.6214
Setting the "FloatingPointOutput" preference affects only the output display format and does not
affect the floating-point precision in symbolic computations. For example, restore the default setting
2-9
2 Symbolic Computations in MATLAB
of the symbolic preference by using sympref("default"). The variables y_eval and y_vpaeval
still contain the exact symbolic arithmetic and 10-digit variable-precision arithmetic, respectively.
sympref("default");
y_eval
y_eval = 11 35
y_vpaeval
y_vpaeval = 19.62141687
You can also convert symbolic values to the default MATLAB double-precision values.
For example, you can use the double function to convert symbolic numbers to double-precision
numbers.
a_num = double(a)
a_num = 0.5606
You can use matlabFunction to generate a MATLAB function that operates on the double data
type from an existing symbolic function.
y_num = matlabFunction(y)
y_numeval = y_num(sqrt(35))
y_numeval = 19.6214
Setting the "FloatingPointOutput" preference using sympref affects only the output display
format of symbolic results. To change the output display format for MATLAB numeric results, use the
format function.
See Also
Related Examples
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Change Output Display Format of Symbolic Results in the Live Editor” on page 2-11
2-10
Change Output Display Format of Symbolic Results in the Live Editor
This example shows how to modify the output display format of symbolic results in the MATLAB®
Live Editor by using the sympref function. To demonstrate the use of the function, this example uses
a third-degree polynomial.
Create a third-degree polynomial consisting of one variable and three coefficients. Define the variable
and coefficients as symbolic variables by using the syms command.
syms x a b c
f(x) = (a*x^2 + b)*(b*x - a) + c
f(x) = c − a x2 + b a − b x
Symbolic preferences persist through successive MATLAB sessions. Restore all symbolic preferences
to the default values. Expand the polynomial and return the output in the default order.
sympref('default');
poly = expand(f)
2
poly(x) = −a2 x2 + a b x3 − a b + b x + c
The default output format displays the terms of a symbolic polynomial in alphabetical order, without
distinguishing the different symbolic variables in each monomial term.
To change the output order of a polynomial, set the 'PolynomialDisplayStyle' preference. The
'ascend' option sorts the output in an ascending order based on the standard mathematical
notation for polynomials. Here, the variable x with the highest order in a monomial term is displayed
last.
sympref('PolynomialDisplayStyle','ascend');
poly
2
poly(x) = c − a b + b x − a2 x2 + a b x3
By default, symbolic results in Live Scripts are typeset in standard mathematical notation, long
expressions are abbreviated, and matrices are set in parentheses (round brackets). You can modify
the output display format by setting the symbolic preferences.
Find the roots or zeros of the third-degree polynomial using solve. In Symbolic Math Toolbox™, the
root function represents the roots of a polynomial.
sols = solve(poly,x)
sols =
2-11
2 Symbolic Computations in MATLAB
root σ1, z, 1
root σ1, z, 2
root σ1, z, 3
where
2
σ1 = a b z3 − a2 z2 + b z − a b + c
To display the results without being abbreviated, set 'AbbreviateOutput' preference to false.
sympref('AbbreviateOutput',false);
sols
sols =
2
root a b z3 − a2 z2 + b z − a b + c, z, 1
2
root a b z3 − a2 z2 + b z − a b + c, z, 2
2
root a b z3 − a2 z2 + b z − a b + c, z, 3
To display the symbolic matrix with square brackets, rather than parentheses, set
'MatrixWithSquareBrackets' preference to true.
sympref('MatrixWithSquareBrackets',true);
sols
sols =
2
root a b z3 − a2 z2 + b z − a b + c, z, 1
2
root a b z3 − a2 z2 + b z − a b + c, z, 2
2
root a b z3 − a2 z2 + b z − a b + c, z, 3
To display the results in ASCII characters instead of in typeset mathematical notation, set
'TypesetOutput' preference to false.
sympref('TypesetOutput',false);
sols
sols =
The preferences you set using sympref persist through your current and future MATLAB sessions.
Restore the symbolic preferences to the default values for the next step.
sympref('default');
Replace the polynomial coefficients with symbolic numbers using subs. The function returns the
solutions without any approximation.
2-12
Change Output Display Format of Symbolic Results in the Live Editor
numSols =
root σ1, z, 1
root σ1, z, 2
root σ1, z, 3
where
sympref('FloatingPointOutput',true);
numSols
numSols =
0.4501
4.6427e−05 − 1.4904 i
4.6427e−05 + 1.4904 i
The display preferences you set do not affect the computation of symbolic results. You can use the
vpa function to approximate symbolic numbers in floating-point precision with 4 significant digits.
vpaSols = vpa(numSols,4)
vpaSols =
0.4501
−1.4904 i
1.4904 i
sympref('FloatingPointOutput','default');
See Also
Related Examples
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Change Output Format of Symbolic and Variable-Precision Arithmetic” on page 2-8
2-13
2 Symbolic Computations in MATLAB
Starting in R2019a, MATLAB® Live Editor displays symbolic variables with subscripts, superscripts,
and accents in standard mathematical notation. This example shows how to add subscripts,
superscripts, and accents to symbolic variables in the MATLAB Live Editor.
To add subscripts to symbolic variables in live scripts, append the corresponding index to the variable
using one underscore (_). For example, create two symbolic variables with subscripts using syms.
Use these variables in an expression.
Ftot = Fa + Fb
You can also use sym to create a symbolic variable with a subscript and assign the variable to a
symbolic expression.
Fa = sym("F_a")
Fa = Fa
To add superscripts to symbolic variables, append the corresponding index to the variable using two
underscores (__). For example, create two symbolic variables with superscripts.
Ftot = Fa + Fb
When you assign symbolic variables to an expression, the symbolic expression is displayed in ASCII
format.
Add Accents
To add accents to symbolic variables in live scripts, append the corresponding suffix to the variable
using an underscore (_). For example, create symbolic variables with one dot and two dots over the
symbol x. Use these variables in an equation.
eq1 = k x − c ẋ + m ẍ = 0
When you compute the complex conjugate of a symbolic variable with an accent, a bar notation is
added above the variable. For example, find the complex conjugate of x_dot using the conj function.
xConj = conj(x_dot)
xConj = ẋ
2-14
Add Subscripts, Superscripts, and Accents to Symbolic Variables in the Live Editor
This accent list shows the supported accent suffixes and the corresponding display output. The
dagger accent with † symbol is available since R2022b and the degree accent with ° symbol is
available since R2023a.
accentList =
ast x*
dag x†
deg x°
hat x
tilde ∼
x
vec x
bar x
ubar x
dot ẋ
ddot ẍ
⃛
tdot x
⃛
qdot x
prime x′
dprime x′′
tprime x′′′
qprime x′′′′
When you compute the complex conjugate transpose of a matrix containing symbolic variables, a bar
notation is also added above each variable. For example, find the complex conjugate transpose of the
symbolic variables in accentList(:,2) using the ctranspose or ' function.
conjVar = accentList(:,2)'
conjVar =
⃛ ⃛
x* x† x° x ∼
x x x x ẋ ẍ x x x′ x′′ x′′′ x′′′′
When you compute the nonconjugate transpose of a matrix containing symbolic variables, the display
output is unchanged. For example, find the nonconjugate transpose of the symbolic variables in
accentList(:,2) using the transpose or .' function.
nonconjVar = accentList(:,2).'
nonconjVar =
⃛ ⃛
x* x† x° x ∼
x x x x ẋ ẍ x x x′ x′′ x′′′ x′′′′
You can create symbolic variables with multiple subscripts, superscripts, and accents. The multiple
suffixes are assigned to the symbolic variables from left to right.
Create symbolic variables with multiple subscripts and superscripts. If you add multiple subscripts
and superscripts, then the input indices are separated with a comma and displayed from left to right.
2-15
2 Symbolic Computations in MATLAB
x1 = sym("x_b_1__a__1")
a, 1
x1 = xb, 1
x2 = sym("x__b_1_a__1")
b, 1
x2 = x1, a
Now create symbolic variables with multiple accents. If you add multiple accents, then the input
accents are assigned from left to right to the closest preceding variable or index.
v1 = sym("v_prime_vec")
v1 =
v′
v2 = sym("v_vec_prime")
v2 = v ′
va = sym("v__a_bar_prime")
va = va′
vb = sym("v_bar__b_prime")
vb = vb′
Adding suffixes to symbolic variables can produce similar output. However, the variables are equal
only if their suffixes are also in the same order. For example, create three symbolic variables that
produce similar output.
syms F_t__a
F1 = F_t__a
F1 = Fta
F2 = sym("F_t__a")
F2 = Fta
F3 = sym("F__a_t")
F3 = Fta
Determine if the symbolic variables are equal to each other using the isequal function.
tf_12 = isequal(F1,F2)
tf_12 = logical
1
tf_23 = isequal(F2,F3)
2-16
Add Subscripts, Superscripts, and Accents to Symbolic Variables in the Live Editor
tf_23 = logical
0
Starting in R2022b, you can also add signs as suffixes when creating symbolic variables. The
supported signs are −, +, ±, and #. This sign list shows the supported sign suffixes and the
corresponding display output.
signList =
minus A−
plus A+
plusmn A±
hash A#
You can add these signs in combinations with other symbols when creating symbolic variables. To
combine these signs with other subscripts or superscripts, you can use one underscore (_) or two
underscores (__) with other suffixes, respectively. For example:
A1 = sym("A_minus_x_bar")
A1 = A−x
A2 = sym("A__plusmn__c")
A2 = A±c
A3 = sym("A_hash_123")
A3 = A#123
A4 = sym("A_minus_x_plus_y__r__theta")
r, θ
A4 = A−x, +y
See Also
Related Examples
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Find Symbolic Variables in Expressions, Functions, and Matrices” on page 2-2
• “Use Assumptions on Symbolic Variables” on page 1-41
2-17
2 Symbolic Computations in MATLAB
This example shows how to copy symbolic output and paste it as MATLAB® code or equation typeset
in the MATLAB Live Editor. To demonstrate this capability, this example uses a cubic (third-degree)
polynomial.
Solve the cubic polynomial x3 + bx + c = 0. The solutions are displayed in terms of the abbreviated
expression σ1.
syms b c x
S = solve(x^3 + b*x + c == 0,x,"MaxDegree",3)
S =
b
σ1 −
3 σ1
b
σ1 3 3 σ + σ1 i
b 1
− −
6 σ1 2 2
b
σ1 3 3 σ + σ1 i
b 1
− +
6 σ1 2 2
where
3 1/3
b c2 c
σ1 = + −
27 4 2
After you run your code, right-click the symbolic output. Select Copy Output to copy the symbolic
expressions that represent the roots of the cubic polynomial.
Starting in R2023b, you can also use keyboard shortcuts to navigate to the symbolic output. To move
between code and output in the Live Editor, use the Up/Down Arrow when the output is inline, or
use Ctrl+Shift+O (on macOS systems, use Option+Command+O instead) when the output is on
the right. Use the shortcut Shift+F10 to open the menu selection to copy output.
2-18
Copy and Paste Symbolic Output in Live Editor
Insert code in the live script and assign the polynomial roots to the variable Sol. Then paste the
output as MATLAB code using Ctrl + V (or right-click and select Paste). Pasting the output as
MATLAB code automatically expands the abbreviated expression.
Sol =
2-19
2 Symbolic Computations in MATLAB
b
σ1 −
3 σ1
b
σ1 3 3 σ + σ1 i
b 1
− −
6 σ1 2 2
b
σ1 3 3 σ + σ1 i
b 1
− +
6 σ1 2 2
where
3 1/3
b c2 c
σ1 = + −
27 4 2
Select the first solution of the cubic polynomial. When selecting a subexpression, you can copy and
paste only the subexpression that is on the right side of the equal sign. Right-click the existing
selection and choose Copy (Ctrl + C) in the context menu.
2-20
Copy and Paste Symbolic Output in Live Editor
Insert code in the live script and assign the first root of the polynomial to the variable S1. Then paste
the output as MATLAB code using Ctrl + V (or right-click and select Paste). Pasting the output as
MATLAB code automatically expands the abbreviated expression.
S1 =
3 1/3
b c2 c b
+ − −
27 4 2 3 1/3
b c2 c
3 27
+ 4
− 2
2-21
2 Symbolic Computations in MATLAB
You can also paste a selection as equation typeset. Select the second solution of the cubic polynomial.
Right-click the selection and choose Copy (Ctrl + C) in the context menu.
Then paste the selection as equation typeset in the live script using Ctrl + V (or right-click and select
Paste). The equation typeset is rendered as an editable equation. Note that when you paste the
output as equation typeset, abbreviated expressions are not expanded.
b
3 + σ1 i
b σ1 3 σ1
6 σ1
− 2
− 2
2-22
Check Symbolic Equations, Inequalities, and Conditional Statements
Symbolic Math Toolbox™ provides several functions to check symbolic equations, inequalities, and
conditional statements that involve symbolic objects. This example discusses the use cases of these
functions:
• Use isequal to check if two symbolic inputs are equal (from a coding perspective).
• Use logical to check if symbolic conditions involving relational operators (such as &, |, >, ~=,
and so on) are true.
• Use isAlways to check if symbolic conditions are always mathematically true.
• isequal(A,B) checks if A and B are the same size and their contents are equal (from a coding
perspective). isequal is useful only to check equality between two expressions without applying
mathematical transformations and simplifications. isequal returns a scalar logical value 1
(true) if A and B are the same expressions. Otherwise, it returns logical 0 (false). Note that
isequal does not consider NaN (not a number) values as equal. To consider NaN values as equal,
you can use isequaln.
• logical(cond) checks if the symbolic statements in cond hold true without applying
mathematical transformations and simplifications. It also ignores assumptions on symbolic
variables. logical returns a logical array with elements 1 (true) for the elements in cond that
are true and 0 (false) for the elements in cond that are false.
• isAlways(cond) checks if the symbolic statements in cond are always true for all possible
values of the symbolic variables in cond. When verifying cond, isAlways applies mathematical
transformations and simplifications. isAlways also considers all assumptions on the variables in
cond. isAlways returns a logical array with elements 1 (true) for the elements in cond that are
mathematically true and 0 (false) for the elements in cond that are not mathematically true. In
almost all cases, you can use isAlways to check symbolic equalities, inequalities, and conditional
statements.
isequal(a,b) only checks if a and b have the same contents but does not check if they are
2
mathematically equal. If you use isequal to check different expressions, such as x + 1 and
x2 + 2x + 1, then it returns 0 (false), even though they are mathematically equal.
syms x
tf = isequal((x+1)^2,x^2+2*x+1)
tf = logical
0
2
Expand the expression x + 1 , and use isequal to test if the expanded expression is equal to
x2 + 2x + 1.
expr = expand((x+1)^2)
expr = x2 + 2 x + 1
2-23
2 Symbolic Computations in MATLAB
tf = isequal(expr,x^2+2*x+1)
tf = logical
1
sin x
Next, check if the equation tan x = cos x
is true for all values of x by using isAlways.
tf = isAlways(tan(x) == sin(x)/cos(x))
tf = logical
1
sin x
Test if the expressions tan x and cos x
are equal. The isequal function returns 0 (false) because
the expressions are different, even though they are mathematically equal.
tf = isequal(tan(x),sin(x)/cos(x))
tf = logical
0
Rewrite the expression tan x in terms of sin x and cos x . Test if rewrite correctly rewrites tan x
sin x
as cos x
.
expr = rewrite(tan(x),"sincos")
expr =
sin x
cos x
tf = isequal(expr,sin(x)/cos(x))
tf = logical
1
To check an equation that requires simplifications, use isAlways. For example, check the equality of
x + 1 and x2 + 2x + 1 / x + 1 .
syms x
tf = isAlways(x+1 == (x^2+2*x+1)/(x+1))
tf = logical
1
If you use logical to check an equality with different expressions on both sides, then it returns 0
(false).
tf = logical(x+1 == (x^2+2*x+1)/(x+1))
tf = logical
0
2-24
Check Symbolic Equations, Inequalities, and Conditional Statements
Simplify the condition represented by the symbolic equation using simplify. The simplify
function returns the symbolic logical constant symtrue because the equation is always true for all
values of x.
cond = symtrue
tf = logical(cond)
tf = logical
1
As shown in the previous section, if you use isequal to check expressions that are different, then it
returns 0 (false).
tf = isequal(x+1,(x^2+2*x+1)/(x+1))
tf = logical
0
expr = simplify((x^2+2*x+1)/(x+1))
expr = x + 1
tf = isequal(x+1,expr)
tf = logical
1
Check if the equation sin 2nπ = 0 holds true for all integers n. When you create n as a symbolic
variable, Symbolic Math Toolbox treats it as a general complex quantity. To test if the equation holds
true for integers, set an assumption on n and check the equation using isAlways.
syms n
assume(n,"integer")
tf = isAlways(sin(2*n*pi) == 0)
tf = logical
1
Note that logical ignores assumptions on variables. It returns logical 0 (false) in this case.
tf = logical(sin(2*n*pi) == 0)
tf = logical
0
2-25
2 Symbolic Computations in MATLAB
To check conditions involving equations and inequalities, you can use logical or isAlways.
However, logical does not apply mathematical transformations and simplifications when checking
the conditions.
For example, test the condition 1 < 2 AND exp log x = x. Note that if a condition uses other
functions, such as exp and log, then these functions are evaluated when defining the condition.
syms x
cond1 = 1 < 2 & exp(log(x)) == x
cond1 = x = x
tf = isAlways(cond1)
tf = logical
1
You can also use logical to check a condition that does not require mathematical transformations
and simplifications.
tf = logical(cond1)
tf = logical
1
Do not use logical to check if a condition holds true when mathematical transformations are
required. For example, logical returns an error when testing the conditional statement
2 2
sin x + cos x = 1 OR x2 > 0. Instead, use isAlways to test this conditional statement.
2 2
cond2 = 0 < x2 ∨ cos x + sin x =1
tf = isAlways(cond2)
tf = logical
1
For example, create two symbolic arrays where each array has three different expressions.
syms x
expr1 = [tan(x); x+1; exp(log(x))]
expr1 =
tan x
x+1
x
2-26
Check Symbolic Equations, Inequalities, and Conditional Statements
expr2 =
sin x
cos x
x2 + 2 x + 1
x+1
x
To compare these expressions, create a symbolic array of conditional statements using the relational
operator ==.
cond =
sin x
tan x =
cos x
x2 + 2 x + 1
x+1=
x+1
x=x
Check if these multiple conditions are always mathematically true using isAlways. isAlways
returns a 3-by-1 array with logical values 1 (true) because each condition is mathematically true.
tf = isAlways(cond)
1
1
1
Check if these conditions hold true using logical. logical returns a 3-by-1 array, where the first
two elements are 0 (false) because logical does not apply mathematical transformations or
simplifications.
tf = logical(cond)
0
0
1
Check if each corresponding element in the two 3-by-1 symbolic arrays, expr1 and expr2, is equal
using isequal. isequal returns a logical scalar 0 (false) because some of the corresponding
elements are not equal.
tf = isequal(expr1,expr2)
tf = logical
0
2-27
2 Symbolic Computations in MATLAB
expr2 = simplify(expr2,Steps=10)
expr2 =
tan x
x+1
x
Check if each simplified expression in expr2 is equal to the corresponding expression in expr1 using
logical.
tf = logical(expr1 == expr2)
1
1
1
Check if all simplified expressions in expr2 are equal to expr1 using isequal.
tf = isequal(expr1,expr2)
tf = logical
1
See Also
isequal | logical | isAlways | isequaln
2-28
Numeric to Symbolic Conversion
This topic shows how Symbolic Math Toolbox™ converts numbers into symbolic form. For an
overview of symbolic and numeric arithmetic, see “Choose Numeric or Symbolic Arithmetic” on page
2-32.
To convert numeric input to symbolic form, use the sym command. By default, sym returns a rational
approximation of a numeric expression.
t = 0.1;
sym(t)
ans =
1
10
1
sym determines that the double-precision value 0.1 approximates the exact symbolic value 10 . In
general, sym tries to correct the round-off error in floating-point inputs to return the exact symbolic
1
p pπ p 2
form. Specifically, sym corrects round-off error in numeric inputs that match the forms q , q , q
,
q q
2 , and 10 , where p and q are modest-sized integers.
For these forms, demonstrate that sym converts floating-point inputs to the exact symbolic form.
1 1
First, numerically approximate 7 , π, and .
2
N = [1/7 pi 1/sqrt(2)]
N = 1×3
Convert the numeric approximations to exact symbolic form. sym corrects the round-off error.
S = sym(N)
S =
1 2
π
7 2
You can force sym to accept the input as is by placing the input in quotes. Demonstrate this behavior
on the previous input 0.142857142857143. The sym function does not convert the input to 1/7.
sym('0.142857142857143')
ans = 0.142857142857143
When you convert large numbers, use quotes to exactly represent them. Demonstrate this behavior
by comparing sym(133333333333333333333) with sym('133333333333333333333').
sym(1333333333333333333)
ans = 1333333333333333248
sym('1333333333333333333')
2-29
2 Symbolic Computations in MATLAB
ans = 1333333333333333333
You can specify the technique used by sym to convert floating-point numbers using the optional
second argument, which can be 'f', 'r', 'e', or 'd'. The default flag is 'r', for rational form.
Convert input to exact rational form by calling sym with the 'r' flag. This is the default behavior
when you call sym without flags.
t = 0.1;
sym(t,'r')
ans =
1
10
If you call sym with the flag 'f', sym converts double-precision, floating-point numbers to their
e
numeric value by using N ⋅ 2 , where N and e are the exponent and mantissa respectively.
sym(t,'f')
ans =
3602879701896397
36028797018963968
If you call sym with the flag 'e', sym returns the rational form of t plus the error between the
estimated, exact value for t and its floating-point representation. This error is expressed in terms of
eps (the floating-point relative precision).
Convert t to symbolic form. Return the error between its estimated symbolic form and its floating-
point value.
sym(t,'e')
ans =
eps 1
+
40 10
The error term eps/40 is the difference between sym('0.1') and sym(0.1).
If you call sym with the flag 'd', sym returns the decimal expansion of the input. The digits
function specifies the number of significant digits used. The default value of digits is 32.
sym(t,'d')
ans = 0.10000000000000000555111512312578
2-30
Numeric to Symbolic Conversion
digitsOld = digits(7);
sym(t,'d')
ans = 0.1
digits(digitsOld)
You can create symbolic numbers with variable-precision floating-point arithmetic by using vpa. By
default, vpa calculates values to 32 significant digits.
piVpa = vpa(pi)
piVpa = 3.1415926535897932384626433832795
When you use vpa on a numeric input, such as log(2), the numeric expression is first evaluated to
the MATLAB® default double-precision number that has less than 32 significant digits. Then, vpa is
applied on that double-precision number, which can be less accurate. For more accurate results,
convert numeric expressions to symbolic expressions with sym and then use vpa to evaluate the
results with variable precision. For example, find log(2) with 17 and 20 digits precision.
vpaOnDouble = vpa(log(2))
vpaOnDouble = 0.69314718055994528622676398299518
vpaOnSym_17 = vpa(log(sym(2)),17)
vpaOnSym_17 = 0.69314718055994531
vpaOnSym_20 = vpa(log(sym(2)),20)
vpaOnSym_20 = 0.69314718055994530942
When you convert large numbers, use quotes to exactly represent them.
inaccurateNum = vpa(123456789012345678)
inaccurateNum = 123456789012345680.0
accurateNum = vpa('123456789012345678')
accurateNum = 123456789012345678.0
See Also
More About
• “Conversion Between Symbolic and Numeric”
2-31
2 Symbolic Computations in MATLAB
Double-Precision Arithmetic
Numeric computations in MATLAB use double-precision arithmetic by default. For example, evaluate
the expressions 10001/1001, π, and 2. The results are converted to double-precision values.
x = 10001/1001
y = pi
z = sqrt(2)
x =
9.9910
y =
3.1416
z =
1.4142
For more information about double-precision arithmetic, see “Floating-Point Numbers”. This
arithmetic is recommended when you do not have Symbolic Math Toolbox or are using functions that
do not accept symbolic input. Otherwise, exact symbolic arithmetic and variable-precision arithmetic
are recommended. To convert a symbolic value to double precision, use the double function.
Variable-Precision Arithmetic
Variable-precision arithmetic using vpa is the recommended approach for numeric calculations in
Symbolic Math Toolbox. You can specify the number of significant digits when performing
calculations with variable-precision arithmetic.
For example, use vpa to evaluate the fraction 10001/1001. By default, vpa evaluates inputs to 32
significant digits. Approximate the fraction 10001/1001 to at least 32 significant digits.
vpa(10001/1001)
ans =
9.991008991008991008991008991009
Approximate the fraction to at least 8 significant digits. Change the number of significant digits by
using the digits function.
digits(8);
vpa(10001/1001)
ans =
9.991009
2-32
Choose Numeric or Symbolic Arithmetic
In variable-precision arithmetic, you can increase the number of significant digits on page 2-36 for
greater precision. Alternatively, you can decrease the number of significant digits on page 3-321 for
faster computations and decreased memory usage.
Symbolic Arithmetic
Symbolic Math Toolbox provides the sym and syms functions to perform exact symbolic computations
on page 1-28. In symbolic arithmetic, you can perform computations involving numbers and variables
in their exact form, such as x/2, 2^(1/2), or pi. The following three examples show several
calculations that are performed in symbolic arithmetic.
Use sym to create symbolic numbers. Express the irrational numbers π and 2 in symbolic form.
x = sym(pi)
y = sqrt(sym(2))
x =
pi
y =
2^(1/2)
When you declare a number, MATLAB automatically converts the number to double precision. For
example, declare the integer 80435758145817515 as the input argument of sym. The number loses
its accuracy since it is bigger than the largest consecutive integer flintmax in double precision,
which is 2^53.
Z = 80435758145817515
Zinaccurate = sym(80435758145817515)
Z =
8.0436e+16
Zinaccurate =
80435758145817520
To declare a large integer as symbolic number accurately, use a character vector with single
quotation marks as the input argument of sym.
Zaccurate = sym('80435758145817515')
Zaccurate =
80435758145817515
You can then perform calculations with large integers using symbolic arithmetic accurately. For
example, evaluate the sum of the cubes of three large integers.
Z1 = sym('80435758145817515')
Z2 = sym('12602123297335631')
Z3 = sym('-80538738812075974')
Zsum = Z1^3 + Z2^3 + Z3^3
Z1 =
80435758145817515
2-33
2 Symbolic Computations in MATLAB
Z2 =
12602123297335631
Z3 =
-80538738812075974
Zsum =
42
With symbolic arithmetic, you can solve a mathematical equation. For example, solve the quadratic
equation ax2 + bx + c = 0. Use syms to declare the variable x and the coefficients a, b, and c in the
quadratic equation.
syms a b c x
eqn = a*x^2 + b*x + c == 0;
Find the solutions using solve and return them as symbolic expressions.
sols = solve(eqn,x)
sols =
-(b + (b^2 - 4*a*c)^(1/2))/(2*a)
-(b - (b^2 - 4*a*c)^(1/2))/(2*a)
Use subs to substitute symbolic values for the coefficients. Set a = 1, b = 2, and c = 3. Return the
solutions of the quadratic equation as symbolic numbers.
solsSym =
- (8^(1/2)*1i)/2 - 1
(8^(1/2)*1i)/2 - 1
You can then convert the symbolic solutions to floating-point format in double precision or variable
precision.
digits(32);
solsDouble = double(solsSym)
solsVpa = vpa(solsSym)
solsDouble =
-1.0000 - 1.4142i
-1.0000 + 1.4142i
solsVpa =
- 1.0 - 1.4142135623730950488016887242097i
- 1.0 + 1.4142135623730950488016887242097i
2-34
Choose Numeric or Symbolic Arithmetic
a = b = c =
3.1416 3.1415926535897932384626433832795
pi
ans = ans = ans =
1.2246e-16 -3.2101083013100396069547145883568e-40
0
Example 2: a = 4/3 digits(16); c = sym(4)/3
Evaluate 1 - 1 - 3*(a - 1) b = vpa(4/3) 1 - 3*(c - 1)
3*(4/3 - 1) 1 - 3*(b - 1)
a = c =
1.3333 b = 4/3
ans = 1.333333333333333 ans =
2.2204e-16 ans = 0
3.308722450212111e-24
Functions Used double vpa sym
digits
Data Type double sym sym
Round-Off Errors Yes, the answer has 16 Yes, the number of digits No, the results are exact.
digits of precision. depends on the precision
used.
Speed Faster Faster, depending on the Slowest
precision used
Memory Usage Least Variable, depending on Greatest
the precision used
See Also
More About
• “Numeric to Symbolic Conversion” on page 2-29
• “Increase Precision of Numeric Calculations” on page 2-36
• “Find Almost Integers with High-Precision Arithmetic” on page 2-41
2-35
2 Symbolic Computations in MATLAB
When you choose variable-precision arithmetic, by default, vpa uses 32 significant decimal digits of
precision. For details, see “Choose Numeric or Symbolic Arithmetic” on page 2-32. You can set a
higher precision by using the digits function.
Approximate a sum using the default precision of 32 digits. If at least one input is wrapped with vpa,
all other inputs are converted to variable precision automatically.
vpa(1/3) + 1/2
ans =
0.83333333333333333333333333333333
You must wrap all inner inputs with vpa, such as exp(vpa(200)). Otherwise, the inputs are
automatically converted to double by MATLAB.
Increase the precision to 50 digits by using digits and save the old value of digits in digitsOld.
Repeat the sum.
digitsOld = digits(50);
sum50 = vpa(1/3) + 1/2
sum50 =
0.83333333333333333333333333333333333333333333333333
digits(digitsOld)
Note vpa output is symbolic. To use symbolic output with a MATLAB function that does not accept
symbolic values, convert symbolic values to double precision by using double.
digits
Digits = 32
Change the precision for a single vpa call by specifying the precision as the second input to vpa. This
call does not affect digits. For example, approximate pi with 100 digits.
vpa(pi,100)
ans =
3.14159265358979323846264338327950288419716939937510582097494
4592307816406286208998628034825342117068
Digits = 32
2-36
Increase Precision of Numeric Calculations
digitsOld = digits(500);
vpa(pi)
digits(digitsOld)
ans =
3.1415926535897932384626433832795028841971693993751058209749
445923078164062862089986280348253421170679821480865132823066
470938446095505822317253594081284811174502841027019385211055
596446229489549303819644288109756659334461284756482337867831
652712019091456485669234603486104543266482133936072602491412
737245870066063155881748815209209628292540917153643678925903
600113305305488204665213841469519415116094330572703657595919
530921861173819326117931051185480744623799627495673518857527
248912279381830119491
digits and vpa control the number of significant decimal digits. For example, approximating 1/111
with four-digit accuracy returns six digits after the decimal point because the first two digits are
zeros.
vpa(1/111,4)
ans =
0.009009
Note If you want to increase performance by decreasing precision, see “Increase Speed by Reducing
Precision” on page 3-321.
2-37
2 Symbolic Computations in MATLAB
This example shows how to get precise values for binomial coefficients and find probabilities in coin-
tossing experiments using the Symbolic Math Toolbox™.
Define the symbolic function, P(n,k), that computes the probability for the heads to come up exactly
k times out of n tosses.
syms P(n,k)
P(n,k) = nchoosek(n,k)/2^n
P(n, k) =
n
k
n
2
Suppose you toss a coin 2000 times. The probability that heads comes up in half of the tosses is P(n,
n/2), where n = 2000. The result is a rational expression with large numbers in both the numerator
and denominator. Symbolic Math Toolbox returns the exact result.
n = 2000;
central = P(n, n/2)
central =
3200236917171077678648691410907539131869413887470932865344347871362106540940755868482707803410328
17939542113660226941138018768401281000348714095135862507463167762902597834255786154010304473695410
Approximate this rational number with 10-digit accuracy using digits and vpa.
previous_digits = digits(10);
vpa(central)
ans = 0.01783901115
Compute the probability that the number of "heads" differs from the expected value by no more than
two standard deviations.
sigma = sqrt(n/4);
withinTwoSigma = symsum(P(n, k), k, ceil(n/2 - 2*sigma), floor(n/2 + 2*sigma))
2-38
Compute Binomial Coefficients Exactly
withinTwoSigma =
13683524663950565202894406832034749167239195904700934509667499858152527897032069211850781661943643
14351633690928181552910415014721024800278971276108690005970534210322078267404628923208243578956328
vpa(withinTwoSigma)
ans = 0.9534471795
Compare this result with the following two estimates derived from the cumulative distribution
function (cdf) of the normal distribution. It turns out that taking the midpoint between the first
integer outside and the first integer inside the two-sigma interval gives a more precise result than
using the two-sigma interval itself.
syms cdf(x)
cdf(x) = 1/2 * (1 + erf((x - n/2)/sqrt(sym(n/2))))
cdf(x) =
10 x − 1000
erf 100 1
+
2 2
estimate1 = 0.9544997361
estimate2 = 0.9534201342
error1 = 0.001052556595
error2 = −0.00002704525904
digits(previous_digits);
Plot this distribution for k within the 2σ-interval. The plot is a Gaussian curve.
k = n/2 + (-2*sigma:2*sigma);
plot(k, P(n,k), '-+');
title('2000 coin tosses');
xlabel('Number of heads');
ylabel('Probability');
2-39
2 Symbolic Computations in MATLAB
2-40
Find Almost Integers with High-Precision Arithmetic
Algorithms for finding integer relations [1], such as the PSLQ algorithm, require high-precision
arithmetic to produce accurate results. The higher the precision of the inputs to the algorithm, the
greater the level of confidence that the algorithm can find an integer relation that is not just a
numerical artifact. The PSLQ algorithm can encounter false positives, such as those caused by almost
integers.
This example shows how to find almost integers, or numbers that are very close to integers, using
variable-precision arithmetic in Symbolic Math Toolbox™. This example searches for almost integers
(or near-integers) that have the form exp π n or exp π n for the integers n = 1, . . . , 200.
First, consider a well-known example of an almost integer [2] that is the real number exp π 163 .
Create this real number as an exact symbolic number.
r = exp(pi*sqrt(sym(163)))
r = eπ 163
Evaluate this number with variable-precision arithmetic using vpa. By default, vpa calculates values
to 32 significant digits.
vpa(r)
ans = 262537412640768743.99999999999925
You can change the number of significant digits to a higher precision by using digits. Evaluate the
same number to 40 significant digits.
digits(40)
vpa(r)
ans = 262537412640768743.9999999999992500725972
This number is very close to an integer. Find the difference between this real number and its nearest
integer. Use vpa to evaluate this result to 40 significant digits.
dr = vpa(round(r)-r)
dr = 0.0000000000007499274028018143151532171817442410122968
Next, search for almost integers that have the form exp π n for the integers n = 1, . . . , 200. Create
these numbers as exact symbolic numbers.
A = exp(pi*sqrt(sym(1:200)));
Set the number of significant digits to the number of digits in the integer part of exp π 200 plus 20
decimal points.
d = log10(A(end));
digits(ceil(d) + 20)
Evaluate the differences between this series of numbers and their nearest integers. Find the almost
integers with rounding errors that are less than 0.0001. Show the results in exact symbolic form.
2-41
2 Symbolic Computations in MATLAB
B = vpa(round(A)-A);
A_nearint = A(abs(B)<0.0001)'
A_nearint =
eπ 37
eπ 58
eπ 67
eπ 163
A_nearint = vpa(A_nearint)
A_nearint =
199148647.9999780465518567665009238753359
24591257751.99999982221324146957619235527
147197952743.9999986624542245068292613126
262537412640768743.9999999999992500725972
Plot the histogram of the differences to show their distribution. The distribution has many
occurrences of differences that are close to zero, where the form exp π n is an almost integer.
histogram(double(B),40)
2-42
Find Almost Integers with High-Precision Arithmetic
Next, search for almost integers that have the form exp π n for the integers n = 1, . . . , 200. Create
these numbers as exact symbolic numbers.
A = exp(sym(pi)*1:200);
Set the number of significant digits to the number of digits in the integer part of exp π ⋅ 200 plus 20
decimal points.
d = log10(A(end));
digits(ceil(d) + 20)
Evaluate the differences between this series of numbers and their nearest integers. Find the almost
integers with rounding errors that are less than 0.0001. The result is an empty sym array, which
means there is no almost integer that satisfies this condition.
B = vpa(round(A)-A);
A_nearint = A(abs(B)<0.0001)
A_nearint =
Plot the histogram of the differences. The histogram is relatively evenly distributed and shows that
the form exp π n does not have many occurrences of almost integers. For this specific example, there
is no almost integer with a rounding error that is less than 0.0001.
histogram(double(B),40)
2-43
2 Symbolic Computations in MATLAB
Finally, restore the default precision of 32 significant digits for further calculations.
digits(32)
References
See Also
sym | vpa | digits
More About
• “Choose Numeric or Symbolic Arithmetic” on page 2-32
• “Numeric to Symbolic Conversion” on page 2-29
• “Increase Precision of Numeric Calculations” on page 2-36
2-44
Decimal Digits of PI
Decimal Digits of PI
This example shows how to use variable-precision arithmetic to investigate the decimal digits of pi
using Symbolic Math Toolbox™.
π≈3
. 141592653589793238462643383279502884197169399375105820974944592307816406286208998628034
..
.
Joke: What do you get when you take the sun and divide its circumference by its diameter?
It is an old game to search for one's birthday or telephone number in the decimal digits of π. The
precision of the built-in datatypes suffices to obtain a few digits only:
num2str(pi, 100000)
ans =
'3.141592653589793115997963468544185161590576171875'
The function vpa uses variable-precision to convert symbolic expressions into symbolic floating-point
numbers. Convert pi to a floating-point number using vpa. Increase the precision of vpa using
digits.
digits(5000);
a = vpa(pi)
a = 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117
c = char(a);
strfind(c, '1185480')
ans = 447
It is common belief that all digits occur asymptotically equally often in the decimal expansion of π,
but no proof exists yet. Find the decimal point:
pos = 2
Convert the decimal digits to numbers, and plot a histogram of their frequency:
d = arrayfun(@str2num, c(pos+1:end));
histogram(d, 10);
title('Frequency of the decimal digits of \pi');
2-45
2 Symbolic Computations in MATLAB
2-46
Units of Measurement Tutorial
Use units of measurement with Symbolic Math Toolbox™. This page shows how to define units, use
units in equations (including differential equations), and verify the dimensions of expressions.
Specify a unit by using u.unit. For example, specify a distance of 5 meters, a weight of 50
kilograms, and a speed of 10 kilometers per hour.
d = 5*u.m
d = 5m
w = 50*u.kg
w = 50 kg
s = 10*u.km/u.hr
s =
km
10
h
You can use tab expansion to find names of units. Type u., press Tab, and continue typing.
Units are treated like other symbolic expressions and can be used in any standard operation or
function. Units are not automatically simplified, which provides flexibility. Common alternate names
for units are supported. Plurals are not supported.
Add 500 meters and 2 kilometers. The resulting distance is not automatically simplified.
d = 500*u.m + 2*u.km
d = 2 km + 500 m
Simplify d by using simplify. The simplify function chooses the unit to return.
d = simplify(d)
d = 2500 m
d =
5
km
2
For more unit conversion and unit system options, see “Unit Conversions and Unit Systems” on page
2-53.
Find the speed if the distance d is traveled in 50 seconds. The result has the correct units.
2-47
2 Symbolic Computations in MATLAB
t = 50*u.s;
s = d/t
s =
1 km
20 s
By default, temperatures are assumed to represent differences and not absolute measurements. For
example, 5*u.Celsius is assumed to represent a temperature difference of 5 degrees Celsius. This
assumption allows arithmetical operations on temperature values.
To represent absolute temperatures, use kelvin, so that you do not have to distinguish an absolute
temperature from a temperature difference.
Convert 23 degrees Celsius to kelvin, treating the temperature first as a temperature difference and
then as an absolute temperature.
u = symunit;
T = 23*u.Celsius;
diffK = unitConvert(T,u.K)
diffK = 23 K
absK = unitConvert(T,u.K,'Temperature','absolute')
absK =
5923
K
20
Because the value 0 times a symbolic unit is returned as a dimensionless 0 when using symunit, you
can use a cell array to represent 0 degrees.
TC = {0,u.Celsius};
TF = unitConvert(TC,u.Fahrenheit,'Temperature','Absolute')
TF = 32 °F
Verify Dimensions
In longer expressions, visually checking for units is difficult. You can check the dimensions of
expressions automatically by verifying the dimensions of an equation.
First, define the kinematic equation v2 = v02 + 2as, where v represents velocity, a represents
acceleration, and s represents distance. Assume s is in kilometers and all other units are in SI base
units. To demonstrate dimension checking, the units of a are intentionally set incorrectly.
syms v v0 a s
u = symunit;
eqn = (v*u.m/u.s)^2 == (v0*u.m/u.s)^2 + 2*a*u.m/u.s*s*u.km
eqn =
m2 m2 km m
v2 2 = v02 2 + 2 a s
s s s
2-48
Units of Measurement Tutorial
Observe the units that appear in eqn by using findUnits. The returned units show that both
kilometers and meters are used to represent distance.
findUnits(eqn)
ans = km m s
Check if the units have the same dimensions (such as length or time) by using checkUnits with the
'Compatible' input. MATLAB® assumes symbolic variables are dimensionless. checkUnits
returns logical 0 (false), meaning the units are incompatible and not of the same physical
dimensions.
checkUnits(eqn,'Compatible')
ans = logical
0
Looking at eqn, the acceleration a has incorrect units. Correct the units and recheck for compatibility
again. eqn now has compatible units.
ans = logical
1
Now, to check that each dimension is consistently represented by the same unit, use checkUnits
with the 'Consistent' input. checkUnits returns logical 0 (false) because meters and
kilometers are both used to represent distance in eqn.
checkUnits(eqn,'Consistent')
ans = logical
0
Convert eqn to SI base units to make the units consistent. Run checkUnits again. eqn has both
compatible and consistent units.
eqn = unitConvert(eqn,'SI')
eqn =
m2 m2 m2
v2 2 = v02 2 + 2000 a s 2
s s s
checkUnits(eqn)
After you finish working with units and only need the dimensionless equation or expression, separate
the units and the equation by using separateUnits.
eqn = separateUnits(eqn)
2-49
2 Symbolic Computations in MATLAB
To calculate numeric values from your expression, substitute for symbolic variables using subs, and
convert to numeric values using double or vpa.
Solve eqn for v. Then find the value of v where v0 = 5 , a = 2 . 5 , and s = 10. Convert the result to
double.
v = solve(eqn,v);
v = v(2); % choose the positive solution
vSol = subs(v,[v0 a s],[5 2.5 10]);
vSol = double(vSol)
vSol = 223.6627
Use units in differential equations just as in standard equations. This section shows how to use units
in differential equations by deriving the velocity relations v = v0 + at and v2 = v02 + 2as starting from
dv
the definition of acceleration a = dt
.
Represent the definition of acceleration symbolically using SI units. Given that the velocity V has
units, you must differentiate V with respect to the correct units as T = t*u.s and not just t.
syms V(t) a
u = symunit;
T = t*u.s; % time in seconds
A = a*u.m/u.s^2; % acceleration in meters per second
eqn1 = A == diff(V,T)
eqn1(t) =
m ∂ 1
a 2= V t
s ∂t s
Because the velocity V is unknown and does not have units, eqn1 has incompatible and inconsistent
units.
checkUnits(eqn1)
Solve eqn1 for V with the condition that the initial velocity is v0. The result is the equation
v t = v0 + at.
syms v_0
cond = V(0) == v_0*u.m/u.s;
eqn2 = V == dsolve(eqn1,cond)
eqn2(t) =
1
V t = v0 m + a t m
s
Check that the result has the correct dimensions by substituting rhs(eqn2) into eqn1 and using
checkUnits.
2-50
Units of Measurement Tutorial
checkUnits(subs(eqn1,V,rhs(eqn2)))
Now, derive v2 = v02 + 2as. Because velocity is the rate of change of distance, substitute V with the
derivative of distance S. Again, given that S has units, you must differentiate S with respect to the
correct units as T = t*u.s and not just t.
syms S(t)
eqn2 = subs(eqn2,V,diff(S,T))
eqn2(t) =
∂ 1 1
St = v0 m + a t m
∂t s s
Solve eqn2 with the condition that the initial distance covered is 0. Get the expected form of S by
using expand.
cond2 = S(0) == 0;
eqn3 = S == dsolve(eqn2,cond2);
eqn3 = expand(eqn3)
eqn3(t) =
a t2
St = m + v0 t m
2
You can use this equation with the units in symbolic workflows. Alternatively, you can remove the
units by returning the right side using rhs, separating units by using separateUnits, and using the
resulting unitless expression.
[S units] = separateUnits(rhs(eqn3))
S(t) =
t 2 v0 + a t
2
units(t) = m
When you need to calculate numeric values from your expression, substitute for symbolic variables
using subs, and convert to numeric values using double or vpa.
Find the distance traveled in 8 seconds where v_0 = 20 and a = 1.3. Convert the result to double.
dist = 201.6000
See Also
checkUnits | findUnits | isUnit | newUnit | separateUnits | symunit2str |
unitConversionFactor | unitConvert
2-51
2 Symbolic Computations in MATLAB
More About
• “Unit Conversions and Unit Systems” on page 2-53
• “Units and Unit Systems List” on page 2-60
External Websites
• The International System of Units (SI)
2-52
Unit Conversions and Unit Systems
Convert Units
Convert between units by using unitConvert.
u = symunit;
len = 1.2*u.m;
len = unitConvert(len,u.cm)
len =
120*[cm]
Convert len to inches. The result is in exact symbolic form. Separate units and convert to double.
len = unitConvert(len,u.in)
len =
(6000/127)*[in]
len =
47.2441
m = 5*u.kg;
a = 2*u.m/u.s^2;
F = m*a
F =
10*(([kg]*[m])/[s]^2)
F = unitConvert(F,u.N)
F =
10*[N]
Tip Use tab expansion to find names of units. Type u., press Tab, and continue typing.
Calculate the energy when force F is applied for 3 meters. Convert the result to joule.
d = 3*u.m;
E = F*d
E =
30*[N]*[m]
2-53
2 Symbolic Computations in MATLAB
E = unitConvert(E,u.J)
E =
30*[J]
Convert E to kilowatt-hour.
E = unitConvert(E,u.kWh)
E =
(1/120000)*[kWh]
Convert 23 degrees Celsius to degrees Kelvin, first as a temperature difference and then as an
absolute temperature.
u = symunit;
T = 23*u.Celsius;
relK = unitConvert(T,u.K,'Temperature','difference')
relK =
23*[K]
absK = unitConvert(T,u.K,'Temperature','absolute')
absK =
(5923/20)*[K]
Because the value 0 is dimensionless and 0 degrees cannot be represented, convert 0 degrees
between temperature units by using cell input.
tF =
32*[Fahrenheit]
Calculate the force due to a 5 kg mass accelerating at 2 m/s2. The resulting units are hard to read.
Convert them to convenient units by specifying the SI and Derived options. unitConvert
automatically chooses the correct units of newton.
u = symunit;
m = 5*u.kg;
2-54
Unit Conversions and Unit Systems
a = 2*u.m/u.s^2;
F = m*a
F =
10*(([kg]*[m])/[s]^2)
F = unitConvert(F,'SI','Derived')
F =
10*[N]
Convert F to US units. By default, the converted units are base units. For convenience, also convert
into derived units by specifying the Derived option. The derived units are easier to read.
F = unitConvert(F,'US')
F =
(1250000000000/17281869297)*(([ft]*[lbm])/[s]^2)
F = unitConvert(F,'US','Derived')
F =
(20000000000000/8896443230521)*[lbf]
F = unitConvert(F,'CGS','Derived')
F =
1000000*[dyn]
loadCell =
(300000000/45359237)*[lbm]
(125/762)*[ft]
(25/508)*[ft]
(25/762)*[ft]
14*[Fahrenheit]
104*[Fahrenheit]
If unitConvert does not choose your preferred unit, then adjust the result with further
unitConvert commands. Here, inches are more convenient than feet. Convert the result to inches.
loadCell = unitConvert(loadCell,u.inch)
loadCell =
(300000000/45359237)*[lbm]
(250/127)*[in]
(75/127)*[in]
(50/127)*[in]
2-55
2 Symbolic Computations in MATLAB
14*[Fahrenheit]
104*[Fahrenheit]
The exact symbolic values are hard to read. Separate the units and convert to double.
loadCellDouble =
6.6139
1.9685
0.5906
0.3937
14.0000
104.0000
Alternatively, approximate the result to high precision by using vpa. The vpa function also keeps the
symbolic units because it returns symbolic output.
loadCell = vpa(loadCell)
loadCell =
6.6138678655463274216892140403508*[lbm]
1.968503937007874015748031496063*[in]
0.5905511811023622047244094488189*[in]
0.3937007874015748031496062992126*[in]
14.0*[Fahrenheit]
104.0*[Fahrenheit]
Convert five acres (ac), whose unit is a U.S. survey acre, to metric area.
u = symunit;
area = 5*u.ac_US;
area = unitConvert(area,'SI')
area =
(313632000000/15499969)*[m]^2
In photonics, commonly used units are nanosecond (ns), electron volt (eV), and nanometer (nm).
Define a unit system with these units by modifying the SI unit system. Get SI base and derived units
by using baseUnits and derivedUnits. Modify the units by using subs.
u = symunit;
bunits = baseUnits('SI');
bunits = subs(bunits,[u.m u.s],[u.nm u.ns])
bunits =
[ [kg], [ns], [nm], [A], [cd], [mol], [K]]
dunits = derivedUnits('SI');
dunits = subs(dunits,u.J,u.eV)
2-56
Unit Conversions and Unit Systems
dunits =
[ [F], [C], [S], [H], [V], [eV], [N], [lx], [lm], [Wb], [W], [Pa],...
[Ohm], [T], [Gy], [Bq], [Sv], [Hz], [kat], [rad], [sr], [Celsius]]
Note Do not define variables called baseUnits and derivedUnits because the variables prevent
access to the baseUnits and derivedUnits functions.
phSys =
"photonics"
Calculate the energy of a photon of frequency 1 GHz and convert the result to derived units of the
phSys system. The result is in electron volts.
f = 1*u.GHz;
E = u.h_c*f;
E = unitConvert(E,phSys,'Derived')
E =
(44173801/10681177560000)*[eV]
The exact symbolic result is hard to read. Separate the units and convert to double.
[E Eunits] = separateUnits(E);
E = double(E)
E =
4.1357e-06
u = symunit;
t_au = newUnit('t_au',u.hbar/u.E_h);
bunits = [u.m_e u.e u.Bohr u.t_au]
bunits =
[ [m_e], [e], [a_0], [t_au]]
2-57
2 Symbolic Computations in MATLAB
edm_au = newUnit('edm_au',u.e*u.bohr);
mdm_au = newUnit('mdm_au', u.e*u.hbar/(2*u.me));
ep_au = newUnit('ep_au', u.E_h/u.e);
dunits = [u.hbar u.E_h u.edm_au u.mdm_au u.ep_au]
dunits =
[ [h_bar], [E_h], [edm_au], [mdm_au], [ep_au]]
auSys = newUnitSystem('atomicUnits',bunits,dunits)
auSys =
"atomicUnits"
proton =
1836.1526726825404620381265471117*[m_e]
0.99999999176120807953267071600981*[e]
0.0000000000000010204521072979158730257341288851*[edm_au]
0.00048415958374162452452052339364507*pi*[mdm_au]
After completing calculations, remove the unit system and the added units.
removeUnitSystem(auSys)
removeUnit([u.t_au u.edm_au u.mdm_au u.ep_au])
• Base units must be independent in terms of the dimensions mass, time, length, electric current,
luminous intensity, amount of substance, and temperature. Therefore, a unit system has up to 7
base units. As long as the independence is satisfied, any unit can be a base unit, including units
such as newton or watt.
• A unit system can have less than 7 base units. For example, mechanical systems need base units
only for the dimensions length, mass, and time.
2-58
Unit Conversions and Unit Systems
• Derived units in a unit system must have a representation in terms of the products of powers of
the base units for that system. Unlike base units, derived units do not have to be independent.
• Derived units are optional and added for convenience of representation. For example, kg m/s2 is
abbreviated by newton.
• An example of a unit system is the SI unit system, which has 7 base units: kilogram, second,
meter, ampere, candela, mol, and kelvin. There are 22 derived units found by calling
derivedUnits('SI').
See Also
baseUnits | derivedUnits | newUnitSystem | removeUnit | removeUnitSystem | symunit |
unitConvert
More About
• “Units of Measurement Tutorial” on page 2-47
• “Units and Unit Systems List” on page 2-60
External Websites
• The International System of Units (SI)
2-59
2 Symbolic Computations in MATLAB
In this section...
“Units List” on page 2-60
“SI Unit Prefixes List” on page 2-70
“Unit Systems List” on page 2-71
“Defining Constants of SI Units” on page 2-72
Units List
Length
• Ao - angstrom
• a_0 - Bohr radius
• au - astronomical unit
• ch - chain
• ft - foot
• ft_US - U.S. survey foot
• ftm - fathom
• fur - furlong
• gg - gauge
• hand - hand
• in - inch
• inm - international nautical mile
• land - league
• li - link
• line - line
• ly - light-year
• m - meter (SI)
• mi - mile
• mi_US - U.S. survey mile
• mil - mil
• nmile - British imperial nautical mile
• pc - parsec
• pica - pica
• pica_US - U.S. customary pica
• pt - point
2-60
Units and Unit Systems List
Mass
• Mt - metric megaton
• ct - carat
• cwt - U.S. customary short hundredweight
• cwt_UK - British imperial short hundredweight
• dalton - atomic mass constant
• dr - dram
• g - gram (SI)
• gr - grain
• hyl - hyl
• kt - metric kiloton
• lbm - pound mass
• m_e - electron mass
• m_p - proton mass
• m_u - atomic mass constant
• oz - ounce
• quarter - quarter
• slug - slug
• stone - stone
• t - metric ton
• tn - U.S. customary short ton
• ton_UK - British imperial ton
Time
• d - day
• fortnight - 14 days
• h - hour
• min - minute
• month_30 - 30-day month
• s - second (SI)
• week - 7-day week
• year_360 - 360-day year
2-61
2 Symbolic Computations in MATLAB
• Gy - gray (SI)
• Rad - absorbed radiation dose
• Sv - sievert (SI)
• rem - roentgen equivalent man
Acceleration
• Gal - gal
• g_n - earth gravitational acceleration
Activity
• Bq - becquerel (SI)
• Ci - curie
Amount of Substance
Angular Momentum
Area
• a - are
• ac - acre
• ac_US - U.S. survey acre
• barn - barn
• circ_mil - circular mil
• circ_inch - circular inch
• ha - metric hectare
• ha_US - U.S. survey hectare
• ro - rood
• twp - township
Capacitance
• F - farad (SI)
2-62
Units and Unit Systems List
• abF - abfarad
• statF - statfarad
Catalytic Activity
Conductance
• Bd - baud
• bps - bit per second
Digital Information
• B - byte
• bit - basic unit of information
Dimensionless
Dose Equivalent
• Sv - sievert (SI)
Dynamic Viscosity
• P - poise
• reyn - reynolds
Electric Charge
• C - coulomb (SI)
• Fr - franklin
• abC - abcoulomb
• e - elementary charge
• statC - statcoulomb
2-63
2 Symbolic Computations in MATLAB
Electric Current
• A - ampere (SI)
• Bi - biot
• abA - abampere
• statA - statampere
• debye - debye
• V - volt (SI)
• abV - abvolt
• statV - statvolt
2-64
Units and Unit Systems List
• therm - therm
European Currency
• Cent - cent
• EUR - Euro
Flow Rate
Force
• N - newton (SI)
• dyn - dyne
• kgf - kilogram force
• kip - kip
• kp - kilopond
• lbf - pound force
• ozf - ounce force
• p - pond
• pdl - poundal
• sn - sthene
• tonf - short ton force
2-65
2 Symbolic Computations in MATLAB
Frequency
• Hz - hertz (SI)
• dv_Cs - caesium hyperfine transition frequency
Frequency of Rotation
Fuel Consumption
Fuel Economy
Gravity
Illuminance
• lx - lux (SI)
• nx - nox
• ph - phot
Inductance
• H - henry (SI)
• abH - abhenry
• statH - stathenry
Ionising Dosage
• R - roentgen
Kinematic Viscosity
• St - stokes
• newt - newt
2-66
Units and Unit Systems List
Luminance
• asb - apostilb
• sb - stilb
Luminous Efficacy
Luminous Flux
• lm - lumen (SI)
Luminous Intensity
• cd - candela (SI)
• cp - candlepower
• Oe - oersted
Magnetic Flux
• Mx - maxwell
• Wb - weber (SI)
• abWb - abweber
• statWb - statweber
• phi_0 - magnetic flux quantum
• G - gauss
• T - tesla (SI)
• abT - abtesla
• statT - stattesla
Magnetic Force
• Gb - gilbert
• den - denier
• tex - filament tex
2-67
2 Symbolic Computations in MATLAB
Plane Angle
• arcsec - arcsecond
• arcmin - arcminute
• deg - degree
• rad - radian (SI)
• rev - revolution
Pressure or Stress
• Ba - barye
• Pa - pascal (SI)
• Torr - torr
• at - technical atmosphere
• atm - standard atmosphere
• bar - bar
• cmHg - centimeter of mercury (conventional)
• cmH2O - centimeter of water (conventional)
• ftHg - foot of mercury (conventional)
• ftH2O - foot of water (conventional)
• inHg - inch of mercury (conventional)
• inH2O - inch of water (conventional)
• ksf - kip per square foot
• ksi - kip per square inch
• mH2O - meter of water (conventional)
• mHg - meter of mercury (conventional)
• mmHg - millimeter of mercury (conventional)
• mmH2O - millimeter of water (conventional)
• psf - pound force per square foot
2-68
Units and Unit Systems List
Quantum Resistance
Radiation
• lan - langley
Reciprocal Length
• kayser - kayser
• R_inf - Rydberg constant
• dpt - diopter
Resistance
Solid Angle
• sr - steradian (SI)
• molarity - molarity
Temperature
Velocity
• Kyne - kyne
• c_0 - speed of light in vacuum
• fpm - foot per minute
• fps - foot per second
• kmh - kilometer per hour
• knot_UK - British imperial knot
• kts - international knot
2-69
2 Symbolic Computations in MATLAB
Volume
• barrel - barrel
• bbl - U.S. customary dry barrel
• bu_UK - British imperial bushel
• chaldron - chaldron
• dry_bu - U.S. customary dry bushel
• dry_gal - U.S. customary dry gallon
• dry_pk - U.S. customary dry peck
• dry_pt - U.S. customary dry pint
• dry_qt - U.S. customary dry quart
• fldr - U.S. customary fluid dram
• fldr_UK - British imperial fluid drachm (dram)
• floz - U.S. customary fluid ounce
• floz_UK - British imperial fluid ounce
• gal - U.S. customary liquid gallon
• gal_UK - British imperial gallon
• gill - U.S. customary fluid gill
• gill_UK - British imperial gill
• igal - British imperial gallon
• l - liter
• liq_pt - U.S. customary liquid pint
• liq_qt - U.S. customary liquid quart
• minim - U.S. customary minim
• minim_UK - British imperial minim
• pint - U.S. customary liquid pint
• pint_UK - British imperial pint
• pk_UK - British imperial peck
• pottle - British imperial pottle
• qt_UK - British imperial quart
• quart - U.S. customary liquid quart
2-70
Units and Unit Systems List
Available unit systems in Symbolic Math Toolbox are listed below. For details, see “Unit Conversions
and Unit Systems” on page 2-53.
ans = ans =
[ [kg], [s], [m], [A], [cd], [[mol],
[F], [C],
[K]] [S], [H], [V], [J], [N], [l
[Pa], [Ohm], [T], [Gy], [Bq], [Sv], [H
[Celsius]]
CGS units ('CGS') baseUnits('CGS') derivedUnits('CGS')
ans = ans =
[ [cm], [g], [s], [K]] [ [Gal], [dyn], [erg], [Ba], [P], [St],
2-71
2 Symbolic Computations in MATLAB
ans = ans =
[ [lbm], [s], [ft], [A], [cd],
[ [F],
[mol],
[C],
[K]]
[S], [H], [V], [Btu_IT], [l
[W], [psf], [Ohm], [T], [Gy], [Bq], [S
[sr], [Fahrenheit], [gal]]
Electrostatic units ('ESU') baseUnits('ESU') derivedUnits('ESU')
ans = ans =
[ [cm], [g], [s], [K], [statC]]
[ [Gal], [dyn], [erg], [Ba], [P], [St],
[statH], [statS], [statOhm], [statT],
Gaussian units ('GU') baseUnits('GU') derivedUnits('GU')
ans = ans =
[ [cm], [g], [s], [K], [Fr]] [ [Gal], [dyn], [erg], [Ba], [P], [St],
[Bi], [Mx], [Oe], [debye]]
Electromagnetic units ('EMU') baseUnits('EMU') derivedUnits('EMU')
ans = ans =
[ [cm], [g], [s], [K], [abA]][ [Gal], [dyn], [erg], [Ba], [P], [St],
[abF], [abH], [abS], [abOhm], [abT], [
ans =
9192631770*(1/[s])
Speed of light (c_0) u = symunit;
unitConvert(u.c_0,'SI')
ans =
299792458*([m]/[s])
Planck constant (h_c) u = symunit;
unitConvert(u.h_c,'SI')
ans =
(132521403/200000000000000000000000000000000000000000)*(([kg]*[m]^2)
Elementary charge (e) u = symunit;
unitConvert(u.e,'SI')
ans =
(801088317/5000000000000000000000000000)*[A]*[s]
2-72
Units and Unit Systems List
ans =
(1380649/100000000000000000000000000000)*(([kg]*[m]^2)/([K]*[s]^2))
Avogadro constant (N_A) u = symunit;
unitConvert(u.N_A,'SI')
ans =
602214076000000000000000*(1/[mol])
Luminous efficacy of a 540 THz u = symunit;
radiation (K_cd) unitConvert(u.K_cd,'SI')
ans =
683*(([cd]*[s]^3*[sr])/([kg]*[m]^2))
See Also
unitInfo | checkUnits | isUnit | newUnit | rewrite | separateUnits | symunit |
symunit2str | unitConversionFactor
See Also
Related Examples
• “Units of Measurement Tutorial” on page 2-47
• “Unit Conversions and Unit Systems” on page 2-53
External Websites
• The International System of Units (SI)
2-73
2 Symbolic Computations in MATLAB
This example shows how to work with units in physics calculations. Calculate the terminal velocity of
a falling paratrooper in both SI and imperial units. Solve the motion of the paratrooper, taking into
account the gravitational force and the drag force.
Introduction
Imagine a paratrooper jumping out of an airplane. Assume there are only two forces acting on the
paratrooper: the gravitational force and an opposing drag force from the parachute. The drag force is
proportional to the velocity squared of the paratrooper.
∂ 2
m v t = cdv t − m g,
∂t
where
syms g m c_d
syms v(t)
eq = m*diff(v(t),t) + m*g == c_d*v(t)^2
eq =
∂ 2
m v t + g m = cd v t
∂t
2-74
Units in Physics Calculations
Assume that the parachute opens immediately at t = 0 so that the equation eq is valid for all values of
t ≥ 0. Solve the differential equation analytically using dsolve with the initial condition v 0 = 0. The
solution represents the velocity of the paratrooper as a function of time.
velocity = simplify(dsolve(eq, v(0) == 0))
velocity =
cd g t
g m tanh
m
−
cd
kg ⋅ m
The SI unit of force is the Newton N . In terms of the base units, the Newton is . Since these
s2
are equivalent, they have a unit conversion factor of 1.
u = symunit;
unitConversionFactor(u.N, u.kg*u.m/u.s^2)
ans = 1
2
The drag force cdv t must have the same unit in Newton N as the gravitational force m g. Using
dimensional analysis, solve for the unit of cd.
syms drag_units_SI
drag_units_SI = simplify(solve(drag_units_SI * (u.m / u.s)^2 == u.N))
drag_units_SI =
kg
m
Substitute these values into the velocity equation and simplify the result.
vel_SI = subs(velocity,[g,m,c_d],[9.81*u.m/u.s^2, 70*u.kg, 40*drag_units_SI])
vel_SI =
kg 981 m
t 40
m 100 s2 981 m
tanh 70 kg 100 2
70 kg s
−
kg
40 m
vel_SI = simplify(vel_SI)
vel_SI =
2-75
2 Symbolic Computations in MATLAB
3 763 t 1
3 763 tanh 35 s m
−
20 s
digits(3)
vel_SI = vpa(vel_SI)
vel_SI =
1 m
−4.14 tanh 2.37 t
s s
The paratrooper approaches a constant velocity when the gravitational force is balanced by the drag
force. This is called the terminal velocity and it occurs when the drag force from the parachute
cancels out the gravitational force (there is no further acceleration). Find the terminal velocity by
taking the limit of t ⟶ ∞.
vel_term_SI =
m
−4.14
s
vel_Imperial = rewrite(vel_SI,u.ft)
vel_Imperial =
1 ft
−13.6 tanh 2.37 t
s s
vel_term_Imperial = rewrite(vel_term_SI,u.ft)
vel_term_Imperial =
ft
−13.6
s
To plot the velocity as a function of time, express the time t in seconds and replace t by T s, where T
is a dimensionless symbolic variable.
syms T
vel_SI = subs(vel_SI, t, T*u.s)
vel_SI =
m
−4.14 tanh 2.37 T
s
vel_Imperial =
ft
−13.6 tanh 2.37 T
s
2-76
Units in Physics Calculations
Separate the expression from the units by using separateUnits. Plot the expression using fplot.
Convert the units to strings for use as plot labels by using symunit2str.
The velocity of the paratrooper approaches steady state when t > 1. Show how the velocity
approaches terminal velocity by plotting the velocity over the range 0 ≤ T ≤ 2.
subplot(1,2,1)
fplot(data_SI,[0 2])
title('Velocity in SI Units')
xlabel('Time in s')
ylabel(['Velocity in ' symunit2str(units_SI)])
subplot(1,2,2)
fplot(data_Imperial,[0 2])
title('Velocity in Imperial Units')
xlabel('Time in s')
ylabel(['Velocity in ' symunit2str(units_Imperial)])
See Also
Functions
symunit | unitConversionFactor | rewrite | separateUnits
2-77
2 Symbolic Computations in MATLAB
This example explores the physics of the damped harmonic oscillator by solving the equations of
motion in the case of no driving forces. This example investigates the cases of under-, over-, and
critical-damping.
Contents
Consider a forced harmonic oscillator with damping shown below. Model the resistance force as
proportional to the speed with which the oscillator moves.
2-78
The Physics of the Damped Harmonic Oscillator
• m is the mass
• c is the damping coefficient
• k is the spring constant
• F is a driving force
eq(t) =
∂2 ∂
m x t +c x t +kx t = F t
∂t 2 ∂t
eq(t) =
∂2 ∂
m x t +γm x t + m x t ω02 = F t
∂t2 ∂t
Divide out the mass m. Now we have the equation in a convenient form to analyze.
eq = collect(eq, m)/m
eq(t) =
∂2 ∂ Ft
x t +γ x t + x t ω02 =
∂t2 ∂t m
Solve the equation of motion using dsolve in the case of no external forces where F = 0. Use the
initial conditions of unit displacement and zero velocity.
vel = diff(x,t);
cond = [x(0) == 1, vel(0) == 0];
eq = subs(eq,F,0);
sol = dsolve(eq, cond)
sol =
2-79
2 Symbolic Computations in MATLAB
γ σ1 γ σ1
e−t 2 − 2 γ + σ1 e−t 2 + 2 γ − σ1
−
2 σ1 2 σ1
where
σ1 = γ − 2 ω0 γ + 2 ω0
sol = expand(sol)
sol =
t γ2 − 4 ω02 t γ2 − 4 ω02
σ1 σ2 σ1 e 2 γ σ1 σ2 γ σ1 e 2
+ − +
2 2 2
2 γ − 4 ω0 2 2 γ − 4 ω02
2
where
γt
σ1 = e− 2
t γ2 − 4 ω02
σ2 = e− 2
Notice that each term has a factor of σ1, or e−γt/2, use collect to gather these terms
sol =
−σ1 σ −σ σ γt
e e 1 γ e 1 γ e 1
+ − + e− 2
2 2 2
2 γ − 4 ω02 2
2 γ − 4 ω0 2
where
t γ2 − 4 ω02
σ1 =
2
The term γ2 − 4ω02 appears in various parts of the solution. Rewrite it in a simpler form by
γ
introducing the damping ratio ζ ≡ .
2ω0
γ 2
2
γ2 − 4ω02 = 2ω0 − 1 = 2ω0 ζ − 1,
2ω0
syms zeta;
sol = subs(sol, ...
sqrt(gamma^2 - 4*omega_0^2), ...
2*omega_0*sqrt(zeta^2-1))
sol =
2-80
The Physics of the Damped Harmonic Oscillator
γt σ2 σ1 γ σ2 γ σ1
e− 2 + + −
2 2 2 2
4 ω0 ζ − 1 4 ω0 ζ − 1
where
2
σ1 = e−ω0 t ζ − 1
2
σ2 = eω0 t ζ − 1
sol =
−ω0 t ζ σ2 σ1 ζ σ2 ζ σ1
e + + −
2 2 2 2
2 ζ −1 2 ζ −1
where
2
σ1 = e−ω0 t ζ − 1
2
σ2 = eω0 t ζ − 1
We have derived the general solution for the motion of the damped harmonic oscillator with no
driving forces. Next, we'll explore three special cases of the damping ratio ζ where the motion takes
on simpler forms. These cases are called
2 2
If ζ < 1, then ζ − 1 = i 1 − ζ is purely imaginary
solUnder = subs(sol, sqrt(zeta^2-1), 1i*sqrt(1-zeta^2))
solUnder =
−ω0 t ζ σ1 σ2 ζ σ1 i ζ σ2 i
e + + −
2 2 2 2
2 1−ζ 2 1−ζ
where
2
σ1 = e−ω0 t 1 − ζ i
2
σ2 = eω0 t 1 − ζ i
2 2
Notice the terms ei ω0 t ζ −1± e−i ω0 t ζ −1 in the above equation and recall the identity
ei x = cos x + i sin x .
2-81
2 Symbolic Computations in MATLAB
−ω0 t ζ 2
solUnder = e cos ω0 t 1 − ζ
−ω0 t ζ 2
solUnder(t, omega_0, zeta) = e cos ω0 t 1 − ζ
2
The system oscillates at a natural frequency of ω0 1 − ζ and decays at an exponential rate of 1/ω0 ζ.
hold on;
for k = 2:numel(z)
fplot(@(t)solUnder(t, w, z(k)), [0 T], lineStyle{k});
end
hold off;
grid on;
xticks(T*linspace(0,1,5));
xticklabels({'0','\pi','2\pi','3\pi','4\pi'});
xlabel('t / \omega_0');
ylabel('amplitude');
lgd = legend('0','1/4','1/2','3/4');
title(lgd,'\zeta');
title('Underdamped');
2-82
The Physics of the Damped Harmonic Oscillator
2
If ζ > 1, then ζ − 1 is purely real and the solution can be rewritten as
solOver = sol
solOver =
−ω0 t ζ σ2 σ1 ζ σ2 ζ σ1
e + + −
2 2 2 2
2 ζ −1 2 ζ −1
where
2
σ1 = e−ω0 t ζ − 1
2
σ2 = eω0 t ζ − 1
solOver =
2 2
−ω0 t ζ eω0 t ζ − 1 e−ω0 t ζ − 1
e +
2 2
2-83
2 Symbolic Computations in MATLAB
2 2
eω0t ζ − 1 + e−ω0t ζ − 1
ex + e−x
Notice the terms 2
and recall the identity cosh x = 2
.
c = exp(-omega_0*t*zeta);
solOver = c*rewrite(solOver / c, 'cosh')
2 −ω0 t ζ
solOver = cosh ω0 t ζ − 1 e
2 −ω0 t ζ
solOver(t, omega_0, zeta) = cosh ω0 t ζ − 1 e
hold on;
for k = 2:numel(z)
fplot(@(t)solOver(t, w, z(k)), [0 T], lineStyle{k});
end
hold off;
grid on;
xticks(T*linspace(0,1,5));
xticklabels({'0','\pi','2\pi','3\pi','4\pi'});
xlabel('\omega_0 t');
ylabel('amplitude');
lgd = legend('1+1/4','1+1/2','1+3/4','2');
title(lgd,'\zeta');
title('Overdamped');
2-84
The Physics of the Damped Harmonic Oscillator
−ω0 t
solCritical(t, omega_0) = e ω0 t + 1
w = 1;
T = 4*pi;
2-85
2 Symbolic Computations in MATLAB
6. Conclusion
We have examined the different damping states for the harmonic oscillator by solving the ODEs which
represents its motion using the damping ratio ζ . Plot all three cases together to compare and contrast
them.
zOver = pi;
zUnder = 1/zOver;
w = 1;
T = 2*pi;
lineStyle = {'-','--',':k'};
textColor = lines(3);
text(3*pi/2, 0.3 , 'over-damped' ,'Color',textColor(1,:));
text(pi*3/4, 0.05, 'critically-damped','Color',textColor(2,:));
text(pi/8 , -0.1, 'under-damped');
grid on;
xlabel('\omega_0 t');
ylabel('amplitude');
xticks(T*linspace(0,1,5));
2-86
The Physics of the Damped Harmonic Oscillator
xticklabels({'0','\pi/2','\pi','3\pi/2','2\pi'});
yticks((1/exp(1))*[-1 0 1 2 exp(1)]);
yticklabels({'-1/e','0','1/e','2/e','1'});
lgd = legend('\pi','1','1/\pi');
title(lgd,'\zeta');
title('Damped Harmonic Oscillator');
See Also
Functions
diff | subs | dsolve | fplot | collect | expand | rewrite
2-87
2 Symbolic Computations in MATLAB
This example uses Symbolic Math Toolbox™ and the Statistics and Machine Learning Toolbox™ to
explore and derive a parametric analytical expression for the average power generated by a wind
turbine.
The parametric equation can be used for evaluating various wind turbine configurations and wind
farm sites. More information see Wind Resource Assessment.
Background
The total power delivered to a wind turbine can be estimated by taking the derivative of the wind's
kinetic energy. This results in the following expression:
ρ A u3
Pw = 2
(1)
The process of converting wind power to electrical power results in efficiency losses, as described in
the diagram below.
2-88
Evaluating the Average Power Delivered by a Wind Turbine
The electrical power output of a practical wind turbine can be described using the following equation:
Ctot ρ Au3
Pe = 2
(2) where Ctot = overall efficiency = CpCtCg
The overall efficiency is between 0.3 and 0.5, and varies with both wind speed and rotational speed of
the turbine. For a fixed rotational speed, there is a rated wind speed at which electrical power
generated by the wind turbine is near its maximum (Per), and overall efficiency at this point is
denoted CtotR.
CtotR ρ Au3
Per = 2
(3)
Assuming a fixed rotational speed, the electrical power output of the wind turbine can be estimated
using the following profile:
Where
As seen in the figure, we assume that output power increases between uc and ur , then is at a constant
maximum value between ur and uf . Power output is zero for all other conditions.
2-89
2 Symbolic Computations in MATLAB
Pe =
0 if u < uc
C1 + C2 uk if uc ≤ u ∧ u ≤ ur
Per if u ≤ uf ∧ ur ≤ u
0 if uf < u
C_1 =
Per uck
uck − ur k
C_2 =
Per
−
uck − ur k
The rated power output offers a good indication of a how much power a wind turbine is capable of
producing, however we'd like to estimate how much power (on average) the wind turbine will actually
deliver. To calculate average power, we need to account for external wind conditions. A Weibull
distribution does a good job at modeling the variance in wind, therefore the wind profile can be
estimated using the following probability density function:
b u b−1
a a
fu = (4)
u b
e a
In general, larger 'a' values indicate a higher median wind speed, and larger 'b' values indicate
reduced variability.
We use the Statistics and Machine Learning Toolbox to generate a “Weibull Distribution” (Statistics
and Machine Learning Toolbox) and illustrate the variability in wind at our wind farm site (a=12.5,
b=2.2):
a = 12.5;
b = 2.2;
N = 1000;
pd = makedist('Weibull','a',a,'b',b)
pd =
WeibullDistribution
Weibull distribution
A = 12.5
B = 2.2
r = wblrnd(a,b,[1 N])
r = 1×1000
2-90
Evaluating the Average Power Delivered by a Wind Turbine
6.0811 4.3679 17.3751 4.1966 8.7677 18.3517 13.9761 9.9363 3.0039 2.7
x = linspace(0,34,N);
y = pdf(pd,x);
plot(x,y,'LineWidth',2)
hold on
histogram(r,15,'Normalization','pdf')
hold off
title('Weibull Distribution of Wind Speeds')
xlabel('Wind Speed (m/s)')
The average power output from a wind turbine can be obtained using the following integral:
∞
Peaverage = ∫0 Pe(u) f (u)du (5)
Power is zero when wind speed is less than the cut in wind speed uc and greater than furling wind
speed uf . Therefore, the integral can be expressed as follows:
u u u
Peaverage = C1 ∫ucr f u du + C2 ∫ucr ub f u du + Per ∫u f f u du (6)
r
2-91
2 Symbolic Computations in MATLAB
There are two distinct integrals in equation (7). We plug equation (4) into these integrals and simplify
u b b u b−1
them using the substitutions: x = a
and dx = a a
du. This simplifies our original integrals to
the following:
1
∫ f u du = ∫ dx (7)
ex
x
∫ub f u du = ab ∫ dx (8)
ex
u b
Solving these integrals and then replacing x with a
yields:
syms a b x
int1 = int(exp(-x), x);
int1 = subs(int1, x, (u/a)^b)
int1 =
u b
− e− a
int2 =
u b u b
−ab e− a +1
a
Substituting the results into equation (6) yields an equation for average power output of the wind
turbine.
Peavg = subs(C_1 * int1, u, u_r) - subs(C_1 * int1, u, u_c) + subs(C_2 * int2, u, u_r) - subs(C_2
Peavg =
uc b uc b ur b
uc b
uf b Per ab e− a +1 Per ab σ2 +1
− Per uck e− a Per uck σ2 a a
Per σ2 − Per e a + − − +
σ1 σ1 σ1 σ1
where
σ1 = uck − ur k
ur b
σ2 = e− a
IV. Conclusion
We have used the Symbolic Math Toolbox to develop a parametric equation which can be used to
perform simulation studies to determine the average power generated for various wind turbine
configurations and wind farm sites.
2-92
Developing an Algorithm for Undistorting an Image
This example develops a mathematical model using the Symbolic Math Toolbox™ to undistort an
image and features a local function in the live script.
Background
Any real world point P X, Y, Z can be defined with respect to some 3-D world origin.
Relative to a camera lens, this 3-D point can be defined as p0, which is obtained by rotating and
translating P.
p0 = x0, y0, z0 = R P + t
The 3-D point p0 is then projected into the camera's image plane as a 2D point, (x1, y1).
x0 y0
x1 = , y1 =
z0 z0
When a camera captures an image, it does not precisely capture the real points, but rather a slightly
distorted version of the real points which can be denoted (x2, y2). The distorted points can be
described using the following function:
x2 = x1 1 + k1 r 2 + k2 r 4 + 2 p1 x1 y1 + p2 r 2 + 2 x12
y2 = y1 1 + k1 r 2 + k2 r 4 + 2 p2 x1 y1 + p1 r 2 + 2 y12
where:
r = x12 + y12
Distortion
An example of lens distortion is shown below; original distorted image (left) and undistorted image
(right).
2-93
2 Symbolic Computations in MATLAB
Note the curvature of the lines toward the edges of the first image. For applications such as image
reconstruction and tracking, it is important to know the real world location of points. When we have a
distorted image, we know the distorted pixel locations (x2, y2). It's our goal to determine the
undistorted pixel locations (x1, y1) given (x2, y2) and the distortion coefficients of the particular lens.
While otherwise straightforward, the nonlinear nature of the lens distortion makes the problem
challenging.
% Parameters
syms k_1 k_2 p_1 p_2 real
syms r x y
distortionX = subs(x * (1 + k_1 * r^2 + k_2 * r^4) + 2 * p_1 * x * y + p_2 * (r^2 + 2 * x^2), r,
2
distortionX = p2 3 x2 + y2 + x k2 x2 + y2 + k1 x2 + y2 + 1 + 2 p1 x y
distortionY = subs(y * (1 + k_1 * r^2 + k_2 * r^4) + 2 * p_2 * x * y + p_1 * (r^2 + 2 * y^2), r,
2
distortionY = p1 x2 + 3 y2 + y k2 x2 + y2 + k1 x2 + y2 + 1 + 2 p2 x y
Radial Distortion k1 = 0
2-94
Developing an Algorithm for Undistorting an Image
We plot a grid of pixel locations assuming our lens has a radial distortion coefficient k1 = 0. Note that
distortion is smallest near the center of the image and largest near the edges.
% Set Parameters
parameters = [k_1 k_2 p_1 p_2];
parameterValues = [0 0 0 0];
plotLensDistortion(distortionX,distortionY,parameters,parameterValues)
spacing = 0.2000
distortionX = x
distortionY = y
Radial Distortion k1 = 0 . 15
% Set Parameters
parameters = [k_1 k_2 p_1 p_2];
parameterValues = [0.15 0 0 0];
plotLensDistortion(distortionX,distortionY,parameters,parameterValues)
spacing = 0.2000
distortionX =
3 x2 3 y2
x + +1
20 20
2-95
2 Symbolic Computations in MATLAB
distortionY =
3 x2 3 y2
y + +1
20 20
Given a camera's lens distortion coefficients and a set of distorted pixel locations (x2, y2), we want to
be able to calculate the undistorted pixel locations (x1, y1). We will look at the specific case where all
distortion coefficients are zero except for k1 which equals 0.2.
syms X Y positive
eq1 = X == distortionX
2
eq1 = X = p2 3 x2 + y2 + x k2 x2 + y2 + k1 x2 + y2 + 1 + 2 p1 x y
eq2 = Y == distortionY
2
eq2 = Y = p1 x2 + 3 y2 + y k2 x2 + y2 + k1 x2 + y2 + 1 + 2 p2 x y
We define the distortion equations for given distortion coefficients, and solve for the undistorted pixel
locations (x1, y1).
2-96
Developing an Algorithm for Undistorting an Image
eq1 =
x3 x y2
X= + +x
5 5
eq2 =
x2 y y3
Y= + +y
5 5
Since element 1 is the only real solution, we will extract that expression into its own variable.
[Result.x Result.y]
ans =
X σ1
σ1
Y
where
5 Y2
σ1 = σ2 −
3 X + Y 2 σ2
2
1/3
5 Y3 25 Y 6 125 Y 6
σ2 = + +
2 X2 + Y 2 4 X2 + Y 2
2
27 X 2 + Y 2
3
Now we have analytical expressions for the pixel locations X and Y which we can use to undistort our
images.
syms x y
% Inspect and parametrically substitute in the values for k_1 k_2 p_1 p_2
distortionX = subs(distortionX,parameters,parameterValues)
distortionY = subs(distortionY,parameters,parameterValues)
2-97
2 Symbolic Computations in MATLAB
end
end
hold off
grid on
end
2-98
Electric Dipole Moment and Radiation Power
This example finds the average radiation power of two attracting charges moving in an elliptical orbit
(an electric dipole).
The two opposite charges, e1 and e2, form an electric dipole. The masses of the charged particles are
m1 and m2, respectively. For the common center of mass m1*r1 + m2*r2 = 0, where r1 and r2 are
distance vectors to the charged particles. The distance between charged particles is r = r1 - r2.
syms m1 m2 e1 e2 r1 r2 r
[r1,r2] = solve(m1*r1 + m2*r2 == 0, r == r1 - r2, r1, r2)
r1 =
m2 r
m1 + m2
r2 =
m1 r
−
m1 + m2
Dipole Moment
d = e1*r1 + e2*r2;
simplify(d)
ans =
r e1 m2 − e2 m1
m1 + m2
2-99
2 Symbolic Computations in MATLAB
2 2
According to the Larmor formula, the total power radiated in a unit of time is J = d̈ , or, in terms
3c3
2 m1m2 e1 e2 2 2
of the distance between the charged particles, J = − r̈ . Here dot means a
3c m1 + m2 m1 m2
3
α
time derivative. Coulomb's law mr̈ = − lets you find the values of acceleration r̈ in terms of the
r2
m1m2
reduced mass of the system, m = , and the product of the charges of the particles,
m1 + m2
α = e1e2 .
alpha = sym('alpha');
syms m c
m = m1*m2/(m1 + m2);
r2 = -alpha/(m*r^2);
J = simplify(subs(2/(3*c^3)*d^2, r, r2))
J =
2
2 α2 e1 m2 − e2 m1
3 c3 m12 m22 r 4
The major semiaxis a and eccentricity ϵ of an elliptical orbit are given by the following expressions,
where E is the total orbital energy, and L = mr 2ϕ̇ is the angular momentum.
syms E L phi
a = alpha/(2*E)
a =
α
2E
eccentricity = sqrt(1-2*E*L^2/(m*alpha^2))
eccentricity =
2 E L2 m1 + m2
1−
α2 m1 m2
The equation of an elliptical orbit, 1 + ϵcosϕ = a 1 − ϵ2 /r, lets you express the distance r in terms of
the angle phi.
The average radiation power of two charged particles moving in an elliptical orbit is an integral of the
∫
T
radiation power over one full cycle of motion, normalized by the period of motion, Javg = 1/T J dt.
0
The period of motions T is
T = 2*pi*sqrt(m*a^3/alpha);
2-100
Electric Dipole Moment and Radiation Power
Changing the integration variable t to phi, you get the following result. Use the simplify function
to get a shorter integration result. Here, use subs to evaluate J.
J = subs(J);
Javg = simplify(1/T*int(J*m*r^2/L, phi, 0, 2*pi))
Javg =
2
2 2 α2 e1 m2 − e2 m1 2 E L2 m1 + 2 E L2 m2 − 3 α2 m1 m2
−
3 α2 m1 m2
3 L5 c3 m1 + m2
E3 m1 + m2
Estimate the average radiation power of the electric dipole with one particle much heavier than the
over, m1>>m2. For this, compute the limit of the expression for radiation power, assuming that m1
tends to infinity.
ans =
2 2 α2 e22 2 E L2 − 3 α2 m2
−
α2 m2
3 L5 c3
E3
2-101
2 Symbolic Computations in MATLAB
This example shows how to model a bouncing ball, which is a classical hybrid dynamic system. This
model includes both continuous dynamics and discrete transitions. It uses the Symbolic Math
Toolbox™ to help explain some of the theory behind ODE solving in the “Simulation of Bouncing Ball”
(Simulink).
Assumptions
Derivation
Cr = vb − va /ua − ub
where v is the speed of object before impact and u is the speed after.
2
d h
= −g
dt2
into
and
2-102
Validate Simulink Model Using Symbolic Math Toolbox
We will use basic 1st order numerical integration using forward Euler.
Using the Symbolic Math Toolbox, we can approach the problem analytically. This allows us to solve
certain problems more easily, such as determining precisely when the ball first hits the ground
(below).
2
d h dh dv
Split the second order differential equation = − ginto = v and = − g.
dt 2 dt dt
Dh = diff(H);
D2h = diff(H, 2) == g
D2h(t) =
∂2
H t =g
∂t2
eqn =
g t2
+ v0 t + h0
2
eqn =
981 t2
− + 15 t + 10
200
Find the time at which the ball hits the ground by solving for zero:
assume(t > 0)
tHit = solve(eqn == 0)
tHit =
20 5 26 500
+
109 327
2-103
2 Symbolic Computations in MATLAB
fplot(eqn,[0 10])
ylim([0 25])
Format your exact results using variable precision arithmetic with vpa:
disp(['The ball with an initial height of 10m and velocity of 15m/s will hit the ground at ' char
The ball with an initial height of 10m and velocity of 15m/s will hit the ground at 3.621 seconds
2-104
Validate Simulink Model Using Symbolic Math Toolbox
Simulate the bouncing ball (we will use basic 1st order numerical integration using forward Euler):
for i=1:N-1
v(i+1)=v(i)-gravity*dt;
h(i+1)=h(i)+v(i)*dt;
v(i)=-v(i)*c_bounce;
v(i+1)=v(i)-gravity*dt;
h(i+1)=0+v(i)*dt;
end
end
plot(t,h,'o')
hold on
fplot(eqn,[0 10])
title('Height over time')
ylim([0 25])
hold off
2-105
2 Symbolic Computations in MATLAB
plot(t,v)
title('Velocity over time')
2-106
Validate Simulink Model Using Symbolic Math Toolbox
disp(['The ball with an initial height of 10m and velocity of 15m/s will hit the ground at ' char
The ball with an initial height of 10m and velocity of 15m/s will hit the ground at 3.621 seconds
From the numerical simulation we can find the closest value in the simulation when h ti ≈ 0
i = ceil(double(tHit/dt));
t([i-1 i i+1])
ans = 1×3
plot(t,h,'o')
hold on
fplot(eqn,[0 10])
plot(t([i-1 i i+1 ]),h([i-1 i i+1 ]),'*R')
title('Height over time')
xlim([0 5])
ylim([0 25])
hold off
2-107
2 Symbolic Computations in MATLAB
2-108
3
Mathematics
3-2
Solve Algebraic Equations
In this section...
“Solve an Equation” on page 3-3
“Return the Full Solution to an Equation” on page 3-3
“Work with the Full Solution, Parameters, and Conditions Returned by solve” on page 3-4
“Visualize and Plot Solutions Returned by solve” on page 3-5
“Simplify Complicated Results and Improve Performance” on page 3-6
Solve an Equation
If eqn is an equation, solve(eqn, x) solves eqn for the symbolic variable x.
Use the == operator to specify the familiar quadratic equation and solve it using solve.
syms a b c x
eqn = a*x^2 + b*x + c == 0;
solx = solve(eqn, x)
solx =
-(b + (b^2 - 4*a*c)^(1/2))/(2*a)
-(b - (b^2 - 4*a*c)^(1/2))/(2*a)
solx is a symbolic vector containing the two solutions of the quadratic equation. If the input eqn is
an expression and not an equation, solve solves the equation eqn == 0.
To solve for a variable other than x, specify that variable instead. For example, solve eqn for b.
solb = solve(eqn, b)
solb =
-(a*x^2 + c)/x
If you do not specify a variable, solve uses symvar to select the variable to solve for. For example,
solve(eqn) solves eqn for x.
solx =
-pi/4
To return all solutions along with the parameters in the solution and the conditions on the solution,
set the ReturnConditions option to true. Solve the same equation for the full solution. Provide
3-3
3 Mathematics
three output variables: for the solution to x, for the parameters in the solution, and for the conditions
on the solution.
syms x
[solx, param, cond] = solve(cos(x) == -sin(x), x, 'ReturnConditions', true)
solx =
pi*k - pi/4
param =
k
cond =
in(k, 'integer')
solx contains the solution for x, which is pi*k - pi/4. The param variable specifies the parameter
in the solution, which is k. The cond variable specifies the condition in(k, 'integer') on the
solution, which means k must be an integer. Thus, solve returns a periodic solution starting at pi/4
which repeats at intervals of pi*k, where k is an integer.
To find values of x in the interval -2*pi<x<2*pi, solve solx for k within that interval under the
condition cond. Assume the condition cond using assume.
assume(cond)
solk = solve(-2*pi<solx, solx<2*pi, param)
solk =
-1
0
1
2
To find values of x corresponding to these values of k, use subs to substitute for k in solx.
xvalues =
-(5*pi)/4
-pi/4
(3*pi)/4
(7*pi)/4
To convert these symbolic values into numeric values for use in numeric calculations, use vpa.
xvalues = vpa(xvalues)
xvalues =
-3.9269908169872415480783042290994
-0.78539816339744830961566084581988
2.3561944901923449288469825374596
5.4977871437821381673096259207391
3-4
Solve Algebraic Equations
fplot(cos(x))
hold on
grid on
fplot(-sin(x))
title('Both sides of equation cos(x) = -sin(x)')
legend('cos(x)','-sin(x)','Location','best','AutoUpdate','off')
Calculate the values of the functions at the values of x, and superimpose the solutions as points using
scatter.
yvalues = cos(xvalues)
yvalues =
−0.70710678118654752440084436210485
0.70710678118654752440084436210485
−0.70710678118654752440084436210485
0.70710678118654752440084436210485
scatter(xvalues, yvalues)
3-5
3 Mathematics
See Also
Related Examples
• “Solve System of Linear Equations” on page 3-30
• “Solve Differential Equation” on page 3-43
• “Solve Differential Algebraic Equations (DAEs)” on page 3-61
3-6
Solve System of Algebraic Equations
This topic shows you how to solve a system of equations symbolically using Symbolic Math Toolbox™.
This toolbox offers both numeric and symbolic equation solvers. For a comparison of numeric and
symbolic solvers, see “Select Numeric or Symbolic Solver” on page 3-33.
x2 y2 = 0
y
x− = α,
2
and you want to solve for x and y. First, create the necessary symbolic objects.
syms x y a
There are several ways to address the output of solve. One way is to use a two-output call. The call
returns the following.
solx =
a
0
soly =
0
−2 a
Modify the first equation to x2 y2 = 1. The new system has more solutions. Four distinct solutions are
produced.
solx =
a a2 − 2
−
2 2
a a2 + 2
−
2 2
a a2 − 2
+
2 2
a a2 + 2
+
2 2
soly =
−a − a2 − 2
−a − a2 + 2
a2 − 2 − a
a2 + 2 − a
3-7
3 Mathematics
Since you did not specify the dependent variables, solve uses symvar to determine the variables.
This way of assigning output from solve is quite successful for “small” systems. For instance, if you
have a 10-by-10 system of equations, typing the following is both awkward and time consuming.
[x1,x2,x3,x4,x5,x6,x7,x8,x9,x10] = solve(...)
To circumvent this difficulty, solve can return a structure whose fields are the solutions. For
example, solve the system of equations u^2 - v^2 = a^2, u + v = 1, a^2 - 2*a = 3. The
solver returns its results enclosed in a structure.
syms u v a
S = solve(u^2 - v^2 == a^2, u + v == 1, a^2 - 2*a == 3)
S.a
ans =
−1
3
Similar comments apply to the solutions for u and v. The structure S can now be manipulated by the
field and index to access a particular portion of the solution. For example, to examine the second
solution, you can use the following statement to extract the second component of each field.
s2 = [S.a(2),S.u(2),S.v(2)]
s2 = 3 5 −4
The following statement creates the solution matrix M whose rows comprise the distinct solutions of
the system.
M = [S.a,S.u,S.v]
M =
−1 1 0
3 5 −4
Linear systems of equations can also be solved using matrix division. For example, solve this system.
clear u v x y
syms u v x y
eqns = [x + 2*y == u, 4*x + 5*y == v];
S = solve(eqns);
sol = [S.x;S.y]
3-8
Solve System of Algebraic Equations
sol =
2v 5u
−
3 3
4u v
−
3 3
[A,b] = equationsToMatrix(eqns,x,y);
z = A\b
z =
2v 5u
−
3 3
4u v
−
3 3
Thus, sol and z produce the same solution, although the results are assigned to different variables.
solve does not automatically return all solutions of an equation. To return all solutions along with
the parameters in the solution and the conditions on the solution, set the ReturnConditions option
to true.
4
sin x + cos y =
5
1
sin x cos y =
10
Visualize the system of equations using fimplicit. To set the x-axis and y-axis values in terms of pi,
get the axes handles using axes in a. Create the symbolic array S of the values -2*pi to 2*pi at
intervals of pi/2. To set the ticks to S, use the XTick and YTick properties of a. To set the labels for
the x-and y-axes, convert S to character vectors. Use arrayfun to apply char to every element of S
to return T. Set the XTickLabel and YTickLabel properties of a to T.
syms x y
eqn1 = sin(x)+cos(y) == 4/5;
eqn2 = sin(x)*cos(y) == 1/10;
a = axes;
fimplicit(eqn1,[-2*pi 2*pi],'b');
hold on
grid on
fimplicit(eqn2,[-2*pi 2*pi],'m');
L = sym(-2*pi:pi/2:2*pi);
a.XTick = double(L);
a.YTick = double(L);
M = arrayfun(@char, L, 'UniformOutput', false);
a.XTickLabel = M;
a.YTickLabel = M;
title('Plot of System of Equations')
legend('sin(x)+cos(y) == 4/5','sin(x)*cos(y) == 1/10',...
'Location','best','AutoUpdate','off')
3-9
3 Mathematics
The solutions lie at the intersection of the two plots. This shows the system has repeated, periodic
solutions. To solve this system of equations for the full solution set, use solve and set the
ReturnConditions option to true.
S = solve(eqn1,eqn2,'ReturnConditions',true)
solve returns a structure S with the fields S.x for the solution to x, S.y for the solution to y,
S.parameters for the parameters in the solution, and S.conditions for the conditions on the
solution. Elements of the same index in S.x, S.y, and S.conditions form a solution. Thus, S.x(1),
S.y(1), and S.conditions(1) form one solution to the system of equations. The parameters in
S.parameters can appear in all solutions.
S.x
ans =
z1
z1
3-10
Solve System of Algebraic Equations
S.y
ans =
z
z
S.parameters
ans = z z1
S.conditions
ans =
z + acos σ3 z − acos σ3 π − z1 + σ1 z1 + σ1
∈ℤ∨ ∈ℤ ∧ − ∈ℤ∨ ∈ℤ
2π 2π 2π 2π
z1 − π + asin σ3 z1 − asin σ3 z + σ2 z − σ2
∈ℤ∨ ∈ℤ ∧ ∈ℤ∨ ∈ℤ
2π 2π 2π 2π
where
6 2
σ1 = asin −
10 5
2 6
σ2 = acos −
5 10
6 2
σ3 = +
10 5
To solve the system of equations under conditions, specify the conditions in the input to solve.
Solve the system of equations considered above for x and y in the interval -2*pi to 2*pi. Overlay
the solutions on the plot using scatter.
Srange = solve(eqn1, eqn2, -2*pi < x, x < 2*pi, -2*pi < y, y < 2*pi, 'ReturnConditions', true);
scatter(Srange.x,Srange.y,'k')
3-11
3 Mathematics
You can use the solutions, parameters, and conditions returned by solve to find solutions within an
interval or under additional conditions. This section has the same goal as the previous section, to
solve the system of equations within a search range, but with a different approach. Instead of placing
conditions directly, it shows how to work with the parameters and conditions returned by solve.
For the full solution S of the system of equations, find values of x and y in the interval -2*pi to 2*pi
by solving the solutions S.x and S.y for the parameters S.parameters within that interval under
the condition S.conditions.
Before solving for x and y in the interval, assume the conditions in S.conditions using assume so
that the solutions returned satisfy the condition. Assume the conditions for the first solution.
assume(S.conditions(1))
paramx = intersect(symvar(S.x),S.parameters)
paramx = z1
paramy = intersect(symvar(S.y),S.parameters)
paramy = z
3-12
Solve System of Algebraic Equations
solparamx =
6 2 6 2 6 2 6 2
π + asin − asin − − π −asin − −2 π − asin −
10 5 10 5 10 5 10 5
solparamy =
6 2 6 2 6 2 6 2
acos + acos + − 2 π −acos + 2 π − acos +
10 5 10 5 10 5 10 5
Clear the assumptions set by S.conditions(1) using assume. Call asumptions to check that the
assumptions are cleared.
assume(S.parameters,'clear')
assumptions
ans =
assume(S.conditions(2))
Solve the second solution to x and y for the parameters paramx and paramy.
solparamx =
π + σ1 σ1 − π −σ1 −2 π − σ1
σ2 π − σ2 σ2 − 2 π −π − σ2
where
6 2
σ1 = asin −
10 5
6 2
σ2 = asin +
10 5
solparamy =
σ2 σ2 − 2 π −σ2 2 π − σ2
σ1 σ1 − 2 π −σ1 2 π − σ1
where
2 6
σ1 = acos −
5 10
6 2
σ2 = acos +
10 5
3-13
3 Mathematics
The first rows of paramx and paramy form the first solution to the system of equations, and the
second rows form the second solution.
To find the values of x and y for these values of paramx and paramy, use subs to substitute for
paramx and paramy in S.x and S.y.
solx =
π + σ1 σ1 − π −σ1 −2 π − σ1
σ2 π − σ2 σ2 − 2 π −π − σ2
where
6 2
σ1 = asin −
10 5
6 2
σ2 = asin +
10 5
soly =
σ2 σ2 − 2 π −σ2 2 π − σ2
σ1 σ1 − 2 π −σ1 2 π − σ1
where
2 6
σ1 = acos −
5 10
6 2
σ2 = acos +
10 5
Note that solx and soly are the two sets of solutions to x and to y. The full sets of solutions to the
system of equations are the two sets of points formed by all possible combinations of the values in
solx and soly.
Plot these two sets of points using scatter. Overlay them on the plot of the equations. As expected,
the solutions appear at the intersection of the plots of the two equations.
for i = 1:length(solx(1,:))
for j = 1:length(soly(1,:))
scatter(solx(1,i), soly(1,j), 'k')
scatter(solx(2,i), soly(2,j), 'k')
end
end
3-14
Solve System of Algebraic Equations
Symbolic calculations provide exact accuracy, while numeric calculations are approximations. Despite
this loss of accuracy, you might need to convert symbolic results to numeric approximations for use in
numeric calculations. For a high-accuracy conversion, use variable-precision arithmetic provided by
the vpa function. For standard accuracy and better performance, convert to double precision using
double.
Use vpa to convert the symbolic solutions solx and soly to numeric form.
vpa(solx)
ans =
2.9859135500977407388300518406219 −3.2972717570818457380952349259371 0.155679103492052499632591542
0.70095651347102524787213653614929 2.4406361401187679905905068471302 −5.5822287937085612290531502
vpa(soly)
ans =
0.86983981332387137135918515549046 −5.4133454938557151055661016110685 −0.8698398133238713713591851
1.4151172233028441195987301489821 −4.8680680838767423573265566175769 −1.4151172233028441195987301
3-15
3 Mathematics
If results look complicated, solve is stuck, or if you want to improve performance, see,
“Troubleshoot Equation Solutions from solve Function” on page 3-17.
3-16
Troubleshoot Equation Solutions from solve Function
In this section...
“Return Only Real Solutions” on page 3-17
“Apply Simplification Rules” on page 3-17
“Use Assumptions to Narrow Results” on page 3-18
“Simplify Solutions” on page 3-19
“Tips” on page 3-19
syms x
solve(x^5 - 1 == 0, x)
ans =
1
- (2^(1/2)*(5 - 5^(1/2))^(1/2)*1i)/4 - 5^(1/2)/4 - 1/4
(2^(1/2)*(5 - 5^(1/2))^(1/2)*1i)/4 - 5^(1/2)/4 - 1/4
5^(1/2)/4 - (2^(1/2)*(5^(1/2) + 5)^(1/2)*1i)/4 - 1/4
5^(1/2)/4 + (2^(1/2)*(5^(1/2) + 5)^(1/2)*1i)/4 - 1/4
If you only need real solutions, specify the Real option as true. The solve function returns the one
real solution.
ans =
1
syms x
solve(x^(5/2) + 1/x^(5/2) == 1, x)
ans =
1/(1/2 - (3^(1/2)*1i)/2)^(2/5)
1/((3^(1/2)*1i)/2 + 1/2)^(2/5)
-(5^(1/2)/4 - (2^(1/2)*(5 - 5^(1/2))^(1/2)*1i)/4 + 1/4)/(1/2 - (3^(1/2)*1i)/2)^(2/5)
-((2^(1/2)*(5 - 5^(1/2))^(1/2)*1i)/4 + 5^(1/2)/4 + 1/4)/(1/2 - (3^(1/2)*1i)/2)^(2/5)
-(5^(1/2)/4 - (2^(1/2)*(5 - 5^(1/2))^(1/2)*1i)/4 + 1/4)/(1/2 + (3^(1/2)*1i)/2)^(2/5)
-((2^(1/2)*(5 - 5^(1/2))^(1/2)*1i)/4 + 5^(1/2)/4 + 1/4)/(1/2 + (3^(1/2)*1i)/2)^(2/5)
3-17
3 Mathematics
ans =
1/(1/2 - (3^(1/2)*1i)/2)^(2/5)
1/((3^(1/2)*1i)/2 + 1/2)^(2/5)
syms x
solve(x^7 + 2*x^6 - 59*x^5 - 106*x^4 + 478*x^3 + 284*x^2 - 1400*x + 800, x)
ans =
1
- 5^(1/2) - 1
- 17^(1/2)/2 - 1/2
17^(1/2)/2 - 1/2
-5*2^(1/2)
5*2^(1/2)
5^(1/2) - 1
Assume x is a positive number and solve the equation again. The solve function only returns the
four positive solutions.
assume(x > 0)
solve(x^7 + 2*x^6 - 59*x^5 - 106*x^4 + 478*x^3 + 284*x^2 - 1400*x + 800, x)
ans =
1
17^(1/2)/2 - 1/2
5*2^(1/2)
5^(1/2) - 1
Place the additional assumption that x is an integer using in(x,'integer'). Place additional
assumptions on variables using assumeAlso.
assumeAlso(in(x,'integer'))
solve(x^7 + 2*x^6 - 59*x^5 - 106*x^4 + 478*x^3 + 284*x^2 - 1400*x + 800, x)
ans =
1
syms x
Alternatively, to make several assumptions, use the & operator. Make the following assumptions, and
solve the following equations.
syms a b c f g h y
assume(f == c & a == h & a~= 0)
S = solve([a*x + b*y == c, h*x - g*y == f], [x, y], 'ReturnConditions', true);
3-18
Troubleshoot Equation Solutions from solve Function
S.x
S.y
S.conditions
ans =
f/h
ans =
0
ans =
b + g ~= 0
Under the specified assumptions, the solution is x = f/h and y = 0 under the condition b + g ~=
0.
Clear the assumptions on the variables for further computations by recreating them using syms.
syms a c f h
Simplify Solutions
The solve function does not call simplification functions for the final results. To simplify the
solutions, call simplify.
Solve the following equation. Convert the numbers to symbolic numbers using sym to return a
symbolic result.
syms x
S = solve((sin(x) - 2*cos(x))/(sin(x) + 2*cos(x)) == 1/2, x)
S =
-log(-(- 140/37 + 48i/37)^(1/2)/2)*1i
-log((- 140/37 + 48i/37)^(1/2)/2)*1i
simplify(S)
ans =
-log(37^(1/2)*(- 1/37 - 6i/37))*1i
log(2)*1i - (log(- 140/37 + 48i/37)*1i)/2
Call simplify with more steps to simplify the result even further.
ans =
atan(6) - pi
atan(6)
Tips
• To represent a number exactly, use sym to convert the number to a floating-point object. For
example, use sym(13)/5 instead of 13/5. This represents 13/5 exactly instead of converting
13/5 to a floating-point number. For a large number, place the number in quotes. Compare
sym(13)/5, sym(133333333333333333333)/5, and sym('133333333333333333333')/5.
3-19
3 Mathematics
sym(13)/5
sym(133333333333333333333)/5
sym('133333333333333333333')/5
ans =
13/5
ans =
133333333333333327872/5
ans =
133333333333333333333/5
Placing the number in quotes and using sym provides the highest accuracy.
• If possible, simplify the system of equations manually before using solve. Try to reduce the
number of equations, parameters, and variables.
3-20
Solve Equations Numerically
Symbolic Math Toolbox™ offers both numeric and symbolic equation solvers. For a comparison of
numeric and symbolic solvers, see “Select Numeric or Symbolic Solver” on page 3-33. An equation
or a system of equations can have multiple solutions. To find these solutions numerically, use the
function vpasolve. For polynomial equations, vpasolve returns all solutions. For nonpolynomial
equations, vpasolve returns the first solution it finds. These examples show you how to use
vpasolve to find solutions to both polynomial and nonpolynomial equations, and how to obtain these
solutions to arbitrary precision.
Use vpasolve to find all the solutions to the function f (x) = 6x7 − 2x6 + 3x3 − 8.
syms f(x)
f(x) = 6*x^7-2*x^6+3*x^3-8;
sol = vpasolve(f)
sol =
1.0240240759053702941448316563337
−0.88080620051762149639205672298326 + 0.50434058840127584376331806592405 i
−0.88080620051762149639205672298326 − 0.50434058840127584376331806592405 i
−0.22974795226118163963098570610724 + 0.96774615576744031073999010695171 i
−0.22974795226118163963098570610724 − 0.96774615576744031073999010695171 i
0.7652087814927846556172932675903 + 0.83187331431049713218367239317121 i
0.7652087814927846556172932675903 − 0.83187331431049713218367239317121 i
vpasolve returns seven roots of the function, as expected, because the function is a polynomial of
degree seven.
Find Zeros of a Nonpolynomial Function Using Search Ranges and Starting Points
A plot of the function f (x) = e(x/7)cos(2x) reveals periodic zeros, with increasing slopes at the zero
points as x increases.
syms x
h = fplot(exp(x/7)*cos(2*x),[-2 25]);
grid on
3-21
3 Mathematics
Use vpasolve to find a zero of the function f. Note that vpasolve returns only one solution of a
nonpolynomial equation, even if multiple solutions exist. On repeated calls, vpasolve returns the
same result.
f = exp(x/7)*cos(2*x);
for k = 1:3
vpasolve(f,x)
end
ans = −7.0685834705770347865409476123789
ans = −7.0685834705770347865409476123789
ans = −7.0685834705770347865409476123789
To find multiple solutions, set the option 'Random' to true. This makes vpasolve choose starting
points randomly. For information on the algorithm that chooses random starting points, see
“Algorithms” on page 7-1626 on the vpasolve page.
for k = 1:3
vpasolve(f,x,'Random',true)
end
ans = −226.98006922186256147892598444194
ans = 98.174770424681038701957605727484
ans = 52.621676947629036744249276669932
3-22
Solve Equations Numerically
vpasolve(f,x,10)
ans = 10.210176124166828025003590995658
vpasolve(f,x,1000)
ans = 999.8118620049516981407362567287
To find a zero in the range 15 ≤ x ≤ 25, set the search range to [15 25].
vpasolve(f,x,[15 25])
ans = 21.205750411731104359622842837137
To find multiple zeros in the range [15 25], you cannot call vpasolve repeatedly because it returns
the same result on each call, as previously shown. Instead, set the search range and set 'Random' to
true.
for k = 1:3
vpasolve(f,x,[15 25],'Random',true)
end
ans = 21.205750411731104359622842837137
ans = 21.205750411731104359622842837137
ans = 16.493361431346414501928877762217
Because 'Random' selects starting points randomly, the same solution might be found on successive
calls.
Create a function findzeros to systematically find all zeros for f in a given search range, within a
specified error tolerance. The function starts with the input search range and calls vpasolve to find
a zero. Then, it splits the search range into two around the zero value and recursively calls itself with
the new search ranges as inputs to find more zeros.
Declare the function with the three inputs and one output. The first input is the function, the second
input is the range, and the optional third input allows you to specify the error between a zero and the
higher and lower bounds generated from it.
If you do not specify the optional argument for error tolerance, findzeros sets err to 0.001.
if nargin < 2
err = 1e-3;
end
sol = vpasolve(f,range);
3-23
3 Mathematics
if(isempty(sol))
return
If vpasolve finds a zero, split the search range into two search ranges above and below the zero.
else
lowLimit = sol-err;
highLimit = sol+err;
Call findzeros with the lower search range. If findzeros returns zeros, copy the values into the
solution array and sort them.
Call findzeros with the higher search range. If findzeros returns zeros, copy the values into the
solution array and sort them.
The entire function findzeros is as follows. Save this function as findzeros.m in the current
folder.
Call findzeros with search range [15 25] to find all zeros in that range for f(x) = exp(x/
7)*cos(2*x), within the default error tolerance.
3-24
Solve Equations Numerically
syms f(x)
f(x) = exp(x/7)*cos(2*x);
sol = findzeros(f,[15 25])'
sol =
16.493361431346414501928877762217
18.064157758141311121160199453857
19.634954084936207740391521145497
21.205750411731104359622842837137
22.776546738526000978854164528776
24.347343065320897598085486220416
Use digits to set the precision of the solutions returned by vpasolve. By default, vpasolve
returns solutions to a precision of 32 significant figures.
f = exp(x/7)*cos(2*x);
vpasolve(f)
ans = −7.0685834705770347865409476123789
Use digits to increase the precision to 64 significant figures. When modifying digits, ensure that
you save its current value so that you can restore it.
digitsOld = digits;
digits(64)
vpasolve(f)
ans = −7.068583470577034786540947612378881489443631148593988097193625333
digits(16)
z = 10 cos x + cos y
z = x + y2 − 0 . 1x2 y
x + y − 2.7 = 0
A plot of the equations for 0 ≤ x ≤ 2 . 5 and 0 ≤ x ≤ 2 . 5 shows that the three surfaces intersect in two
points. To better visualize the plot, change the line of sight using view.
syms x y z
eqn1 = z == 10*(cos(x) + cos(y));
eqn2 = z == x+y^2-0.1*x^2*y;
eqn3 = x+y-2.7 == 0;
equations = [eqn1 eqn2 eqn3];
fimplicit3(equations)
axis([0 2.5 0 2.5 -20 10])
title('System of Multivariate Equations')
view(69,28)
3-25
3 Mathematics
Use vpasolve to find a point where the surfaces intersect. The function vpasolve returns a
structure. To access the x-, y-, and z-values of the solution, index into the structure.
sol = vpasolve(equations);
[sol.x sol.y sol.z]
To search a region of the solution space, specify search ranges for the variables. If you specify the
ranges 0 ≤ x ≤ 1 . 5 and 1 . 5 ≤ y ≤ 2 . 5, then vpasolve function searches the bounded area shown.
3-26
Solve Equations Numerically
Use vpasolve to find a solution for this search range. To omit a search range for z, set the third
search range to [NaN NaN].
vars = [x y z];
range = [0 1.5; 1.5 2.5; NaN NaN];
sol = vpasolve(equations,vars,range);
[sol.x sol.y sol.z]
To find multiple solutions, set the 'Random' option to true. This makes vpasolve use random
starting points on successive runs. The 'Random' option can be used in conjunction with search
ranges to make vpasolve use random starting points within a search range. Because 'Random'
selects starting points randomly, the same solution might be found on successive calls. Call
vpasolve repeatedly to ensure you find both solutions.
clear sol
range = [0 3; 0 3; NaN NaN];
for k = 1:5
temp = vpasolve(equations,vars,range,'Random',true);
sol(k,1) = temp.x;
sol(k,2) = temp.y;
sol(k,3) = temp.z;
end
sol
sol =
3-27
3 Mathematics
Plot the equations. Superimpose the solutions as a scatter plot of points with yellow X markers using
scatter3. To better visualize the plot, make two of the surfaces transparent using alpha and
change the line of sight using view.
vpasolve finds solutions at the intersection of the surfaces formed by the equations as shown.
clf
ax = axes;
h = fimplicit3(equations);
h(2).FaceAlpha = 0;
h(3).FaceAlpha = 0;
axis([0 2.5 0 2.5 -20 10])
hold on
scatter3(sol(:,1),sol(:,2),sol(:,3),600,'red','X','LineWidth',2)
title('Randomly Found Solutions in Specified Search Range')
cz = ax.Children;
view(69,28)
hold off
3-28
Solve Equations Numerically
digits(digitsOld)
3-29
3 Mathematics
In this section...
“Solve System of Linear Equations Using linsolve” on page 3-30
“Solve System of Linear Equations Using solve” on page 3-31
a11 … a1n
A= ⋮ ⋱ ⋮
am1 ⋯ amn
b1
b = ⋮
bm
If you do not have the system of linear equations in the form AX = B, use equationsToMatrix to
convert the equations into this form. Consider the following system.
2x + y + z = 2
−x + y − z = 3
x + 2y + 3z = − 10
Use equationsToMatrix to convert the equations into the form AX = B. The second input to
equationsToMatrix specifies the independent variables in the equations.
[A,B] = equationsToMatrix([eqn1, eqn2, eqn3], [x, y, z])
A =
[ 2, 1, 1]
3-30
Solve System of Linear Equations
[ -1, 1, -1]
[ 1, 2, 3]
B =
2
3
-10
X = linsolve(A,B)
X =
3
1
-5
2x + y + z = 2
−x + y − z = 3
x + 2y + 3z = − 10
syms x y z
eqn1 = 2*x + y + z == 2;
eqn2 = -x + y - z == 3;
eqn3 = x + 2*y + 3*z == -10;
Solve the system of equations using solve. The inputs to solve are a vector of equations, and a
vector of variables to solve the equations for.
xSol =
3
ySol =
1
zSol =
-5
solve returns the solutions in a structure array. To access the solutions, index into the array.
3-31
3 Mathematics
See Also
More About
• “Solve Algebraic Equations” on page 3-3
• “Solve System of Algebraic Equations” on page 3-7
3-32
Select Numeric or Symbolic Solver
Solve Equations Symbolically Using solve Solve Equations Numerically Using vpasolve
Returns exact solutions. Solutions can then be Returns approximate solutions. Precision can be
approximated using vpa. controlled arbitrarily using digits.
Returns a general form of the solution. For polynomial equations, returns all numeric
solutions that exist. For nonpolynomial equations,
returns the first numeric solution found.
General form allows insight into the solution. Numeric solutions provide less insight.
Runs slower. Runs faster.
Search ranges can be specified using inequalities. Search ranges and starting points can be
specified.
solve solves equations and inequalities that vpasolve does not solve inequalities, nor does it
contain parameters. solve equations that contain parameters.
solve can return parameterized solutions. vpasolve does not return parameterized
solutions.
vpasolve uses variable-precision arithmetic. You can control precision arbitrarily using digits. For
examples, see “Increase Precision of Numeric Calculations” on page 2-36.
See Also
solve | vpasolve
Related Examples
• “Solve Algebraic Equations” on page 3-3
• “Solve Equations Numerically” on page 3-21
• “Solve System of Linear Equations” on page 3-30
3-33
3 Mathematics
This example shows you how to solve parameterized algebraic equations using the Symbolic Math
Toolbox™.
To solve algebraic equations symbolically, use the solve function. The solve function can provide
complete information about all solutions of an equation, even if there are infinitely many, by
introducing a parameterization. It can also provide information under which conditions these
solutions are valid. To obtain this information, set the option ReturnConditions to true.
Solve the equation sin(C*x) = 1. Specify x as the variable to solve for. The solve function handles
C as a constant. Provide three output variables for the solution, the newly generated parameters in
the solution, and the conditions on the solution.
syms C x
eq = sin(C*x) == 1;
[solx, params, conds] = solve(eq, x, 'ReturnConditions', true)
solx =
π
2
+2πk
C
params = k
conds = k ∈ ℤ ∧ C ≠ 0
To verify the solution, substitute the solution into the equation using subs. To work on under the
assumptions in conds for the rest of this example, use assume. Test the solution using isAlways.
The isAlways function returns logical 1 (true) indicating that the solution always holds under the
given assumptions.
SolutionCorrect =
π
sin + 2 π k = 1
2
assume(conds)
isAlways(SolutionCorrect)
ans = logical
1
To obtain one solution out of the infinitely many solutions, find a value of the parameters params by
solving the conditions conds for the parameters; do not specify the ReturnConditions option.
Substitute this value of k into the solution using subs to obtain a solution out of the solution set.
k0 = solve(conds, params)
k0 = 0
ans =
3-34
Solve Parametric Equations in ReturnConditions Mode
π
2C
To obtain a parameter value that satisfies a certain condition, add the condition to the input to solve.
Find a value of the parameter greater than 99/4 and substitute in to find the solution.
k1 = 26
ans =
105 π
2C
To find a solution in a specified interval, you can solve the original equation with the inequalities that
specify the interval.
solx1 =
π+4πk
2C
params1 = k
Alternatively, you can also use the existing solution, and restrict it with additional conditions. Note
that while the condition changes, the solution remains the same. The solve function expresses solx
and solx1 with different parameterizations, although they are equivalent.
conds2 =
4 4k+1 4k+1 14
< ∧ <
π C C π
Obtain those parameter values that satisfy the new condition, for a particular value of the constant C:
conds3 = subs(conds2, C, 5)
conds3 =
4 4k 1 4k 1 14
< + ∧ + <
π 5 5 5 5 π
solve(conds3, params)
ans =
2
3
4
5
3-35
3 Mathematics
Starting in R2020a, you can interactively solve algebraic equations to obtain symbolic solutions using
the Solve Symbolic Equation task in the Live Editor. For more information on Live Editor tasks, see
“Add Interactive Tasks to a Live Script”.
• a trigonometric equation
• a cubic equation
• a system of cubic and linear equations
Find the solution of the trigonometric equation sin(x) + cos(x) = 0 with the assumption that x > π/2.
First, go to the Home tab, and create a live script by clicking New Live Script. Define the
symbolic variable x, and use the == operator to declare the equality sign of the trigonometric
equation. Use assume to set the assumption on x.
syms x
eqn = sin(x) + cos(x) == 0;
assume(x > pi/2);
In the Live Editor tab, run the code by clicking Run to store x with its assumption and eqn into
the current workspace.
Next, open the Solve Symbolic Equation task by selecting Task > Solve Symbolic Equation in the
Live Editor tab. To find the solution of the trigonometric equation, select the symbolic equation eqn
from the workspace. Specify x as the variable to solve for. Select the Return conditions option to
return the general solution and the analytic constraints under which it holds.
3-36
Solve Algebraic Equation Using Live Editor Task
You can ignore the assumption on x by selecting the Ignore properties option. Return the solution
without using the assumption that x > π/2.
3-37
3 Mathematics
To experiment with solving symbolic equations, you can repeat the previous steps for other system
equations and solver options. You can run the following examples by adding the code to the existing
live script or a new live script.
Define the symbolic variables x and y using syms, and use the == operator to declare the equality
sign of the cubic equation.
syms x y
cubicEquation = x^3 - 2*x^2 + y == 0;
To find the solutions of the cubic equation, select the symbolic equation cubicEquation from the
workspace. Specify x as the variable to solve for.
The solver returns the symbolic solutions in terms of the root function. To express the root function
in terms of square roots, select the Expand all roots option.
3-38
Solve Algebraic Equation Using Live Editor Task
x3 − 2x2 + y = 0
y = 4x − 8
Define the symbolic variables x and y using syms. Use the == operator to declare the equality sign of
the equations. To declare the system of equations, combine the two symbolic equations into an array.
syms x y
cubicEquation = x^3 - 2*x^2 + y == 0;
linearEquation = y == 4*x - 8;
systemEquations = [cubicEquation linearEquation];
To find the solution of the system of equations, select the symbolic equation systemEquations from
the workspace. Specify x and y as the variables to solve for.
3-39
3 Mathematics
The solver returns real and complex solutions. To show real solutions only, select the Return real
solutions option.
3-40
Solve Algebraic Equation Using Live Editor Task
Generate Code
To view the code that a task used, click at the bottom of the task window. The task displays the
code block, which you can cut and paste to use or modify later in the existing script or a different
program. For example:
Because the underlying code is now part of your live script, you can continue to use the solutions
generated by the task for further processing. For example, you can plot the system of equations and
their real-valued solution.
3-41
3 Mathematics
See Also
Live Editor Tasks
Simplify Symbolic Expression | Solve Symbolic Equation
Functions
solve
Related Examples
• “Add Interactive Tasks to a Live Script”
• “Solve Algebraic Equations” on page 3-3
3-42
Solve Differential Equation
Solve a differential equation analytically by using the dsolve function, with or without initial
conditions. To solve a system of differential equations, see “Solve a System of Differential Equations”
on page 3-47.
In this section...
“First-Order Linear ODE” on page 3-43
“Solve Differential Equation with Condition” on page 3-43
“Nonlinear Differential Equation with Initial Condition” on page 3-44
“Second-Order ODE with Initial Conditions” on page 3-44
“Third-Order ODE with Initial Conditions” on page 3-44
“More ODE Examples” on page 3-45
dy
= ty .
dt
syms y(t)
Define the equation using == and represent differentiation using the diff function.
ode(t) =
diff(y(t), t) == t*y(t)
ySol(t) = dsolve(ode)
ySol(t) =
C1*exp(t^2/2)
cond = y(0) == 2;
ySol(t) = dsolve(ode,cond)
ySol(t) =
2*exp(t^2/2)
3-43
3 Mathematics
If dsolve cannot solve your equation, then try solving the equation numerically. See “Solve a Second-
Order Differential Equation Numerically” on page 3-52.
dy 2
+ y = 1,
dt
y 0 = 0.
syms y(t)
ode = (diff(y,t)+y)^2 == 1;
cond = y(0) == 0;
ySol(t) = dsolve(ode,cond)
ySol(t) =
exp(-t) - 1
1 - exp(-t)
Define the equation and conditions. The second initial condition involves the first derivative of y.
Represent the derivative by creating the symbolic function Dy = diff(y) and then define the
condition using Dy(0)==0.
syms y(x)
Dy = diff(y);
Solve ode for y. Simplify the solution using the simplify function.
ySol(x) =
1 - (8*sin(x/2)^4)/3
3-44
Solve Differential Equation
3
d u
= u,
dx3
u(0) = 1,
u′(0) = − 1,
u′′(0) = π .
Because the initial conditions contain the first- and second-order derivatives, create two symbolic
functions, Du = diff(u,x) and D2u = diff(u,x,2), to specify the initial conditions.
syms u(x)
Du = diff(u,x);
D2u = diff(u,x,2);
ode = diff(u,x,3) == u;
cond1 = u(0) == 1;
cond2 = Du(0) == -1;
cond3 = D2u(0) == pi;
conds = [cond1 cond2 cond3];
uSol(x) = dsolve(ode,conds)
uSol(x) =
ySol(t) =
exp(-t)/3 + (2*exp(-4*t))/3
2
d y dy syms y(x)
2x2 + 3x − y = 0. ode = 2*x^2*diff(y,x,2)+3*x*diff(y,x)-y == 0;
dx2 dx
ySol(x) = dsolve(ode)
ySol(x) =
C1/(3*x) + C2*x^(1/2)
The Airy equation. syms y(x)
ode = diff(y,x,2) == x*y;
2 ySol(x) = dsolve(ode)
d y
= xy(x) .
dx2 ySol(x) =
C1*airy(0,x) + C2*airy(2,x)
3-45
3 Mathematics
ySol(x) =
- (a*x^5)/120 - (5*x^4)/24 + (a*x^3)/6 - (5*x^2)/2 + a*x + 5
See Also
dsolve | odeFunction | odeToVectorField | reduceDifferentialOrder | daeFunction
Related Examples
• “Solve a System of Differential Equations” on page 3-47
• “Solve a Second-Order Differential Equation Numerically” on page 3-52
• “Solve Differential Algebraic Equations (DAEs)” on page 3-61
3-46
Solve a System of Differential Equations
Solve a system of several ordinary differential equations in several variables by using the dsolve
function, with or without initial conditions. To solve a single differential equation, see “Solve
Differential Equation” on page 3-43.
du
= 3u + 4v,
dt
dv
= − 4u + 3v .
dt
First, represent u and v by using syms to create the symbolic functions u(t) and v(t).
syms u(t) v(t)
Define the equations using == and represent differentiation using the diff function.
ode1 = diff(u) == 3*u + 4*v;
ode2 = diff(v) == -4*u + 3*v;
odes = [ode1; ode2]
odes(t) =
∂
u t = 3u t +4v t
∂t
∂
v t = 3v t −4u t
∂t
Solve the system using the dsolve function which returns the solutions as elements of a structure.
S = dsolve(odes)
If dsolve cannot solve your equation, then try solving the equation numerically. See “Solve a Second-
Order Differential Equation Numerically” on page 3-52.
vSol(t) = S.v
Alternatively, store u(t) and v(t) directly by providing multiple output arguments.
[uSol(t),vSol(t)] = dsolve(odes)
3-47
3 Mathematics
The constants C1 and C2 appear because no conditions are specified. Solve the system with the initial
conditions u(0) == 0 and v(0) == 0. The dsolve function finds values for the constants that
satisfy these conditions.
cond1 = u(0) == 0;
cond2 = v(0) == 1;
conds = [cond1; cond2];
[uSol(t),vSol(t)] = dsolve(odes,conds)
uSol(t) = sin 4 t e3 t
vSol(t) = cos 4 t e3 t
fplot(uSol)
hold on
fplot(vSol)
grid on
legend('uSol','vSol','Location','best')
3-48
Solve a System of Differential Equations
dx
= x + 2y + 1,
dt
dy
= −x+ y +t.
dt
x′ 1 2 x 1
= + .
y′ −1 1 y t
Let
x 1 2 1
Y= ,A= ,B = .
y −1 1 t
odes(t) =
∂
x t =x t +2y t +1
∂t
∂
y t =t−x t +y t
∂t
Solve the matrix equation using dsolve. Simplify the solution by using the simplify function.
[xSol(t),ySol(t)] = dsolve(odes);
xSol(t) = simplify(xSol(t))
xSol(t) =
2t 1
+ 2 C2 et cos 2 t + 2 C1 et sin 2 t +
3 9
ySol(t) = simplify(ySol(t))
ySol(t) =
t 2
C1 et cos 2 t − − C2 et sin 2 t −
3 9
Solve the system with the initial conditions u(0) = 2 and v(0) = − 1. When specifying equations in
matrix form, you must specify initial conditions in matrix form too. dsolve finds values for the
constants that satisfy these conditions.
3-49
3 Mathematics
C = Y(0) == [2;-1];
[xSol(t),ySol(t)] = dsolve(odes,C)
xSol(t) =
−t 4 σ + 2 σ + 6 t σ + 6 2 t σ e−t 4 σ2 − 2 σ1 + 6 t σ2 − 6 2 t σ1
17 2 e 1 2 1 2 7
2 et σ2 + − 2 et σ1 +
18 18 18 9
where
σ1 = sin 2 t
σ2 = cos 2 t
ySol(t) =
−t 4 σ + 2 σ + 6 t σ + 6 2 t σ e−t 4 σ2 − 2 σ1 + 6 t σ2 − 6 2 t σ1
17 2 e 1 2 1 2 7
− et σ1 + − et σ2 +
18 18 18 9
where
σ1 = sin 2 t
σ2 = cos 2 t
clf
fplot(ySol)
hold on
fplot(xSol)
grid on
legend('ySol','xSol','Location','best')
3-50
Solve a System of Differential Equations
See Also
“Solve Differential Equation” on page 3-43
3-51
3 Mathematics
This example shows you how to convert a second-order differential equation into a system of
differential equations that can be solved using the numerical solver ode45 of MATLAB®.
2
d y dy
= (1 − y2) −y
dt 2 dt
dy
using a change of variables. Let y(t) = Y 1and = Y 2 such that differentiating both equations we
dt
obtain a system of first-order differential equations.
dY 1
= Y2
dt
dY 2
= − (Y 12 − 1)Y 2 − Y 1
dt
syms y(t)
[V] = odeToVectorField(diff(y, 2) == (1 - y^2)*diff(y) - y)
V =
Y2
− Y 12 − 1 Y 2 − Y 1
The MATLAB ODE solvers do not accept symbolic expressions as an input. Therefore, before you can
use a MATLAB ODE solver to solve the system, you must convert that system to a MATLAB function.
Generate a MATLAB function from this system of first-order differential equations using
matlabFunction with V as an input.
M = matlabFunction(V,'vars', {'t','Y'})
To solve this system, call the MATLAB ode45 numerical solver using the generated MATLAB function
as an input.
3-52
Solve a Second-Order Differential Equation Numerically
Plot the solution using linspace to generate 100 points in the interval [0,20] and deval to evaluate
the solution for each point.
See Also
dsolve | matlabFunction | ode45 | odeToVectorField
3-53
3 Mathematics
This example simulates a tsunami wave phenomenon by solving the partial differential equations that
model the tsunami.
This simulation is a simplified visualization of the phenomenon, and is based on a paper by Goring
and Raichlen [1].
A solitary wave (a soliton solution of the Korteweg-de Vries equation) travels at a constant speed from
the right to the left along a canal of constant depth. This corresponds to a tsunami traveling over
deep sea. At the left end of the canal, there is a slope simulating the continental shelf. After reaching
the slope, the solitary wave begins to increase its height. When the water becomes very shallow, most
of the wave is reflected back into the canal. However, a narrow but high peak of water arises at the
end of the slope and proceeds with reduced speed in the original direction of the incident wave. This
is the tsunami that finally hits the shore, causing disastrous destruction along the coastline. The
speed of the wave nearing the shore is comparatively small. The wave eventually starts to break.
3-54
Solve Partial Differential Equation of Tsunami Model
Using linear dispersionless water theory, the height u(x, t) of a free surface wave above the
undisturbed water level in a one-dimensional canal of varying depth h(x) is the solution of the
following partial differential equation. (See [2].)
utt = g (h ux)x
In this formula, subscripts denote partial derivatives, and g = 9 . 81m/s2 is the gravitational
acceleration.
Consider a wave crossing a linear slope h(x) from a region with the constant depth h2 to a region with
the constant depth h1 ≪ h2. The Fourier transformation with respect to t turns the water wave partial
differential equation to the following ordinary differential equation for the Fourier mode
u(x, t) = U(x, ω) ei ω t.
−ω2 U = g (h Ux)x
For the regions with constant depth h, the Fourier modes are traveling waves propagating in opposite
directions with constant speed c = g h.
i ω (t + x/c2) i ω (t − x/c2)
The solution u2(x, t) = e + R(ω) e for the deep water region is the superposition of
two waves:
3-55
3 Mathematics
This choice of u2 satisfies the wave equation in the deep water region for any R(ω).
i ω(t + x/c1)
The solution u1(x, t) = T(ω) e for the shallow water region is a transmitted wave traveling to
the left with the constant speed c1 = g h1. This choice of u1 satisfies the wave equation in the
shallow water region for any transmission coefficient T(ω).
Define the parameters of the tsunami model as follows. Disregard the dependency on the frequency ω
in the following notations: R = R(ω), T = T(ω), U(x) = U(x, ω).
L1 = depthratio*L;
L2 = L;
h1 = depthratio*H;
h2 = H;
h(x) = x*H/L;
c1 = sqrt(g*h1);
c2 = sqrt(g*h2);
u(x,t) = U(x)*exp(1i*w*t);
u1(x,t) = T*exp(1i*w*(t + x/c1));
u2(x,t) = exp(1i*w*(t + x/c2)) + R*exp(1i*w*(t - x/c2));
In the transition region over the linear slope, use dsolve to solve the ODE for the Fourier transform
U of u.
The solution U is a complicated expression involving Bessel functions. It contains two arbitrary
"constants" that depend on ω.
Const = C1 C2
For any Fourier mode, the overall solution must be a continuously differentiable function of x. Hence,
the function values and the derivatives must match at the seam points L1 and L2. This provides four
linear equations for T , R, and the two constants in U.
du1(x) = diff(u1(x,0),x);
du2(x) = diff(u2(x,0),x);
dU(x) = diff(U(x),x);
3-56
Solve Partial Differential Equation of Tsunami Model
You cannot directly evaluate the solution for ω = 0 because both numerator and denominator of the
corresponding expressions vanish. Instead, find the low frequency limits of these expressions.
simplify(limit(U(x), w, 0))
ans =
2
depthratio + 1
simplify(limit(R, w, 0))
ans =
depthratio − 1
−
depthratio + 1
simplify(limit(T, w, 0))
ans =
2
depthratio + 1
These limits are remarkably simple. They only depend on the ratio of the depth values defining the
slope.
For the following computations, use these numerical values for the symbolic parameters.
g = 9.81;
L = 2;
H = 1;
depthratio = 0.04;
h1 = depthratio*H;
h2 = H;
L1 = depthratio*L;
L2 = L;
3-57
3 Mathematics
c1 = sqrt(g*h1);
c2 = sqrt(g*h2);
Define the incoming soliton of amplitude A traveling to the left with constant speed c2 in the deep
water region.
A = 0.3;
soliton = @(x,t) A.*sech(sqrt(3/4*g*A/H)*(x/c2+t)).^2;
Choose Nt sample points for t. The time scale is chosen as a multiple of the (temporal) width of the
incoming soliton. Store the corresponding discretized frequencies of the Fourier transform in W .
Nt = 64;
TimeScale = 40*sqrt(4/3*H/A/g);
W = [0, 1:Nt/2 - 1, -(Nt/2 - 1):-1]'*2*pi/TimeScale;
Choose Nx sample points in x direction for each region. Create sample points X1 for the shallow
water region, X2 for the deep water region, and X12 for the slope region.
Nx = 100;
x_min = L1 - 4;
x_max = L2 + 12;
X12 = linspace(L1, L2, Nx);
X1 = linspace(x_min, L1, Nx);
X2 = linspace(L2, x_max, Nx);
Compute the Fourier transform of the incoming soliton on a time grid of Nt equidistant sample
points.
S = fft(soliton(-0.8*TimeScale*c2, linspace(0,TimeScale,2*(Nt/2)-1)))';
S = repmat(S,1,Nx);
Construct a traveling wave solution in the deep water region based on the Fourier data in S.
Convert the Fourier modes of the reflected wave in the deep water region to numerical values over a
grid in (x, ω) space. Multiply these values with the Fourier coefficients in S and use the function ifft
to compute the reflected wave in (x, t) space. Note that the first row of the numeric data R consists of
NaN values because proper numerical evaluation of the symbolic data R for ω = 0 is not possible.
Define the values in the first row of R as the low frequency limits.
Use the same approach for the transmitted wave in the shallow water region.
T = double(subs(subs(vpa(subs(T)),w,W),x,X1));
T(1,:) = double(2/(1+sqrt(depthratio)));
transmittedWave = real(ifft(S .* T .* exp(1i*W*X1/c1)));
U12 = double(subs(subs(vpa(subs(U(x))),w,W),x,X12));
U12(1,:) = double(2/(1+sqrt(depthratio)));
U12 = real(ifft(S .* U12));
3-58
Solve Partial Differential Equation of Tsunami Model
For a smoother animation, generate additional sample points using trigonometric interpolation along
the columns of the plot data.
Create an animated plot of the solution that shows-up in a separate figure window.
figure('Visible', 'on');
plot([x_min, L1, L2, x_max], [-h1, -h1, -h2, -h2], 'Color', 'black')
axis([x_min, x_max, -H-0.1, 0.6])
hold on
3-59
3 Mathematics
In real life, tsunamis have a wavelength of hundreds of kilometers, often traveling at speeds of more
than 500 km/hour. (Note that the average depth of the ocean is about 4 km, corresponding to a speed
of g h ≈ 700 km/hour.) Over deep sea, the amplitude is rather small, often about 0.5 m or less.
When propagating onto the shelf, however, tsunamis increase their height dramatically: amplitudes of
up to 30 m and more were reported.
One interesting phenomenon is that although tsunamis typically approach the coastline as a wave
front extending for hundreds of kilometers perpendicular to the direction in which they travel, they
do not cause uniform damage along the coast. At some points they cause disasters, whereas only
moderate wave phenomena are observed at other places. This is caused by different slopes from the
sea bed to the continental shelf. In fact, very steep slopes cause most of the tsunami to be reflected
back into the region of deep water, whereas small slopes reflect less of the wave, transmitting a
narrow but high wave carrying much energy.
Run the simulation for different values of L, which correspond to different slopes. The steeper the
slope, the lower and less powerful the wave that is transmitted.
Note that this model ignores the dispersion and friction effects. On the shelf, the simulation loses its
physical meaning. Here, friction effects are important, causing breaking of the waves.
References
[1] Derek G. Goring and F. Raichlen, Tsunamis - The Propagation of Long Waves onto a Shelf, Journal
of Waterway, Port, Coastal and Ocean Engineering 118(1), 1992, pp. 41 - 63.
See Also
Functions
diff | dsolve | solve | subs
3-60
Solve Differential Algebraic Equations (DAEs)
This example show how to solve differential algebraic equations (DAEs) by using MATLAB® and
Symbolic Math Toolbox™.
where t is the independent variable. The number of equations F = F1, . . . , Fn must match the
number of state variables x t = x1 t , . . . , xn t .
Because most DAE systems are not suitable for direct input to MATLAB solvers, such as ode15i, first
convert them to a suitable form by using Symbolic Math Toolbox functionality. This functionality
reduces the differential index (number of differentiations needed to reduce the system to ODEs) of
the DAEs to 1 or 0, and then converts the DAE system to numeric function handles suitable for
MATLAB solvers. Then, use MATLAB solvers, such as ode15i, ode15s, or ode23t, to solve the DAEs.
The following figure shows the DAE workflow by solving the DAEs for a pendulum.
3-61
3 Mathematics
• Pendulum mass m
• Pendulum length r
• Gravitational constant g
2
d x xt
m =T t
dt 2 r
2
d y yt
m =T t − mg
dt 2 r
2 2
xt +y t = r2
Place the state variables in a column vector. Store the number of original variables for reference.
This step is optional. You can check where variables occur in the DAE system by viewing the
incidence matrix. This step finds any variables that do not occur in your input and can be removed
from the vars vector.
Display the incidence matrix by using incidenceMatrix. The output of incidenceMatrix has a
row for each equation and a column for each variable. Because the system has three equations and
three state variables, incidenceMatrix returns a 3-by-3 matrix. The matrix has 1s and 0s, where 1s
represent the occurrence of a state variable. For example, the 1 in position (2,3) means the second
equation contains the third state variable T(t).
M = incidenceMatrix(eqns,vars)
M = 3×3
1 0 1
3-62
Solve Differential Algebraic Equations (DAEs)
0 1 1
1 1 0
If a column of the incidence matrix is all 0s, then that state variable does not occur in the DAE system
and should be removed.
The differential order of a DAE system is the highest differential order of its equations. To solve DAEs
using MATLAB, the differential order must be reduced to 1. Here, the first and second equations have
second-order derivatives of x(t) and y(t). Thus, the differential order is 2.
eqns =
∂ T t xt
mDxt t −
∂t r
∂ T t yt
gm+m Dyt t −
∂t r
2 2
−r 2 + x t+y t
∂
Dxt t − xt
∂t
∂
Dyt t − yt
∂t
vars =
xt
yt
T t
Dxt t
Dyt t
Check the differential index of the DAE system by using isLowIndexDAE. If the index is 0 or 1, then
isLowIndexDAE returns logical 1 (true) and you can skip step 3.2 and go to Step 4. Convert DAE
Systems to MATLAB Function Handles. Here, isLowIndexDAE returns logical 0 (false), which
means the differential index is greater than 1 and must be reduced.
isLowIndexDAE(eqns,vars)
ans = logical
0
To reduce the differential index, the reduceDAEIndex function adds new equations that are derived
from the input equations, and then replaces higher-order derivatives with new variables. If
3-63
3 Mathematics
reduceDAEIndex fails and issues a warning, then use the alternative function reduceDAEToODE as
described in the workflow “Solve Semilinear DAE System” on page 3-70.
Reduce the differential index of the DAEs described by eqns and vars.
[DAEs,DAEvars] = reduceDAEIndex(eqns,vars)
DAEs =
T t xt
m Dxtt t −
r
T t yt
g m + m Dytt t −
r
2 2
−r 2 + x t + y t
Dxt t − Dxt1 t
Dyt t − Dyt1 t
2 Dxt1 t x t + 2 Dyt1 t y t
∂ 2 2
2y t Dyt1 t + 2 Dxt1 t + 2 Dyt1 t + 2 Dxt1t t x t
∂t
Dxtt t − Dxt1t t
∂
Dytt t − Dyt1 t
∂t
∂
Dyt1 t − yt
∂t
DAEvars =
xt
yt
T t
Dxt t
Dyt t
Dytt t
Dxtt t
Dxt1 t
Dyt1 t
Dxt1t t
If reduceDAEIndex issues an error or a warning, use the alternative workflow described in “Solve
Semilinear DAE System” on page 3-70.
Often, reduceDAEIndex introduces redundant equations and variables that can be eliminated.
Eliminate redundant equations and variables using reduceRedundancies.
[DAEs,DAEvars] = reduceRedundancies(DAEs,DAEvars)
DAEs =
3-64
Solve Differential Algebraic Equations (DAEs)
T t x t − m r Dxtt t
−
r
g m r − T t y t + m r Dytt t
r
2 2
−r 2 + x t + y t
2 Dxt t x t + 2 Dyt t y t
2 2
2 Dxt t + 2 Dyt t + 2 Dxtt t x t + 2 Dytt t y t
∂
Dytt t − Dyt t
∂t
∂
Dyt t − yt
∂t
DAEvars =
xt
yt
T t
Dxt t
Dyt t
Dytt t
Dxtt t
Check the differential index of the new system. Now, isLowIndexDAE returns logical 1 (true), which
means that the differential index of the system is 0 or 1.
isLowIndexDAE(DAEs,DAEvars)
ans = logical
1
This step creates function handles for the MATLAB ODE solver ode15i, which is a general purpose
solver. To use specialized mass matrix solvers such as ode15s and ode23t, see “Solve DAEs Using
Mass Matrix Solvers” on page 3-77 and “Choose an ODE Solver”.
reduceDAEIndex outputs a vector of equations in DAEs and a vector of variables in DAEvars. To use
ode15i, you need a function handle that describes the DAE system.
First, the equations in DAEs can contain symbolic parameters that are not specified in the vector of
variables DAEvars. Find these parameters by using setdiff on the output of symvar from DAEs
and DAEvars.
pDAEs = symvar(DAEs);
pDAEvars = symvar(DAEvars);
extraParams = setdiff(pDAEs,pDAEvars)
extraParams = g m r
The extra parameters that you need to specify are the mass m, radius r, and gravitational constant g.
Create the function handle by using daeFunction. Specify the extra symbolic parameters as
additional input arguments of daeFunction.
f = daeFunction(DAEs,DAEvars,g,m,r);
3-65
3 Mathematics
The rest of the workflow is purely numerical. Set the parameter values and create the function handle
for ode15i.
g = 9.81;
m = 1;
r = 1;
F = @(t,Y,YP) f(t,Y,YP,g,m,r);
The ode15i solver requires initial values for all variables in the function handle. Find initial values
that satisfy the equations by using the MATLAB decic function. decic accepts guesses (which might
not satisfy the equations) for the initial conditions and tries to find satisfactory initial conditions using
those guesses. decic can fail, in which case you must manually supply consistent initial values for
your problem.
DAEvars
DAEvars =
xt
yt
T t
Dxt t
Dyt t
Dytt t
Dxtt t
Here, Dxt(t) is the first derivative of x(t), Dytt(t) is the second derivative of y(t), and so on.
There are 7 variables in a 7-by-1 vector. Therefore, guesses for initial values of variables and their
derivatives must also be 7-by-1 vectors.
Assume the initial angular displacement of the pendulum is 30° or pi/6, and the origin of the
coordinates is at the suspension point of the pendulum. Given that we used a radius r of 1, the initial
horizontal position x(t) is r*sin(pi/6). The initial vertical position y(t) is -r*cos(pi/6).
Specify these initial values of the variables in the vector y0est.
Arbitrarily set the initial values of the remaining variables and their derivatives to 0. These are not
good guesses. However, they suffice for this problem. In your problem, if decic errors, then provide
better guesses and refer to decic.
Create an option set that specifies numerical tolerances for the numerical search.
Find consistent initial values for the variables and their derivatives by using decic.
[y0,yp0] = decic(F,0,y0est,[],yp0est,[],opt)
y0 = 7×1
3-66
Solve Differential Algebraic Equations (DAEs)
0.4771
-0.8788
-8.6214
0
0.0000
-2.2333
-4.1135
yp0 = 7×1
0
0.0000
0
0
-2.2333
0
0
Solve the system integrating over the time span 0 ≤ t ≤ 0.5. Add the grid lines and the legend to the
plot.
for k = 1:origVars
S{k} = char(DAEvars(k));
end
legend(S,'Location','Best')
grid on
3-67
3 Mathematics
Solve the system for different parameter values by setting the new value and regenerating the
function handle and initial conditions.
r = 2;
F = @(t,Y,YP)f(t,Y,YP,g,m,r);
for k = 1:origVars
S{k} = char(DAEvars(k));
end
legend(S,'Location','Best')
grid on
3-68
Solve Differential Algebraic Equations (DAEs)
See Also
Related Examples
• “Solve Semilinear DAE System” on page 3-70
• “Solve DAEs Using Mass Matrix Solvers” on page 3-77
3-69
3 Mathematics
This workflow is an alternative workflow to solving semilinear differential algebraic equations (DAEs),
used only if reduceDAEIndex failed in the standard workflow with the warning message: The
index of the reduced DAEs is larger than 1. [daetools::reduceDAEIndex]. For the
standard workflow, see “Solve Differential Algebraic Equations (DAEs)” on page 3-61.
Complete steps 1 and 2 in “Solve Differential Algebraic Equations (DAEs)” on page 3-61 before
beginning other steps. Then, in step 3, if reduceDAEIndex fails, reduce the differential index using
reduceDAEToODE. The advantage of reduceDAEToODE is that it reliably reduces semilinear DAEs to
ODEs (DAEs of index 0). However, this function is slower and works only on semilinear DAE systems.
reduceDAEToODE can fail if the system is not semilinear.
2
d x xt
m =T t
dt 2 r
2
d y yt
m =T t − mg
dt2 r
2 2
xt +y t = r2
Place the state variables in a column vector. Store the number of original variables for reference.
The differential order of a DAE system is the highest differential order of its equations. To solve DAEs
using MATLAB®, the differential order must be reduced to 1. Here, the first and second equations
have second-order derivatives of x(t) and y(t). Thus, the differential order is 2.
[eqns,vars] = reduceDifferentialOrder(eqns,vars)
3-70
Solve Semilinear DAE System
eqns =
∂ T t xt
m Dxt t −
∂t r
∂ T t yt
gm+m Dyt t −
∂t r
2 2
−r 2 + x t+y t
∂
Dxt t − xt
∂t
∂
Dyt t − yt
∂t
vars =
xt
yt
T t
Dxt t
Dyt t
To reduce the differential index of the DAEs described by eqns and vars, use reduceDAEToODE. To
reduce the index, reduceDAEToODE adds new variables and equations to the system.
reduceDAEToODE also returns constraints, which are conditions that help find initial values to ensure
that the resulting ODEs are equal to the initial DAEs.
[ODEs,constraints] = reduceDAEToODE(eqns,vars)
ODEs =
∂
xt Dxt t −
∂t
∂
Dyt t − yt
∂t
∂ T t xt
m Dxt t −
∂t r
∂ T t y t −gmr
m Dyt t −
∂t r
∂ 2 2 ∂ ∂ ∂ ∂
− 4T t y t −2gmr y t − 2x t +2y t T t −4T t x t x t − 4 m r Dxt t Dxt t − 4 m r Dyt t Dyt
∂t ∂t ∂t ∂t ∂t
constraints =
2 2 2 2
−2 m r Dxt t − 2 m r Dyt t −2T t x t −2T t y t +2gmr y t
2 2
r2 − x t − y t
2 Dxt t x t + 2 Dyt t y t
3-71
3 Mathematics
From the output of reduceDAEToODE, you have a vector of equations in ODEs and a vector of
variables in vars. To use ode15s or ode23t, you need two function handles: one representing the
mass matrix of the ODE system, and the other representing the vector containing the right sides of
the mass matrix equations. These function handles are the equivalent mass matrix representation of
the ODE system where M(t,y(t))y’(t) = f(t,y(t)).
Find these function handles by using massMatrixForm to get the mass matrix massM (M in the
equation) and right sides f.
[massM,f] = massMatrixForm(ODEs,vars)
massM =
−1 0 0 0 0
0 −1 0 0 0
0 0 0 m 0
0 0 0 0 m
2 2
−4 T t x t 2 g m r − 4 T t y t −2 x t −2y t −4 m r Dxt t −4 m r Dyt t
f =
−Dxt t
−Dyt t
T t xt
r
T t y t −gmr
r
0
The equations in ODEs can contain symbolic parameters that are not specified in the vector of
variables vars. Find these parameters by using setdiff on the output of symvar from ODEs and
vars.
pODEs = symvar(ODEs);
pvars = symvar(vars);
extraParams = setdiff(pODEs, pvars)
extraParams = g m r
The extra parameters that you need to specify are the mass m, radius r, and gravitational constant g.
Convert massM and f to function handles using odeFunction. Specify the extra symbolic parameters
as additional inputs to odeFunction.
The rest of the workflow is purely numerical. Set the parameter values and substitute the parameter
values in DAEs and constraints.
m = 1;
r = 1;
g = 9.81;
ODEsNumeric = subs(ODEs);
constraintsNumeric = subs(constraints);
3-72
Solve Semilinear DAE System
M = @(t,Y) massM(t,Y,m,r,g);
F = @(t,Y) f(t,Y,m,r,g);
The solvers require initial values for all variables in the function handle. Find initial values that
satisfy the equations by using the MATLAB decic function. The decic accepts guesses (which might
not satisfy the equations) for the initial conditions and tries to find satisfactory initial conditions using
those guesses. decic can fail, in which case you must manually supply consistent initial values for
your problem.
vars
vars =
xt
yt
T t
Dxt t
Dyt t
Here, Dxt(t) is the first derivative of x(t), and so on. There are 5 variables in a 5-by-1 vector.
Therefore, guesses for initial values of variables and their derivatives must also be 5-by-1 vectors.
Assume the initial angular displacement of the pendulum is 30° or pi/6, and the origin of the
coordinates is at the suspension point of the pendulum. Given that we used a radius r of 1, the initial
horizontal position x(t) is r*sin(pi/6). The initial vertical position y(t) is -r*cos(pi/6).
Specify these initial values of the variables in the vector y0est.
Arbitrarily set the initial values of the remaining variables and their derivatives to 0. These are not
good guesses. However, they suffice for this problem. In your problem, if decic errors, then provide
better guesses and refer to the decic page.
Create an option set that contains the mass matrix M of the system and specifies numerical tolerances
for the numerical search.
Find initial values consistent with the system of ODEs and with the algebraic constraints by using
decic. The parameter [1,0,0,0,1] in this function call fixes the first and the last element in
y0est, so that decic does not change them during the numerical search. Here, this fixing is
necessary to ensure decic finds satisfactory initial conditions.
y0 = 5×1
0.5000
-0.8660
3-73
3 Mathematics
-8.4957
0
0
yp0 = 5×1
0
0
0
-4.2479
-2.4525
Now create an option set that contains the mass matrix M of the system and the vector yp0 of
consistent initial values for the derivatives. You will use this option set when solving the system.
Solve the system integrating over the time span 0 ≤ t ≤ 0.5. Add the grid lines and the legend to the
plot. Use ode23s by replacing ode15s with ode23s.
for k = 1:origVars
S{k} = char(vars(k));
end
3-74
Solve Semilinear DAE System
Solve the system for different parameter values by setting the new value and regenerating the
function handle and initial conditions.
ODEsNumeric = subs(ODEs);
constraintsNumeric = subs(constraints);
M = @(t,Y) massM(t,Y,m,r,g);
F = @(t,Y) f(t,Y,m,r,g);
for k = 1:origVars
S{k} = char(vars(k));
end
3-75
3 Mathematics
See Also
daeFunction | decic | findDecoupledBlocks | incidenceMatrix | isLowIndexDAE |
massMatrixForm | odeFunction | reduceDAEIndex | reduceDAEToODE |
reduceDifferentialOrder | reduceRedundancies
Related Examples
• “Solve Differential Algebraic Equations (DAEs)” on page 3-61
• “Solve DAEs Using Mass Matrix Solvers” on page 3-77
3-76
Solve DAEs Using Mass Matrix Solvers
This example demonstrates the use of ode15s or ode23t. For details on the other solvers, see
“Choose an ODE Solver” and adapt the workflow on this page.
In this section...
“Step 1. Convert DAEs to Function Handles” on page 3-77
“Step 2. Find Initial Conditions” on page 3-78
“Step 3. Solve DAE System” on page 3-79
Find these function handles by using massMatrixForm to get the mass matrix M and the right sides
F.
[M,f] = massMatrixForm(DAEs,DAEvars)
M =
[ 0, 0, 0, 0, 0, 0, 0]
[ 0, 0, 0, 0, 0, 0, 0]
[ 0, 0, 0, 0, 0, 0, 0]
[ 0, 0, 0, 0, 0, 0, 0]
[ 0, 0, 0, 0, 0, 0, 0]
[ 0, 0, 0, 0, -1, 0, 0]
[ 0, -1, 0, 0, 0, 0, 0]
f =
(T(t)*x(t) - m*r*Dxtt(t))/r
-(g*m*r - T(t)*y(t) + m*r*Dytt(t))/r
r^2 - y(t)^2 - x(t)^2
- 2*Dxt(t)*x(t) - 2*Dyt(t)*y(t)
- 2*Dxtt(t)*x(t) - 2*Dytt(t)*y(t) - 2*Dxt(t)^2 - 2*Dyt(t)^2
-Dytt(t)
-Dyt(t)
The equations in DAEs can contain symbolic parameters that are not specified in the vector of
variables DAEvars. Find these parameters by using setdiff on the output of symvar from DAEs
and DAEvars.
pDAEs = symvar(DAEs);
pDAEvars = symvar(DAEvars);
extraParams = setdiff(pDAEs, pDAEvars)
3-77
3 Mathematics
extraParams =
[ g, m, r]
The mass matrix M does not have these extra parameters. Therefore, convert M directly to a function
handle by using odeFunction.
M = odeFunction(M, DAEvars);
Convert f to a function handle. Specify the extra parameters as additional inputs to odeFunction.
The rest of the workflow is purely numerical. Set parameter values and create the function handle.
g = 9.81;
m = 1;
r = 1;
F = @(t, Y) f(t, Y, g, m, r);
DAEvars
DAEvars =
x(t)
y(t)
T(t)
Dxt(t)
Dyt(t)
Dytt(t)
Dxtt(t)
Here, Dxt(t) is the first derivative of x(t), Dytt(t) is the second derivative of y(t), and so on.
There are 7 variables in a 7-by-1 vector. Thus, guesses for initial values of variables and their
derivatives must also be 7-by-1 vectors.
Assume the initial angular displacement of the pendulum is 30° or pi/6, and the origin of the
coordinates is at the suspension point of the pendulum. Given that we used a radius r of 1, the initial
horizontal position x(t) is r*sin(pi/6). The initial vertical position y(t) is -r*cos(pi/6).
Specify these initial values of the variables in the vector y0est.
Arbitrarily set the initial values of the remaining variables and their derivatives to 0. These are not
good guesses. However, they suffice for our problem. In your problem, if decic errors, then provide
better guesses and refer to the decic page.
3-78
Solve DAEs Using Mass Matrix Solvers
Create an option set that contains the mass matrix M and initial guesses yp0est, and specifies
numerical tolerances for the numerical search.
Find consistent initial values for the variables and their derivatives by using the MATLAB decic
function. The first argument of decic must be a function handle describing the DAE as f(t,y,yp)
= f(t,y,y') = 0. In terms of M and F, this means f(t,y,yp) = M(t,y)*yp - F(t,y).
y0 =
0.4771
-0.8788
-8.6214
0
0.0000
-2.2333
-4.1135
yp0 =
0
0.0000
0
0
-2.2333
0
0
Now create an option set that contains the mass matrix M of the system and the vector yp0 of
consistent initial values for the derivatives. You will use this option set when solving the system.
for k = 1:origVars
S{k} = char(DAEvars(k));
end
3-79
3 Mathematics
Solve the system for different parameter values by setting the new value and regenerating the
function handle and initial conditions.
r = 2;
for k = 1:origVars
S{k} = char(DAEvars(k));
end
3-80
Solve DAEs Using Mass Matrix Solvers
See Also
Related Examples
• “Solve Differential Algebraic Equations (DAEs)” on page 3-61
• “Solve Semilinear DAE System” on page 3-70
3-81
3 Mathematics
This example shows how to solve differential algebraic equations (DAEs) of high differential index
using Symbolic Math Toolbox™.
Engineers often specify the behavior of their physical objects (mechanical systems, electrical devices,
and so on) by a mixture of differential equations and algebraic equations. MATLAB® provides special
numerical solvers, such as ode15i and ode15s, capable of integrating such DAEs -- provided that
their 'differential index' does not exceed 1.
This example shows the workflow from setting up the model as a system of differential equations with
algebraic constraints to the numerical simulation. The following Symbolic Math Toolbox functions are
used.
• daeFunction
• findDecoupledBlocks
• incidenceMatrix
• isOfLowDAEIndex
• reduceDifferentialOrder
• massMatrixForm
• reduceDAEIndex
• reduceDAEToODE
• reduceRedundancies
• sym/decic
Consider a 2-D physical pendulum, consisting of a mass m attached to the origin by a string of
constant length r. Only the gravitational acceleration g = 9.81 m/s^2 acts on the mass. The model
consists of second-order differential equation for the position (x(t), y(t)) of the mass with an
unknown force F(t) inside the string which serves for keeping the mass on the circle. The force is
directed along the string.
syms x(t) y(t) F(t) m g r
eqs = [m*diff(x(t), t, t) == F(t)/r*x(t);
m*diff(y(t), t, t) == F(t)/r*y(t) - m*g;
x(t)^2 + y(t)^2 == r^2]
eqs =
∂2 Ft xt
m xt =
∂t 2 r
2
∂ Ft yt
m yt = −gm
∂t2 r
2 2
xt +y t = r2
vars = x t y t F t
3-82
Analyze and Manipulate Differential Algebraic Equations
eqs =
∂ Ft xt
m Dxt t −
∂t r
∂ Ft yt
gm+m Dyt t −
∂t r
2 2
−r 2 + x t+y t
∂
Dxt t − xt
∂t
∂
Dyt t − yt
∂t
vars =
xt
yt
Ft
Dxt t
Dyt t
newVars =
∂
Dxt t xt
∂t
∂
Dyt t yt
∂t
Before you can use a numerical MATLAB solver, such as ode15i, you must follow these steps.
Assign numerical values to the symbolic parameters of the system: m = 1kg, g = 9.18m/s^2, and r
= 1m.
The function handle f is a suitable input for the numerical solver ode15i. The next step is to
compute consistent initial conditions. Use odeset to set numerical tolerances. Then use the MATLAB
decic function to compute consistent initial conditions y0, yp0 for the positions and the derivatives
at time t0 = 0.
3-83
3 Mathematics
y0 = 5×1
0.9777
-0.2100
0
0
0
yp0 = 5×1
0
0
0
0
-9.8100
ans = 5×1
10-16 ×
0
0
-0.3469
0
0
Now you can use ode15i to try solving the system. When you call ode15i, the integration stops
immediately and issues the following warnings.
For this example, ode15i issues these warnings multiple times. For readability, disable warnings by
using warning('off','all') before calling ode15i and then enable them again.
tfinal = 0.5;
s = warning('off','all');
ode15i(f, [t0, tfinal], y0, yp0, opt);
3-84
Analyze and Manipulate Differential Algebraic Equations
warning(s)
isLowIndexDAE(eqs, vars)
ans = logical
0
This result explains why ode15i cannot solve this system. This function requires the input DAE
system to be of differential index 0 or 1. Reduce the differential index by extending the model to an
equivalent larger DAE system that includes some hidden algebraic constraints.
eqs =
3-85
3 Mathematics
Ft xt
m Dxtt t −
r
Ft yt
g m + m Dytt t −
r
2 2
−r 2 + x t + y t
Dxt t − Dxt1 t
Dyt t − Dyt1 t
2 Dxt1 t x t + 2 Dyt1 t y t
∂ 2 2
2y t Dyt1 t + 2 Dxt1 t + 2 Dyt1 t + 2 Dxt1t t x t
∂t
Dxtt t − Dxt1t t
∂
Dytt t − Dyt1 t
∂t
∂
Dyt1 t − yt
∂t
vars =
xt
yt
Ft
Dxt t
Dyt t
Dytt t
Dxtt t
Dxt1 t
Dyt1 t
Dxt1t t
newVars =
∂
Dytt t Dyt t
∂t
∂
Dxtt t Dxt t
∂t
∂
Dxt1 t xt
∂t
∂
Dyt1 t yt
∂t
∂2
Dxt1t t xt
∂t2
index = 3
The fourth output shows that the differential index of the original model is three. Simplify the new
system.
eqs =
3-86
Analyze and Manipulate Differential Algebraic Equations
F t x t − m r Dxtt t
−
r
g m r − F t y t + m r Dytt t
r
2 2
−r 2 + x t + y t
2 Dxt t x t + 2 Dyt t y t
2 2
2 Dxt t + 2 Dyt t + 2 Dxtt t x t + 2 Dytt t y t
∂
Dytt t − Dyt t
∂t
∂
Dyt t − yt
∂t
vars =
xt
yt
Ft
Dxt t
Dyt t
Dytt t
Dxtt t
ans = logical
1
Generate a MATLAB function handle that replaces the symbolic parameters by numerical values.
F = daeFunction(eqs, vars, [m, g, r])
Compute consistent initial conditions for the index reduced by the MATLAB decic function. Here,
opt is the options structure that sets numerical tolerances. You already computed it using odeset.
[y0,yp0] = decic(f, t0, [0.98;-0.21; zeros(5,1)], [], zeros(7,1), [], opt)
3-87
3 Mathematics
y0 = 7×1
0.9779
-0.2093
-2.0528
-0.0000
0
-9.3804
-2.0074
yp0 = 7×1
0
0
0
0
-9.3804
0
0
3-88
Derive and Apply Inverse Kinematics to Two-Link Robot Arm
This example shows how to derive and apply inverse kinematics to a two-link robot arm by using
MATLAB® and Symbolic Math Toolbox™.
The example defines the joint parameters and end-effector locations symbolically, calculates and
visualizes the forward and inverse kinematics solutions, and finds the system Jacobian, which is
useful for simulating the motion of the robot arm.
Define the link lengths, joint angles and end-effector locations of the robots as symbolic variables.
syms L_1 L_2 theta_1 theta_2 XE YE
3-89
3 Mathematics
Define the X and Y coordinates of the end-effector as a function of the joint angles θ1 , θ2 .
∘ ∘ ∘ ∘
Specify the input values of the joint angles as 0 < θ1 < 90 and −180 < θ2 < 180 .
t1_degs_row = linspace(0,90,100);
t2_degs_row = linspace(-180,180,100);
[tt1_degs,tt2_degs] = meshgrid(t1_degs_row,t2_degs_row);
tt1_rads = deg2rad(tt1_degs);
tt2_rads = deg2rad(tt2_degs);
Calculate the X and Y coordinates using the MATLAB functions XE_MLF and YE_MLF, respectively.
X_mat = XE_MLF(L1,L2,tt1_rads,tt2_rads);
Y_mat = YE_MLF(L1,L2,tt1_rads,tt2_rads);
plot_XY_given_theta_2dof(tt1_degs,tt2_degs,X_mat,Y_mat,(L1+L2))
3-90
Derive and Apply Inverse Kinematics to Two-Link Robot Arm
XE_EQ = XE == XE_RHS;
YE_EQ = YE == YE_RHS;
The structure S represents the multiple solutions for θ1 and θ2. Show the pair of solutions for θ1.
simplify(S.theta_1)
ans =
3-91
3 Mathematics
2 L1 YE + σ1
2 atan
L1 + 2 L1 XE − L22 + XE2 + YE2
2
2 L1 YE − σ1
2 atan
L1 + 2 L1 XE − L22 + XE2 + YE2
2
where
σ1 = −L14 + 2 L12 L22 + 2 L12 XE2 + 2 L12 YE2 − L24 + 2 L22 XE2 + 2 L22 YE2 − XE4 − 2 XE2 YE2 − YE4
simplify(S.theta_2)
ans =
−σ1
σ1
where
Convert the solutions into MATLAB functions that you can use later. The functions TH1_MLF and
TH2_MLF represent the inverse kinematics.
Use the inverse kinematics to compute θ1 and θ2 from the X and Y coordinates.
[xmat,ymat] = meshgrid(0:0.01:1.5,0:0.01:1.5);
Calculate the angles θ1 and θ2 using the MATLAB functions TH1_MLF{1} and TH2_MLF{1},
respectively.
tmp_th1_mat = TH1_MLF{1}(L1,L2,xmat,ymat);
tmp_th2_mat = TH2_MLF{1}(L1,L2,xmat,ymat);
tmp_th1_mat = rad2deg(tmp_th1_mat);
tmp_th2_mat = rad2deg(tmp_th2_mat);
Some of the input coordinates, such as (X,Y) = (1.5,1.5), are beyond the reachable workspace of the
end effector. The inverse kinematics solutions can generate some imaginary theta values that require
correction. Correct the imaginary theta values.
th1_mat = NaN(size(tmp_th1_mat));
th2_mat = NaN(size(tmp_th2_mat));
3-92
Derive and Apply Inverse Kinematics to Two-Link Robot Arm
tf_mat = imag(tmp_th1_mat) == 0;
th1_mat(tf_mat) = real(tmp_th1_mat(tf_mat));
tf_mat = imag(tmp_th2_mat) == 0;
th2_mat(tf_mat) = real(tmp_th2_mat(tf_mat));
plot_theta_given_XY_2dof(xmat,ymat,th1_mat,th2_mat)
dX dX
d(X, Y) dθ1 dθ2
J= =
d(θ1, θ2) dY dY
dθ1 dθ2
the_J =
−L2 sin θ1 + θ2 − L1 sin θ1 −L2 sin θ1 + θ2
L2 cos θ1 + θ2 + L1 cos θ1 L2 cos θ1 + θ2
3-93
3 Mathematics
You can relate the joint velocity to the end-effector velocity and the other way around, by using the
system Jacobian J and its Moore-Penrose pseudoinverse J +:
dX dX dX dθ1
dt dθ1 dθ2 dt
= .
dY dY dY dθ2
dt dθ1 dθ2 dt
dX dθ1
dt dt
= J.
dY dθ2
dt dt
dθ1 dX
dt + dt
= J .
dθ2 dY
dt dt
You can also convert the symbolic expression of the Jacobian to a MATLAB function block. Simulate
the end-effector locations of the robot on a trajectory by defining the multiple waypoints as inputs to
a Simulink® model. The Simulink model can calculate a motion-profile based on the joint angle
values to reach each waypoint in the trajectory. For more details, see Inverse Kinematics of a 2-link
Robot Arm and Teaching Rigid Body Dynamics.
Helper Functions
function plot_theta_given_XY_2dof(X_mat,Y_mat,theta_1_mat_degs,...
theta_2_mat_degs)
figure;
hax(1) = subplot(1,2,1);
contourf(X_mat, Y_mat, theta_1_mat_degs);
clim(hax(1), [-180 180]);
colormap(gca,'jet'); colorbar
xlabel(xlab_str, 'Interpreter', 'tex');
ylabel(ylab_str, 'Interpreter', 'tex');
title(hax(1), '\theta_1', 'Interpreter', 'tex')
axis('equal')
hax(2) = subplot(1,2,2);
contourf(X_mat, Y_mat, theta_2_mat_degs);
clim(hax(2), [-180 180]);
colormap(gca,'jet'); colorbar
xlabel(xlab_str, 'Interpreter', 'tex');
ylabel(ylab_str, 'Interpreter', 'tex');
title(hax(2), '\theta_2', 'Interpreter', 'tex')
axis('equal')
end
function plot_XY_given_theta_2dof(theta_1_mat_degs,theta_2_mat_degs,...
3-94
Derive and Apply Inverse Kinematics to Two-Link Robot Arm
X_mat,Y_mat,a_cmax)
figure;
hax(1) = subplot(1,2,1);
contourf(theta_1_mat_degs, theta_2_mat_degs, X_mat);
clim(hax(1), [0 a_cmax]);
colormap(gca,'jet'); colorbar
xlabel(xlab_str, 'Interpreter', 'tex');
ylabel(ylab_str, 'Interpreter', 'tex');
title(hax(1), 'X_E', 'Interpreter', 'tex')
hax(2) = subplot(1,2,2);
contourf(theta_1_mat_degs, theta_2_mat_degs, Y_mat);
clim(hax(1), [0 a_cmax]);
colormap(gca,'jet'); colorbar
xlabel(xlab_str, 'Interpreter', 'tex');
ylabel(ylab_str, 'Interpreter', 'tex');
title(hax(2), 'Y_E', 'Interpreter', 'tex')
end
See Also
Functions
matlabFunction | solve | simplify | jacobian
3-95
3 Mathematics
This example shows how to solve polynomial equations and systems of equations, and work with the
results using Symbolic Math Toolbox™.
n
∫
b
Gaussian quadrature rules approximate an integral by sums
a
f (t)w(t)dt ≈ ∑ f (xi)αi. Here, the xi
i=1
and αi are parameters of the method, depending on n but not on f . They follow from the choice of the
weight function w(t), as follows. Associated to the weight function is a family of orthogonal
polynomials. The polynomials' roots are the evaluation points xi. Finally, the weights αi are
determined by the condition that the method be correct for polynomials of small degree. Consider the
weight function w(t) = exp( − t) on the interval [0, ∞ ]. This case is known as Gauss-Laguerre
quadrature.
syms t
n = 4;
w(t) = exp(-t);
Assume you know the first n members of the family of orthogonal polynomials. In case of the
quadrature rule considered here, they turn out to be the Laguerre polynomials.
F = laguerreL(0:n-1, t)
F =
t2 t3 3 t2
1 1−t −2t+1 − + −3t+1
2 6 2
X = X1 X2 X3 X4 X5
L = poly2sym(X, t)
L = X1 t4 + X2 t3 + X3 t2 + X4 t + X5
Represent the orthogonality relations between the Laguerre polynomials F and L in a system of
equations sys.
3-96
Gauss-Laguerre Quadrature Evaluation Points and Weights
S = solve(sys, X)
solve returns the two solutions in a structure array. Display the solutions.
structfun(@display, S)
ans =
1
−
24
1
24
ans =
2
3
2
−
3
ans =
−3
3
ans =
4
−4
ans =
−1
1
Make the solution unique by imposing an extra condition that the first coefficient be positive:
L = subs(L, S)
L =
t4 2 t3
− + 3 t2 − 4 t + 1
24 3
3-97
3 Mathematics
laguerreL(n, t)
ans =
t4 2 t3
− + 3 t2 − 4 t + 1
24 3
The evaluation points xi are the roots of the polynomial L. Solve L for the evaluation points. The roots
are expressed in terms of the root function.
x = solve(L)
x =
root σ1, z, 1
root σ1, z, 2
root σ1, z, 3
root σ1, z, 4
where
σ1 = z4 − 16 z3 + 72 z2 − 96 z + 24
The form of the solutions might suggest that nothing has been achieved, but various operations are
available on them. Compute floating-point approximations using vpa:
vpa(x)
ans =
0.32254768961939231180036145910437
1.7457611011583465756868167125179
4.5366202969211279832792853849571
9.3950709123011331292335364434205
Some spurious imaginary parts might occur. Prove symbolically that the roots are real numbers:
isAlways(in(x, 'real'))
1
1
1
1
For polynomials of degree less than or equal to 4, you can use MaxDegree to obtain the solutions in
terms of nested radicals instead in terms of root. However, subsequent operations on results of this
form would be slow.
xradical =
3-98
Gauss-Laguerre Quadrature Evaluation Points and Weights
4 − σ1 − σ3
4 + σ1 − σ3
σ3 − σ2 + 4
σ3 + σ2 + 4
where
96 σ6 σ4 − 3 σ5 σ4 − 288 σ4 − 512 3 6 6 + 3 6 i
σ1 = 1/4
1/6
2 768 + 128 3 6 i 144 σ6 + 9 σ5 + 864
96 σ6 σ4 − 3 σ5 σ4 − 288 σ4 + 512 3 6 6 + 3 6 i
σ2 = 1/4
1/6
2 768 + 128 3 6 i 144 σ6 + 9 σ5 + 864
σ4
σ3 = 1/6
2 768 + 128 3 6 i
σ4 = 16 σ6 + σ5 + 96
2/3
σ5 = 768 + 128 3 6 i
1/3
σ6 = 768 + 128 3 6 i
The weights αi are given by the condition that for polynomials of degree less than n, the quadrature
rule must produce exact results. It is sufficient if this holds for a basis of the vector space of these
polynomials. This condition results in a system of four equations in four variables.
y = sym('y', [n, 1]);
sys = sym(zeros(n));
for k=0:n-1
sys(k+1) = sum(y.*(x.^k)) == int(t^k * w(t), t, 0, inf);
end
sys
sys =
y1 + y2 + y3 + y4 = 1 0 0 0
y1 root σ1, z, 1 + y2 root σ1, z, 2 + y3 root σ1, z, 3 + y4 root σ1, z, 4 = 1 0 0 0
2 2 2 2
y1 root σ1, z, 1 + y2 root σ1, z, 2 + y3 root σ1, z, 3 + y4 root σ1, z, 4 =2 0 0 0
3 3 3 3
y1 root σ1, z, 1 + y2 root σ1, z, 2 + y3 root σ1, z, 3 + y4 root σ1, z, 4 =6 0 0 0
where
σ1 = z4 − 16 z3 + 72 z2 − 96 z + 24
Solve the system both numerically and symbolically. The solution is the desired vector of weights αi.
a1 = 0.60315410434163360163596602381808
a2 = 0.35741869243779968664149201745809
a3 = 0.03888790851500538427243816815621
a4 = 0.00053929470556132745010379056762059
3-99
3 Mathematics
alpha1 =
σ3 σ2 + σ3 σ1 + σ2 σ1 − σ3 σ2 σ1 − 2 σ3 − 2 σ2 − 2 σ1 + 6
−
σ4 − σ3 σ4 σ2 + σ4 σ1 − σ2 σ1 − σ42
where
σ1 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 4
σ2 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 3
σ3 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 2
σ4 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 1
alpha2 =
root σ1, z, 1 root σ1, z, 3 + root σ1, z, 1 root σ1, z, 4 + root σ1, z, 3 root σ1, z, 4 − root σ1, z, 1 root σ1, z, 3 root σ1, z, 4
root σ1, z, 2 − root σ1, z, 1 root σ1, z, 2 − root σ1, z, 3 root σ1, z, 2 − root
where
σ1 = z4 − 16 z3 + 72 z2 − 96 z + 24
alpha3 =
σ3 σ2 + σ3 σ1 + σ2 σ1 − σ3 σ2 σ1 − 2 σ3 − 2 σ2 − 2 σ1 + 6
σ4 − σ1 σ3 σ2 − σ3 σ4 − σ2 σ4 + σ42
where
σ1 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 4
σ2 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 2
σ3 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 1
σ4 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 3
alpha4 =
σ3 σ2 + σ3 σ1 + σ2 σ1 − σ3 σ2 σ1 − 2 σ3 − 2 σ2 − 2 σ1 + 6
−
σ4 σ3 + σ42 σ2 + σ42 σ1 − σ43 + σ3 σ2 σ1 − σ3 σ2 σ4 − σ3 σ1 σ4 − σ2 σ1 σ4
2
where
σ1 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 3
σ2 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 2
σ3 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 1
σ4 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 4
Alternatively, you can also obtain the solution as a structure by giving only one output argument.
S = solve(sys, y)
3-100
Gauss-Laguerre Quadrature Evaluation Points and Weights
structfun(@double, S)
ans = 4×1
0.6032
0.3574
0.0389
0.0005
Scell = struct2cell(S);
alpha = transpose([Scell{:}])
alpha =
3-101
3 Mathematics
where
2
σ14 = root σ16, z, 4
σ16 = z4 − 16 z3 + 72 z2 − 96 z + 24
The symbolic solution looks complicated. Simplify it, and convert it into a floating point vector:
alpha = simplify(alpha)
alpha =
3-102
Gauss-Laguerre Quadrature Evaluation Points and Weights
2
root σ1, z, 1 29 root σ1, z, 1 2
− +
72 144 3
2
root σ1, z, 2 29 root σ1, z, 2 2
− +
72 144 3
2
root σ1, z, 3 29 root σ1, z, 3 2
− +
72 144 3
2
root σ1, z, 4 29 root σ1, z, 4 2
− +
72 144 3
where
σ1 = z4 − 16 z3 + 72 z2 − 96 z + 24
vpa(alpha)
ans =
0.60315410434163360163596602381808
0.35741869243779968664149201745809
0.03888790851500538427243816815621
0.00053929470556132745010379056762059
Increase the readability by replacing the occurrences of the roots x in alpha by abbreviations:
ans =
R12 29 R1 2
− +
72 144 3
2
root σ1, z1, 2 29 root σ1, z1, 2 2
− +
72 144 3
2
root σ1, z1, 3 29 root σ1, z1, 3 2
− +
72 144 3
2
root σ1, z1, 4 29 root σ1, z1, 4 2
− +
72 144 3
where
simplify(sum(alpha))
ans = 1
A different method to obtain the weights of a quadrature rule is to compute them using the formula
t − xj
∫
b
αi = w(t) ∏ dt. Do this for i = 1. It leads to the same result as the other method:
a x
j≠i i
− xj
ans =
3-103
3 Mathematics
2
root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 1 29 root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 1 2
− +
72 144 3
The quadrature rule produces exact results even for all polynomials of degree less than or equal to
2n − 1, but not for t2n.
ans = 0
ans = −576
Apply the quadrature rule to the cosine, and compare with the exact result:
vpa(sum(alpha.*(cos(x))))
ans = 0.50249370546067059229918484198931
int(cos(t)*w(t), t, 0, inf)
ans =
1
2
For powers of the cosine, the error oscillates between odd and even powers:
3-104
Gauss-Laguerre Quadrature Evaluation Points and Weights
3-105
3 Mathematics
This example obtains the partial differential equation that describes the expected final price of an
asset whose price is a stochastic process given by a stochastic differential equation.
A model for the price of an asset X(t) defined in the time interval [0,T] is a stochastic process
defined by a stochastic differential equation of the form dX = μ(t, X)dt + σ(t, X)dB(t), where B(t) is
the Wiener process with unit variance parameter.
• r(t) is a continuous function representing a spot interest rate. This rate determines the discount
factor for the final payoff at the time T.
• u(t,x) is the expected value of the discounted future price calculated as X T exp −∫T r t dt
t
under the condition X(t) = x.
• μ(t, X) and σ(t, X) are drift and diffusion of the stochastic process X(t).
The numerical solver pdepe works with initial conditions. To transform the final condition into an
initial condition, apply a time reversal by setting u(t, X) = v(T - t, X).
syms v(t, X)
eq2 = subs(eq, {u, t}, {v(T - t, X), T - t});
eq2 = feval(symengine, 'rewrite', eq2, 'diff')
eq2 =
2
2 ∂
σ T − t, X v t, X
∂ X2 ∂ ∂
+ μ T − t, X v t, X − v t, X − v t, X r T − t, X
2 ∂X ∂t
The solver pdepe requires the partial differential equation in the following form. Here the
coefficients c, f, and s are functions of x, t, v, and ∂v/ ∂x.
∂v ∂f
c = +s
∂t ∂x
3-106
Simulate a Stochastic Process Using the Feynman–Kac Formula
To be able to solve the equation eq2 with the pdepe solver, map eq2 to this form. First, extract the
coefficients and terms of eq2.
syms dvt dvXX
eq3 = subs(eq2, {diff(v, t), diff(v, X, X)}, {dvt, dvXX});
[k,terms] = coeffs(eq3, [dvt, dvXX])
k =
2
σ T − t, X ∂
−1 μ T − t, X v t, X − v t, X r T − t, X
2 ∂X
∂v ∂2 v
= k(2) 2 + k(3)
∂t ∂X
∂ ∂v ∂v ∂k(2)
k(2) + k(3) −
∂X ∂X ∂X ∂X
Therefore, to write eq2 in the form suitable for pdepe, use the following parameters:
c = 1;
f = k(2) * diff(v, X);
s = k(3) - diff(v, X) * diff(k(2), X);
Asset prices follow a multiplicative process. That is, the logarithm of the price can be described in
terms of an SDE, but the expected value of the price itself is of interest because it describes the
profit, and thus we need an SDE for the latter.
In general, if a stochastic process X is given in terms of an SDE, then Ito's rule says that the
transformed process G(t, X) satisfies
2
dG σ2 d G dG dG
dG = μ + + dt + σdB(t)
dX 2 dX 2 dt dX
We assume that the logarithm of the price is given by a one-dimensional additive Brownian motion,
that is, mu and sigma are constants. Define a function that applies Ito's rule, and use it to transform
the additive Brownian motion into a geometric Brownian motion.
ito = @(mu, sigma, G, t, X) ...
deal( mu * diff(G, X) + sigma^2/2 * diff(G, X, X) + diff(G, t), ...
diff(G, X) * sigma );
mu1 =
e X σ02
+ μ0 e X
2
3-107
3 Mathematics
sigma1 = σ0 e X
Replace exp(X) by Y.
syms Y
mu1 = subs(mu1, X, log(Y));
sigma1 = subs(sigma1, X, log(Y));
f = f(t, log(Y));
s = s(t, log(Y));
For simplicity, assume that the interest rate is zero. This is a special case also known as Kolmogorov
backward equation.
r0 = 0;
Before you can convert symbolic expressions to MATLAB function handles, you must replace function
calls, such as diff(v(t, X), X) and v(t, X), with variables. You can use any valid MATLAB
variable names.
syms dvdx V;
dvX = diff(v, X);
c = subs(c, {dvX, v}, {dvdx, V});
f = subs(f, {dvX, v}, {dvdx, V});
s = subs(s, {dvX, v}, {dvdx, V});
m = 0;
muvalue = 0;
sigmavalue = 1;
Use matlabFunction to create a function handle. Pass the coefficients c0, f0, and s0 in the form
required by pdepe, namely, a function handle with three output arguments.
As the final condition, take the identity mapping. That is, the payoff at time T is given by the asset
price itself. You can modify this line in order to investigate derivative instruments.
FeynmanKacIC = @(x) x;
3-108
Simulate a Stochastic Process Using the Feynman–Kac Formula
Numerical solving of PDEs can only be applied to a finite domain. Therefore, you must specify a
boundary condition. Assume that the asset is sold at the moment when its price rises above or falls
below a certain limit, and thus the solution v has to satisfy x - v = 0 at the boundary points x. You
can choose another boundary condition, for example, you can use v = 0 to model knockout options.
The zeroes in the second and fourth output indicate that the boundary condition does not depend on
dv
dx
.
Choose the space grid, which is the range of values of the price x. Set the left boundary to zero: it is
not reachable by a geometric random walk. Set the right boundary to one: when the asset price
reaches this limit, the asset is sold.
Choose the time grid. Because of the time reversal applied in the beginning, it denotes the time left
until the final time T.
sol = pdepe(m,FeynmanKacPde,FeynmanKacIC,FeynmanKacBC,xgrid,tgrid);
Plot the solution. The expected selling price depends nearly linearly on the price at time t, and also
weakly on t.
3-109
3 Mathematics
The state of a geometric Brownian motion with drift μ1 at time t is a lognormally distributed random
variable with expected value exp(μ1t) times its initial value. This describes the expected selling price
of an asset that is never sold because of reaching a limit.
Dividing the solution obtained above by that expected value shows how much profit is lost by selling
prematurely at the limit.
sol2 = sol./Expected;
surf(xgrid, tgrid, sol2)
title('Ratio of expected final prices: with / without sales order at x=1')
xlabel('price');
ylabel('time');
zlabel('ratio of final prices');
3-110
Simulate a Stochastic Process Using the Feynman–Kac Formula
For example, plot the ratio of the expected payoff of an asset for which a limit sales order has been
placed and the same asset without sales order over a timespan T, as a function of t. Consider the
case of an order limit of two and four times the current price, respectively.
3-111
3 Mathematics
It is a textbook result that the expected exit time when the limit is reached and the asset is sold is
given by the following equation:
syms y(X)
exitTimeEquation(X) = subs(eq, {r, u}, {0, y(X)}) == -1
exitTimeEquation(X) =
2
2 ∂
σ t, X y X
∂ X2 ∂
+ μ t, X y X = −1
2 ∂X
In addition, y must be zero at the boundaries. For mu and sigma, insert the actual stochastic process
under consideration:
exitTimeGBM = subs(subs(exitTimeEquation, {mu, sigma}, {mu1, sigma1}), Y, X)
exitTimeGBM(X) =
∂2
X 2 σ02 y X
X σ02 ∂ ∂ X2
+ X μ0 y X + = −1
2 ∂X 2
3-112
Simulate a Stochastic Process Using the Feynman–Kac Formula
exitTime =
σ σ σ σ σ
2 μ0 σ4 log b − 2 μ0 σ5 log a + a 1 σ02 σ4 σ5 − b 1 σ02 σ4 σ5 log X σ2 σ6 − σ7 − a 1 σ02 σ4 + b 1 σ02 σ5 X 1 σ02
− + +
σ3 μ0 σ3 2 μ02
where
2 μ0
σ1 =
σ02
2 μ0 log X
−
σ2 = e σ02
σ3 = 2 μ02 σ4 − σ5
σ6
−
σ4 = e σ02
σ7
−
σ5 = e σ02
σ6 = 2 μ0 log a
σ7 = 2 μ0 log b
Because you cannot substitute mu0 = 0 directly, compute the limit at mu0 -> 0 instead.
Using the value b = 1 for the right border, compute the limit.
ans = ∞
See Also
Functions
diff | subs | coeffs | matlabFunction | dsolve
3-113
3 Mathematics
This example shows how to calculate the call option price using the Black–Scholes formula. This
example uses vpasolve to numerically solve the problems of finding the spot price and implied
volatility from the Black–Scholes formula.
The Black–Scholes formula models the price of European call options [1 on page 3-118]. For a non-
dividend-paying underlying stock, the parameters of the formula are defined as:
where:
• 1 S σ2
d1 = log + r+ T
σ T K 2
• d2 = d1 − σ T
• PV(K) = Kexp( − rT)
•
∫
1 d
N(d) is the standard normal cumulative distribution function, N(d) = exp( − t2 /2) dt.
2π −∞
Find the price of a European stock option that expires in three months with an exercise price of $95.
Assume that the underlying stock pays no dividend, trades at $100, and has a volatility of 50% per
annum. The risk-free rate is 1% per annum.
Use sym to create symbolic numbers that represent the values of the Black–Scholes parameters.
syms t d
S = sym(100); % current stock price (spot price)
K = sym(95); % exercise price (strike price)
sigma = sym(0.50); % volatility of stock
T = sym(3/12); % expiry time in years
r = sym(0.01); % annualized risk-free interest rate
Calculate the option price without approximation. Create a symbolic function N(d) that represents
the standard normal cumulative distribution function.
PV_K = K*exp(-r*T);
d1 = (log(S/K) + (r + sigma^2/2)*T)/(sigma*sqrt(T));
d2 = d1 - sigma*sqrt(T);
N(d) = int(exp(-((t)^2)/2),t,-Inf,d)*1/sqrt(2*sym(pi))
3-114
The Black–Scholes Formula for Call Option Price
N(d) =
2d
erf 2 1
+
2 2
Csym =
20 23
2 4 log −
19 200
20 27
erf 2
2 4 log 19 + 200 1 1
50 erf − 95 e− 400 + + 50
2 2 2
To obtain the numeric result with variable precision, use vpa. By default, vpa returns a number with
32 significant digits.
Cvpa = vpa(Csym)
Cvpa = 12.52792339252145394554497137187
To change the precision, use digits. The price of the option to 6 significant digits is $12.5279.
digits(6)
Cvpa = vpa(Csym)
Cvpa = 12.5279
Next, suppose that for the same stock option the time to expiry changes and the day-to-day stock
price is unknown. Find the price of this call option for expiry time T that varies from 0 to 0.25 years,
and spot price S that varies from $50 to $140. Use the values for exercise rate (K), volatility (sigma),
and interest rate (r) from the previous example. In this case, use the time to expiry T and day-to-day
stock price S as the variable quantities.
Define the symbolic expression C to represent the call option price with T and S as the unknown
variables.
syms T S
PV_K = K*exp(-r*T);
d1 = (log(S/K) + (r + sigma^2/2)*T)/(sigma*sqrt(T));
d2 = d1 - sigma*sqrt(T);
Nd1 = int(exp(-((t)^2)/2),-Inf,d1)*1/sqrt(2*pi);
Nd2 = int(exp(-((t)^2)/2),-Inf,d2)*1/sqrt(2*pi);
C = Nd1*S - Nd2*PV_K;
Plot the call option price as a function of spot price and expiry time.
3-115
3 Mathematics
Calculate the call option price with expiry time 0.1 years and spot price $105. Use subs to substitute
the values of T and S to the expression C. Return the price as a numeric result using vpa.
Cvpa = 12.5868
Consider the case where the option price is changing, and you want to know how this affects the
underlying stock price. This is a problem of finding S from the Black–Scholes formula given the
known parameters K , σ, T , r , and C.
For example, after one month, the price of the same call option now trades at $15.04 with expiry time
of two months. Find the spot price of the underlying stock. Create a symbolic function C(S) that
represents the Black–Scholes formula with the unknown parameter S.
PV_K = K*exp(-r*T);
d1(S) = (log(S/K) + (r + sigma^2/2)*T)/(sigma*sqrt(T));
3-116
The Black–Scholes Formula for Call Option Price
d2(S) = d1 - sigma*sqrt(T);
Nd1(S) = int(exp(-((t)^2)/2),-Inf,d1)*1/sqrt(2*pi);
Nd2(S) = int(exp(-((t)^2)/2),-Inf,d2)*1/sqrt(2*pi);
C(S) = Nd1*S - Nd2*PV_K;
Use vpasolve to numerically solve for the spot price of the underlying stock. Search for solutions
only in the positive numbers. The spot price of the underlying stock is $106.162.
S_Sol = 106.162
Consider the case where the option price is changing and you want to know what is the implied
volatility. This is a problem of finding the value of σ from the Black–Scholes formula given the known
parameters S, K , T , r , and C.
Consider the same stock option that expires in three months with an exercise price of $95. Assume
that the underlying stock trades at $100, and the risk-free rate is 1% per annum. Find the implied
volatility as a function of option price that ranges from $6 to $25. Create a vector for the range of the
option price. Create a symbolic function C(sigma) that represents the Black–Scholes formula with
the unknown parameter sigma. Use vpasolve to numerically solve for the implied volatility.
PV_K = K*exp(-r*T);
d1(sigma) = (log(S/K) + (r + sigma^2/2)*T)/(sigma*sqrt(T));
d2(sigma) = d1 - sigma*sqrt(T);
Nd1(sigma) = int(exp(-((t)^2)/2),-Inf,d1)*1/sqrt(2*pi);
Nd2(sigma) = int(exp(-((t)^2)/2),-Inf,d2)*1/sqrt(2*pi);
C(sigma) = Nd1*S - Nd2*PV_K;
for i = 1:length(C_Range)
sigma_Sol(i) = vpasolve(C(sigma) == C_Range(i),sigma,[0 Inf]);
end
plot(C_Range,sigma_Sol)
xlabel('Option price')
ylabel('Implied volatility')
3-117
3 Mathematics
Reference
[1] https://en.wikipedia.org/wiki/Black–Scholes_model
See Also
Functions
vpa | vpasolve | subs
3-118
Choose Function to Rearrange Expression
syms x y
combine(2*sin(x)*cos(x),'sincos')
ans =
sin(2*x)
If you do not specify a target function, combine uses the identities for powers wherever these
identities are valid:
• ab ac = ab + c
• ac bc = (a b)c
• (ab)c = abc
For example, by default the function combines the following square roots.
combine(sqrt(2)*sqrt(x))
ans =
(2*x)^(1/2)
The function does not combine the square roots sqrt(x)*sqrt(y) because the identity is not valid
for negative values of variables.
combine(sqrt(x)*sqrt(y))
3-119
3 Mathematics
ans =
x^(1/2)*y^(1/2)
ans =
(x*y)^(1/2)
ans =
(x*y)^(1/2)
For further computations, clear the assumptions on x and y by recreating them using syms.
syms x y
As target functions, combine accepts atan, exp, gamma, int, log, sincos, and sinhcosh.
Expand Expressions
For elementary expressions, use the expand function to transform the original expression by
multiplying sums of products. This function provides an easy way to expand polynomials.
expand((x - 1)*(x - 2)*(x - 3))
ans =
x^3 - 6*x^2 + 11*x - 6
expand(x*(x*(x - 6) + 11) - 6)
ans =
x^3 - 6*x^2 + 11*x - 6
The function also expands exponential and logarithmic expressions. For example, expand the
following expression containing exponentials.
expand(exp(x + y)*(x + exp(x - y)))
ans =
exp(2*x) + x*exp(x)*exp(y)
Expand an expression containing logarithm. Expanding logarithms is not valid for generic complex
values, but it is valid for positive values.
syms a b c positive
expand(log(a*b*c))
ans =
log(a) + log(b) + log(c)
3-120
Choose Function to Rearrange Expression
syms a b c
expand(log(a*b*c),'IgnoreAnalyticConstraints',true)
ans =
log(a) + log(b) + log(c)
expand also works on trigonometric expressions. For example, expand this expression.
expand(cos(x + y))
ans =
cos(x)*cos(y) - sin(x)*sin(y)
expand(sin(5*x))
ans =
sin(x) - 12*cos(x)^2*sin(x) + 16*cos(x)^4*sin(x)
expand(cos(3*acos(x)))
ans =
4*x^3 - 3*x
ans =
2*sin(x) + 2*cos(x)^2 - 10*cos(x)^2*sin(x) + 8*cos(x)^4*sin(x) - 2
To prevent the expansion of all trigonometric, logarithmic, and exponential subexpressions, use the
option ArithmeticOnly.
ans =
exp(x - y)*exp(x + y) + x*exp(x + y)
ans =
cos(2*x) - sin(3*x) + cos(2*x)*sin(3*x) - 1
Factor Expressions
To return all irreducible factors of an expression, use the factor function. For example, find all
irreducible polynomial factors of this polynomial expression. The result shows that this polynomial
has three roots: x = 1, x = 2, and x = 3.
syms x
factor(x^3 - 6*x^2 + 11*x - 6)
ans =
[ x - 3, x - 1, x - 2]
3-121
3 Mathematics
ans =
x^3 - 6*x^2 + 11*x - 5
Find irreducible polynomial factors of the expression x^6 + 1. By default, factor uses factorization
over rational numbers keeping rational numbers in their exact symbolic form. The resulting factors
for this expression do not show polynomial roots.
factor(x^6 + 1)
ans =
[ x^2 + 1, x^4 - x^2 + 1]
Using other factorization modes lets you factor this expression further. For example, factor the same
expression over complex numbers.
factor(x^6 + 1,'FactorMode','complex')
ans =
[ x + 0.86602540378443864676372317075294 + 0.5i,...
x + 0.86602540378443864676372317075294 - 0.5i,...
x + 1.0i,...
x - 1.0i,...
x - 0.86602540378443864676372317075294 + 0.5i,...
x - 0.86602540378443864676372317075294 - 0.5i]
factor also works on expressions other than polynomials and rational expressions. For example, you
can factor the following expression that contains logarithm, sine, and cosine functions. Internally,
factor converts such expressions into polynomials and rational expressions by substituting
subexpressions with variables. After computing irreducible factors, the function restores original
subexpressions.
ans =
[ log(x) - 1, log(x) + 1, 1/(cos(x) - sin(x)), 1/(cos(x) + sin(x))]
factor(sym(902834092))
factor(1/sym(210))
ans =
[ 2, 2, 47, 379, 12671]
ans =
[ 1/2, 1/3, 1/5, 1/7]
factor also can factor numbers larger than flintmax that the MATLAB factor cannot. To
represent a large number accurately, place the number in quotation marks.
factor(sym('41758540882408627201'))
ans =
[ 479001599, 87178291199]
3-122
Choose Function to Rearrange Expression
syms x y
f = exp(3*x)*y^3 + exp(2*x)*y^2 + exp(x)*y;
expr = children(f)
expr =
1×3 cell array
{[y^2*exp(2*x)]} {[y^3*exp(3*x)]} {[y*exp(x)]}
You can extract lower-level subexpressions by calling children repeatedly on the results.
expr1 = children(expr{1})
expr1 =
1×2 cell array
{[y^2]} {[exp(2*x)]}
expr1{1}
expr1{2}
ans =
y^2
ans =
exp(2*x)
syms x y z
expr = x*y^4 + x*z + 2*x^3 + x^2*y*z +...
3*x^3*y^4*z^2 + y*z^2 + 5*x*y*z;
collect(expr, x)
ans =
(3*y^4*z^2 + 2)*x^3 + y*z*x^2 + (y^4 + 5*z*y + z)*x + y*z^2
Group the terms of the same expression with the equal powers of y.
collect(expr, y)
3-123
3 Mathematics
ans =
(3*x^3*z^2 + x)*y^4 + (x^2*z + 5*x*z + z^2)*y + 2*x^3 + z*x
Group the terms of the same expression with the equal powers of z.
collect(expr, z)
ans =
(3*x^3*y^4 + y)*z^2 + (x + 5*x*y + x^2*y)*z + 2*x^3 + x*y^4
If you do not specify variables that collect must consider as unknowns, the function uses symvar to
determine the default variable.
collect(expr)
ans =
(3*y^4*z^2 + 2)*x^3 + y*z*x^2 + (y^4 + 5*z*y + z)*x + y*z^2
Collect terms of an expression with respect to several unknowns by specifying those unknowns as a
vector.
collect(expr, [y,z])
ans =
3*x^3*y^4*z^2 + x*y^4 + y*z^2 + (x^2 + 5*x)*y*z + x*z + 2*x^3
ans =
(2*tan(x/2))/(tan(x/2)^2 + 1)
rewrite(cos(x),'tan')
ans =
-(tan(x/2)^2 - 1)/(tan(x/2)^2 + 1)
rewrite(sin(2*x) + cos(3*x)^2,'tan')
ans =
(tan((3*x)/2)^2 - 1)^2/(tan((3*x)/2)^2 + 1)^2 +...
(2*tan(x))/(tan(x)^2 + 1)
Use rewrite to express these trigonometric functions in terms of the exponential function.
rewrite(sin(x),'exp')
ans =
(exp(-x*1i)*1i)/2 - (exp(x*1i)*1i)/2
rewrite(cos(x),'exp')
ans =
exp(-x*1i)/2 + exp(x*1i)/2
3-124
Choose Function to Rearrange Expression
Use rewrite to express these hyperbolic functions in terms of the exponential function.
rewrite(sinh(x),'exp')
ans =
exp(x)/2 - exp(-x)/2
rewrite(cosh(x),'exp')
ans =
exp(-x)/2 + exp(x)/2
ans =
log(x + (x^2 + 1)^(1/2))
rewrite(acosh(x),'log')
ans =
log(x + (x - 1)^(1/2)*(x + 1)^(1/2))
ans =
1/(x + 1) + 1/(x + 2)^2 + 1/(x + 3)^3 + 1
The denominators in rational terms represent the factored common denominator of the original
expression.
factor(d)
ans =
[ x + 1, x + 2, x + 2, x + 3, x + 3, x + 3]
ans =
(x^3 + 3*x^2)/(x^2 - y^2)
3-125
3 Mathematics
ans =
x - y
simplifyFraction also handles expressions other than polynomials and rational functions.
Internally, it converts such expressions into polynomials or rational functions by substituting
subexpressions with identifiers. After normalizing the expression with temporary variables,
simplifyFraction restores the original subexpressions.
ans =
exp(x) + exp(y)
syms x
horner(x^3 - 6*x^2 + 11*x - 6)
ans =
x*(x*(x - 6) + 11) - 6
If polynomial coefficients are floating-point numbers, the resulting Horner form represents them as
rational numbers.
ans =
x*((33*x)/10 + 11/5) + 11/10
vpa(ans)
ans =
x*(3.3*x + 2.2) + 1.1
3-126
Extract Numerators and Denominators of Rational Expressions
[n,d] = numden(1/sym(3))
n =
1
d =
3
syms x y
[n,d] = numden((x^2 - y^2)/(x^2 + y^2))
n =
x^2 - y^2
d =
x^2 + y^2
Use numden to find numerators and denominators of symbolic functions. If the input is a symbolic
function, numden returns the numerator and denominator as symbolic functions.
n(x) =
sin(x)
d(x) =
x^2
[n,d] = numden(f/g)
n(x) =
sin(x)
d(x) =
x*cos(x)
numden converts the input to its one-term rational form, such that the greatest common divisor of the
numerator and denominator is 1. Then it returns the numerator and denominator of that form of the
expression.
n =
x^2 + y^2
d =
x*y
3-127
3 Mathematics
numden works on vectors and matrices. If an input is a vector or matrix, numden returns two vectors
or two matrices of the same size as the input. The first vector or matrix contains numerators of each
element. The second vector or matrix contains denominators of each element. For example, find
numerators and denominators of each element of the 3-by-3 Hilbert matrix.
H = sym(hilb(3))
H =
[ 1, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
[n,d] = numden(H)
n =
[ 1, 1, 1]
[ 1, 1, 1]
[ 1, 1, 1]
d =
[ 1, 2, 3]
[ 2, 3, 4]
[ 3, 4, 5]
3-128
Simplify Symbolic Expressions
The first form clearly shows the roots of this polynomial. This form is simpler for working with the
roots. The second form serves best when you want to see the coefficients of the polynomial. For
example, this form is convenient when you differentiate or integrate polynomials.
If the problem you want to solve requires a particular form of an expression, the best approach is to
choose the appropriate simplification function. See “Choose Function to Rearrange Expression” on
page 3-119.
Besides specific simplifiers, Symbolic Math Toolbox offers a general simplifier, simplify.
If you do not need a particular form of expressions (expanded, factored, or expressed in particular
terms), use simplify to shorten mathematical expressions. For example, use this simplifier to find a
shorter form for a final result of your computations.
simplify works on various types of symbolic expressions, such as polynomials, expressions with
trigonometric, logarithmic, and special functions. For example, simplify these polynomials.
syms x y
simplify((1 - x^2)/(1 - x))
simplify((x - 1)*(x + 1)*(x^2 + x + 1)*(x^2 + 1)*(x^2 - x + 1)*(x^4 - x^2 + 1))
ans =
x + 1
ans =
x^12 - 1
simplify(cos(x)^(-2) - tan(x)^2)
simplify(cos(x)^2 - sin(x)^2)
ans =
1
ans =
cos(2*x)
Simplify expressions involving exponents and logarithms. In the third expression, use log(sym(3))
instead of log(3). If you use log(3), then MATLAB calculates log(3) with the double precision,
and then converts the result to a symbolic number.
simplify(exp(x)*exp(y))
simplify(exp(x) - exp(x/2)^2)
simplify(log(x) + log(sym(3)) - log(3*x) + (exp(x) - 1)/(exp(x/2) + 1))
3-129
3 Mathematics
ans =
exp(x + y)
ans =
0
ans =
exp(x/2) - 1
simplify(gamma(x + 1) - x*gamma(x))
simplify(besselj(2, x) + besselj(0, x))
ans =
0
ans =
(2*besselj(1, x))/x
syms f(x,y)
f(x,y) = exp(x)*exp(y)
f = simplify(f)
f(x, y) =
exp(x)*exp(y)
f(x, y) =
exp(x + y)
syms x
simplify(log(x^2) + log(x))
ans =
log(x^2) + log(x)
You can apply additional simplification rules which are not correct for all values of parameters and all
cases, but using which simplify can return shorter results. For this approach, use
IgnoreAnalyticConstraints. For example, simplifying the same expression
with IgnoreAnalyticConstraints, you get the result with combined logarithms.
simplify(log(x^2) + log(x),'IgnoreAnalyticConstraints',true)
ans =
3*log(x)
3-130
Simplify Symbolic Expressions
in general. If you assume that x is a real value, simplify combines logarithms without
IgnoreAnalyticConstraints.
assume(x,'real')
simplify(log(x^2) + log(x))
ans =
log(x^3)
syms x
Another approach that can improve simplification of an expression or function is the syntax
simplify(f,'Steps',n), where n is a positive integer that controls how many steps simplify
takes. Specifying more simplification steps can help you simplify the expression better, but it takes
more time. By default, n = 1. For example, create and simplify this expression. The result is shorter
than the original expression, but it can be simplified further.
syms x
y = (cos(x)^2 - sin(x)^2)*sin(2*x)*(exp(2*x) - 2*exp(x) + 1)/...
((cos(2*x)^2 - sin(2*x)^2)*(exp(2*x) - 1));
simplify(y)
ans =
(sin(4*x)*(exp(x) - 1))/(2*cos(4*x)*(exp(x) + 1))
Specify the number of simplification steps for the same expression. First, use 25 steps.
simplify(y,'Steps',25)
ans =
(tan(4*x)*(exp(x) - 1))/(2*(exp(x) + 1))
simplify(y,'Steps',50)
ans =
(tan(4*x)*tanh(x/2))/2
Suppose, you already simplified an expression or function, but you want the other forms of the same
expression. To do this, you can set the 'All' option to true. The syntax
simplify(f,'Steps',n,'All',true) shows other equivalent results of the same expression in
the simplification steps.
syms x
y = cos(x) + sin(x)
simplify(y,'Steps',10,'All',true)
ans =
2^(1/2)*sin(x + pi/4)
2^(1/2)*cos(x - pi/4)
cos(x) + sin(x)
2^(1/2)*((exp(- x*1i - (pi*1i)/4)*1i)/2 - (exp(x*1i + (pi*1i)/4)*1i)/2)
To return even more equivalent results, increase the number of steps to 25.
simplify(y,'Steps',25,'All',true)
3-131
3 Mathematics
ans =
2^(1/2)*sin(x + pi/4)
2^(1/2)*cos(x - pi/4)
cos(x) + sin(x)
-2^(1/2)*(2*sin(x/2 - pi/8)^2 - 1)
2^(1/2)*(exp(- x*1i + (pi*1i)/4)/2 + exp(x*1i - (pi*1i)/4)/2)
2^(1/2)*((exp(- x*1i - (pi*1i)/4)*1i)/2 - (exp(x*1i + (pi*1i)/4)*1i)/2)
ans =
sin(2*pi*n)
However, if you assume that variable n represents an integer, the same trigonometric expression
simplifies to 0.
assume(n,'integer')
simplify(sin(2*n*pi))
ans =
0
Simplify Fractions
You can use the general simplification function, simplify, to simplify fractions. However, Symbolic
Math Toolbox offers a more efficient function specifically for this task: simplifyFraction. The
statement simplifyFraction(f) represents the expression f as a fraction, where both the
numerator and denominator are polynomials whose greatest common divisor is 1. For example,
simplify these expressions.
syms x y
simplifyFraction((x^3 - 1)/(x - 1))
ans =
x^2 + x + 1
ans =
(x^2 - 2*x*y + y^2)/(x^2 - x*y + y^2)
By default, simplifyFraction does not expand expressions in the numerator and denominator of
the returned result. To expand the numerator and denominator in the resulting expression, use the
Expand option. For comparison, first simplify this fraction without Expand.
simplifyFraction((1 - exp(x)^4)/(1 + exp(x))^4)
3-132
Simplify Symbolic Expressions
ans =
(exp(2*x) - exp(3*x) - exp(x) + 1)/(exp(x) + 1)^3
ans =
(exp(2*x) - exp(3*x) - exp(x) + 1)/(3*exp(2*x) + exp(3*x) + 3*exp(x) + 1)
3-133
3 Mathematics
Starting in R2020a, you can interactively simplify or rearrange symbolic expressions using the
Simplify Symbolic Expression task in the Live Editor. For more information on Live Editor tasks, see
“Add Interactive Tasks to a Live Script”.
This example shows you how to simplify or rearrange various symbolic expressions into the particular
form you require by choosing the appropriate method.
e−ix − eix
Simplify the expression i .
e−ix + eix
First, go to the Home tab, and create a live script by clicking New Live Script. Define the
symbolic variable x and declare the expression as a symbolic expression.
syms x;
expr = 1i*(exp(-1i*x) - exp(1i*x))/(exp(-1i*x) + exp(1i*x));
In the Live Editor tab, run the code by clicking Run to store x and expr into the current
workspace.
Next, open the Simplify Symbolic Expression task by selecting Task > Simplify Symbolic
Expression in the Live Editor tab. Select the symbolic expression expr from the workspace and
specify the simplification method as Simplify. Select Minimum for the computational effort (fastest
computation time).
3-134
Simplify Symbolic Expressions Using Live Editor Task
To experiment with simplifying symbolic expressions, you can repeat the previous steps for other
symbolic expressions and simplification methods. You can run the following examples by adding the
code to the existing live script or a new live script.
(x2 − 1)(x + 1)
Simplify the polynomial fraction .
x2 − 2x + 1
Select the symbolic expression expr2 from the workspace and specify the simplification method as
Simplify fraction.
Select the Expand option to return the numerator and denominator of the simplified fraction in
expanded form.
3-135
3 Mathematics
Select the symbolic expression expr3 from the workspace and specify the simplification method as
Rewrite. Choose sin to rewrite tan(x) in terms of the sine function.
x3 ex
Expand the expression log using the logarithmic identities.
2
3-136
Simplify Symbolic Expressions Using Live Editor Task
expr4 = log(x^3*exp(x)/2);
Select the symbolic expression expr4 from the workspace and specify the simplification method as
Expand. By default, the symbolic variable x in expr4 is complex when it is initially created. The
Expand method does not simplify the input expression because the logarithmic identities are not
valid for complex values of variables. To apply identities that are convenient but do not always hold
for all values of variables, select the Ignore analytic constraints option.
∫ x f x dx + ∫ g y dy.
b b
Simplify the sum of two integral expressions:
a a
First, define a and b as symbolic variables, and f (x) and g(y) as symbolic functions. Use the int
function to represent the integrals.
Select the symbolic expression expr5 from the workspace and specify the simplification method as
Combine. Choose int as the function to combine.
3-137
3 Mathematics
Generate Code
To view the code that a task used, click at the bottom of the task window. The task displays the
code block, which you can cut and paste to use or modify later in the existing script or a different
program. For example:
Because the underlying code is now part of your live script, you can continue to use the variables
created by the task for further processing. For example, define the functions f (x) and g(x) as f (x) = x
and g(x) = cos(x). Evaluate the integrals in simplifiedExpr3 by substituting these functions.
3-138
Simplify Symbolic Expressions Using Live Editor Task
See Also
Live Editor Tasks
Simplify Symbolic Expression | Solve Symbolic Equation
Functions
simplify | simplifyFraction | combine | expand | rewrite
Related Examples
• “Add Interactive Tasks to a Live Script”
• “Choose Function to Rearrange Expression” on page 3-119
• Simplify Symbolic Expression
3-139
3 Mathematics
syms x
eqn = sin(2*x) + cos(x) == 0;
[solx, params, conds] = solve(eqn, x, 'ReturnConditions', true)
solx =
pi/2 + pi*k
2*pi*k - pi/6
(7*pi)/6 + 2*pi*k
params =
k
conds =
in(k, 'integer')
in(k, 'integer')
in(k, 'integer')
Replace the parameter k with a new symbolic variable a. First, create symbolic variables k and a.
(The solver does not create variable k in the MATLAB workspace.)
syms k a
Now, use the subs function to replace k by a in the solution vector solx, parameters params, and
conditions conds.
solx = subs(solx, k, a)
params = subs(params, k, a)
conds = subs(conds, k, a)
solx =
pi/2 + pi*a
2*pi*a - pi/6
(7*pi)/6 + 2*pi*a
params =
a
conds =
in(a, 'integer')
in(a, 'integer')
in(a, 'integer')
Suppose, you know that the value of the parameter a is 2. Substitute a with 2 in the solution vector
solx.
subs(solx, a, 2)
ans =
(5*pi)/2
(23*pi)/6
(31*pi)/6
Alternatively, substitute params with 2. This approach returns the same result.
3-140
Substitute Variables in Symbolic Expressions
subs(solx, params, 2)
ans =
(5*pi)/2
(23*pi)/6
(31*pi)/6
Substitute parameter a with a floating-point number. The toolbox converts numbers to floating-point
values, but it keeps intact the symbolic expressions, such as sym(pi), exp(sym(1)), and so on.
ans =
2.5*pi
3.8333333333333333333333333333333*pi
5.1666666666666666666666666666667*pi
Approximate the result of substitution with floating-point values by using vpa on the result returned
by subs.
ans =
7.8539816339744830961566084581988
12.042771838760874080773466302571
16.231562043547265065390324146944
3-141
3 Mathematics
Create a 2-by-2 matrix A with automatically generated elements using sym. The generated elements
A1, 1, A1, 2, A2, 1, and A2, 2 do not appear in the MATLAB® workspace.
A = sym('A',[2 2])
A =
A1, 1 A1, 2
A2, 1 A2, 2
Substitute the element A1, 2 with a value 5. Assign the value directly by indexing into the matrix
element.
A(1,2) = 5
A =
A1, 1 5
A2, 1 A2, 2
Alternatively, you can create a 2-by-2 matrix using syms. Create a matrix B using syms.
syms B [2 2]
B
B =
B1, 1 B1, 2
B2, 1 B2, 2
The generated elements B1, 1, B1, 2, B2, 1, and B2, 2 appear as symbolic variables B1_1, B1_2, B2_1,
and B2_2 in the MATLAB workspace. Use subs to substitute the element of B by specifying the
variable name. For example, substitute B2_2 with 4.
B = subs(B,B2_2,4)
B =
B1, 1 B1, 2
B2, 1 4
You can also create a matrix by specifying the elements individually. Create a 3-by-3 circulant matrix
M.
syms a b c
M = [a b c; b c a; c a b]
M =
a b c
b c a
c a b
Replace variable b in the matrix M by the expression a + 1. The subs function replaces all b elements
in matrix M with the expression a + 1.
M = subs(M,b,a+1)
3-142
Substitute Elements in Symbolic Matrices
M =
a a+1 c
a+1 c a
c a a+1
Next, replace all elements whose value is c with a + 2. You can specify the value to replace as c,
M(1,3) or M(3,1).
M = subs(M,M(1,3),a+2)
M =
a a+1 a+2
a+1 a+2 a
a+2 a a+1
To replace a particular element of a matrix with a new value while keeping all other elements
unchanged, use the assignment operation. For example, M(1,1) = 2 replaces only the first element
of the matrix M with the value 2.
[V,E] = eig(M)
V =
3 1 3 1
1 − − −
2 2 2 2
3 1 3 1
1− − −
2 2 2 2
1 1 1
E =
3a+3 0 0
0 3 0
0 0 − 3
subs(E,a,1)
ans =
6 0 0
0 3 0
0 0 − 3
3-143
3 Mathematics
syms w t
f = sin(w*t);
Suppose, your task involves creating a matrix whose elements are sine functions with angular
velocities represented by a Toeplitz matrix. First, create a 4-by-4 Toeplitz matrix.
W = toeplitz(sym([3 2 1 0]))
W =
[ 3, 2, 1, 0]
[ 2, 3, 2, 1]
[ 1, 2, 3, 2]
[ 0, 1, 2, 3]
Next, replace the variable w in the expression f with the Toeplitz matrix W. When you replace a scalar
in a symbolic expression with a matrix, subs expands the expression into a matrix. In this example,
subs expands f = sin(w*t) into a 4-by-4 matrix whose elements are sin(w*t). Then it replaces w
in that matrix with the corresponding elements of the Toeplitz matrix W.
F = subs(f, w, W)
F =
[ sin(3*t), sin(2*t), sin(t), 0]
[ sin(2*t), sin(3*t), sin(2*t), sin(t)]
[ sin(t), sin(2*t), sin(3*t), sin(2*t)]
[ 0, sin(t), sin(2*t), sin(3*t)]
Find the sum of these sine waves at t = π, t = π/2, t = π/3, t = π/4, t = π/5, and t = π/6.
First, find the sum of all elements of matrix F. Here, the first call to sum returns a row vector
containing sums of elements in each column. The second call to sum returns the sum of elements of
that row vector.
S = sum(sum(F))
S =
6*sin(2*t) + 4*sin(3*t) + 4*sin(t)
subs(S, t, sym(pi)./[1:6])
[ 0,...
0,...
5*3^(1/2), 4*2^(1/2) + 6,...
2^(1/2)*(5 - 5^(1/2))^(1/2) + (5*2^(1/2)*(5^(1/2) + 5)^(1/2))/2,...
3*3^(1/2) + 6]
You also can use subs to replace a scalar element of a matrix with another matrix. In this case, subs
expands the matrix to accommodate new elements. For example, replace zero elements of the matrix
F with a column vector [1;2]. The original 4-by-4 matrix F expands to an 8-by-4 matrix. The subs
function duplicates each row of the original matrix, not only the rows containing zero elements.
F = subs(F, 0, [1;2])
3-144
Substitute Scalars with Matrices
F =
[ sin(3*t), sin(2*t), sin(t), 1]
[ sin(3*t), sin(2*t), sin(t), 2]
[ sin(2*t), sin(3*t), sin(2*t), sin(t)]
[ sin(2*t), sin(3*t), sin(2*t), sin(t)]
[ sin(t), sin(2*t), sin(3*t), sin(2*t)]
[ sin(t), sin(2*t), sin(3*t), sin(2*t)]
[ 1, sin(t), sin(2*t), sin(3*t)]
[ 2, sin(t), sin(2*t), sin(3*t)]
3-145
3 Mathematics
syms x
y = x^2;
x = 2;
y
y =
x^2
If you change the value of x again, the value of y stays x^2. Instead, evaluate y with the new value of
x by using subs.
subs(y)
ans =
4
The evaluated result is 4. However, y has not changed. Change the value of y by assigning the result
to y.
y = subs(y)
y =
4
x = 5;
subs(y)
ans =
4
3-146
Abbreviate Common Terms in Long Expressions
Long expressions often contain several instances of the same subexpression. Such expressions look
shorter if the same subexpression is replaced with an abbreviation. You can use sympref to specify
whether or not to use abbreviated output format of symbolic expressions in live scripts.
1
For example, solve the equation x + = 1 using solve.
x
syms x
sols = solve(sqrt(x) + 1/x == 1, x)
sols =
σ2 1 2
1
+ + − σ1
18 σ2 2 3
σ2 1 2
1
+ + + σ1
18 σ2 2 3
where
1
3 9 σ − σ2 i
2
σ1 =
2
25 23 108 1/3
σ2 = −
54 108
The solve function returns exact solutions as symbolic expressions. By default, live scripts display
symbolic expressions in abbreviated output format. The symbolic preference setting uses an internal
algorithm to choose which subexpressions to abbreviate, which can also include nested abbreviations.
For example, the term σ1 contains the subexpression abbreviated as σ2. The symbolic preference
setting does not provide any options to choose which subexpressions to abbreviate.
You can turn off abbreviated output format by setting the 'AbbreviateOutput' preference to
false. The returned result is a long expression that is difficult to read.
sympref('AbbreviateOutput',false);
sols
sols =
3-147
3 Mathematics
2
1 25 23 108 1/3
3 − − i
25 23 108 1/3 25 23 108 1/3 54 108
1 54
− 108 1 9
54
−
108
+ + −
25 23 108 1/3 2 3 2
18 54 − 108
2
1 25 23 108 1/3
3 − − i
25 23 108 1/3 25 23 108 1/3 54 108
1 54
− 108 1 9
54
−
108
+ + +
25 23 108 1/3 2 3 2
18 54 − 108
The preferences you set using sympref persist through your current and future MATLAB® sessions.
Restore the default values of 'AbbreviateOutput' by specifying the 'default' option.
sympref('AbbreviateOutput','default');
subexpr is another function that you can use to shorten long expressions. This function abbreviates
only one common subexpression, and unlike sympref, it does not support nested abbreviations. Like
sympref, subexpr also does not let you choose which subexpressions to replace.
Use the second input argument of subexpr to specify the variable name that replaces the common
subexpression. For example, replace the common subexpression in sols with the variable t.
[sols1,t] = subexpr(sols,'t')
sols1 =
1 2
t 1 1 3 t− 9t i
+ + +
2 18 t 3 2
1 2
t 1 1 3 t− 9t i
+ + −
2 18 t 3 2
t =
25 23 108 1/3
−
54 108
Although sympref and subexpr do not provide a way to choose which subexpressions to replace in a
solution, you can define these subexpressions as symbolic variables and manually rewrite the
solution.
Rewrite the solutions sols in terms of a1 and a2 before assigning the values of a1 and a2 to avoid
evaluating sols.
sols = [(1/2*a1 + 1/3 + sqrt(3)/2*a2*1i)^2;...
(1/2*a1 + 1/3 - sqrt(3)/2*a2*1i)^2]
3-148
Abbreviate Common Terms in Long Expressions
sols =
a1 1 3 a2 i 2
+ +
2 3 2
a1 1 3 a2 i 2
+ −
2 3 2
1 1
Assign the values t + and t − to a1 and a2, respectively.
9t 9t
a1 = t + 1/(9*t)
a1 =
1 25 23 108 1/3
+ −
25 23 108 1/3 54 108
9 54 − 108
a2 = t - 1/(9*t)
a2 =
25 23 108 1/3 1
− −
54 108 25 23 108 1/3
9 54 − 108
Evaluate sols using subs. The result is identical to the first output in this example.
sols_eval = subs(sols)
sols_eval =
σ2 1 2
1
+ + − σ1
18 σ2 2 3
σ2 1 2
1
+ + + σ1
18 σ2 2 3
where
1
3 9 σ − σ2 i
2
σ1 =
2
25 23 108 1/3
σ2 = −
54 108
3-149
3 Mathematics
This example finds closed-form solutions for the coefficients of frequencies in an output signal. The
output signal results from passing an input through an analytical nonlinear transfer function.
Motivation
To motivate the solution, we take a simple element from circuit theory: an ideal diode (in forward bias
operation). The current, I, is the output that depends exponentially on the input, V. Diodes have
found use in creating devices such as mixers and amplifiers where understanding the harmonic
structure of the output can be useful in characterizing the device and meeting design specifications.
syms Is V Vo real;
I = Is*(exp(V/Vo) - 1)
I = Is eV /Vo − 1
If V is a linear combination of 2 signals at frequencies LO and RF, the nonlinear transfer function will
mix LO and RF to create output with content at combinatorial harmonic frequency combinations:
freqs = {LO, 2LO, RF, 2RF, LO-RF, LO-2RF,...}.
The objective of this example is to determine the coefficients of freqs in the output.
3-150
Harmonic Analysis of Transfer Function Output
syms c1 c2 t LO RF real;
input = c1*cos(LO*t) + c2*cos(RF*t)
n = 3;
harmCombinations = [kron((0:n)',ones(n*2+1,1)),repmat((-n:n)',n+1,1)];
freqs = harmCombinations*[LO;RF];
The first n frequencies are just the negative harmonic frequencies and are therefore redundant
considering that the input signal is real.
freqs = freqs(n+1:end)
freqs =
0
RF
2 RF
3 RF
LO − 3 RF
LO − 2 RF
LO − RF
LO
LO + RF
LO + 2 RF
LO + 3 RF
2 LO − 3 RF
2 LO − 2 RF
2 LO − RF
2 LO
2 LO + RF
2 LO + 2 RF
2 LO + 3 RF
3 LO − 3 RF
3 LO − 2 RF
3 LO − RF
3 LO
3 LO + RF
3 LO + 2 RF
3 LO + 3 RF
3-151
3 Mathematics
Taylor Expansion
To cover the frequency spectrum of interest, a Taylor series of order four for I(V) is sufficient.
s = taylor(I, V, 'Order', 4)
s =
Is V 2Is V 3 Is V
+ +
2 Vo2
6 Vo 3 Vo
Use an input signal combination of the LO and RF frequencies and express f in terms of cos(LO*t)
and cos(RF*t).
f0 = subs(s, V, input);
f = expand(f0)
f =
3 3
Is c12 σ2 Is c13 cos LO t Is c22 σ1 Is c23 cos RF t Is c1 cos LO t Is c2 cos RF t Is c1 c2 cos LO t cos RF t
+ + + + + + +
2 Vo2 3
6 Vo 2 Vo2 6 Vo 3 Vo Vo Vo2
where
2
σ1 = cos RF t
2
σ2 = cos LO t
f = combine(f, 'sincos')
f =
Is c12 Is c22 Is c1 cos LO t Is c2 cos RF t Is c12 cos 2 LO t Is c13 cos LO t Is c13 cos 3 LO t
+ + + + + +
4 Vo 2
4 Vo 2 Vo Vo 4 Vo 2
8 Vo 3
24 Vo3
Is c22 cos 2 RF t Is c23 cos RF t Is c23 cos 3 RF t Is c1 c22 cos LO t Is c12 c2 cos RF t
+ 2
+ 3
+ 3
+ 3
+
4 Vo 8 Vo 24 Vo 4 Vo 4 Vo3
Is c1 c2 cos LO t + RF t Is c1 c2 cos LO t − RF t Is c1 c22 cos LO t − 2 RF t
+ 2
+ 2
+
2 Vo 2 Vo 8 Vo3
Is c1 c22 cos LO t + 2 RF t Is c12 c2 cos 2 LO t + RF t Is c12 c2 cos 2 LO t − RF t
+ 3
+ 3
+
8 Vo 8 Vo 8 Vo3
Get the non-constant i.e. non-DC harmonic frequency terms of the form cos(freq*t).
cosFreqs = cos(expand(freqs*t));
terms = collect(setdiff(cosFreqs', sym(1)));
Extract the coefficients for all harmonic frequency terms including DC.
3-152
Harmonic Analysis of Transfer Function Output
else
tx(k) = newvarsx(k);
end
end
cx = simplify(cx);
cosFreqs = arrayfun(@char,cosFreqs,'UniformOutput',false);
Frequencies = arrayfun(@char,freqs,'UniformOutput',false);
Coefficients = num2cell(zeros(size(freqs)));
T = table(Frequencies,Coefficients,'RowNames',cosFreqs);
nonzeroCosFreqs = arrayfun(@char,tx,'UniformOutput',false).';
T(nonzeroCosFreqs,'Coefficients') = arrayfun(@char,cx,'UniformOutput',false).';
T.Properties.RowNames = {};
Observe that the expressions for the terms are symmetric in LO and RF.
T=25×2 table
Frequencies Coefficients
_______________ _____________________________________________
Verify Coefficients
As shown below, the output waveform is reconstructed from the coefficients and has an exact match
with the output.
simplify(f0 - (dot(tx,cx)))
ans = 0
3-153
3 Mathematics
The following shows the particular nonlinear transfer function analyzed above, in the time and
frequency domains, for certain values of the frequencies and voltage ratios. First, extract the data.
sample_values = struct('c1',0.4,'c2',1,'LO',800,'RF',13600,'Vo',1,'Is',1);
sample_input = subs(input,sample_values)
sample_input =
2 cos 800 t
+ cos 13600 t
5
sample_output = subs(f,sample_values)
sample_output =
127 cos 800 t cos 1600 t cos 2400 t cos 12000 t cos 12800 t 233 cos 13600 t
+ + + + +
250 25 375 50 5 200
cos 14400 t cos 15200 t cos 26400 t cos 27200 t cos 28000 t cos 40800 t 29
+ + + + + + +
5 50 20 4 20 24 100
sample_freqs = zeros(size(tx));
for k=1:numel(tx)
cosTerm = subs(tx(k),sample_values);
freq = simplify(acos(cosTerm),'IgnoreAnalyticConstraints',true)/t;
sample_freqs(k) = double(freq);
end
sample_heights = double(subs(cx,sample_values));
Then, use fplot and stem to plot the functions and their harmonic frequencies.
subplot(2,2,1);
fplot(sample_input,[0,0.01])
title Input
subplot(2,2,3);
stem([sample_values.LO, sample_values.RF],[sample_values.c1,sample_values.c2]);
title 'Input Frequencies'
subplot(2,2,2);
fplot(sample_output,[0,0.01])
title Output
subplot(2,2,4);
stem(sample_freqs,sample_heights)
title 'Output Frequencies'
3-154
Harmonic Analysis of Transfer Function Output
3-155
3 Mathematics
This example explores basic arbitrage concepts in a single-period, two-state asset portfolio. The
portfolio consists of a bond, a long stock, and a long call option on the stock.
This example symbolically derives the risk-neutral probabilities and call price for a single-period, two-
state scenario.
Create the symbolic variable r representing the risk-free rate over the period. Set the assumption
that r is a positive value.
syms r positive
Define the parameters for the beginning of a single period, time = 0. Here S0 is the stock price, and
C0 is the call option price with strike, K.
syms S0 C0 K positive
Now, define the parameters for the end of a period, time = 1. Label the two possible states at the
end of the period as U (the stock price over this period goes up) and D (the stock price over this
period goes down). Thus, SU and SD are the stock prices at states U and D, and CU is the value of the
call at state U. Note that SD < = K < = SU.
syms SU SD CU positive
3-156
Explore Single-Period Asset Arbitrage
The bond price at time = 0 is 1. Note that this example ignores friction costs.
prices =
1
S0
C0
Collect the payoffs of the portfolio at time = 1 into the payoff matrix. The columns of payoff
correspond to payoffs for states D and U. The rows correspond to payoffs for bond, stock, and call.
The payoff for the bond is 1 + r. The payoff for the call in state D is zero since it is not exercised
(because SD < = K).
payoff = [(1 + r), (1 + r); SD, SU; 0, CU]
payoff =
r+1 r+1
SD SU
0 CU
payoff =
r+1 r+1
SD SU
0 SU − K
Under no-arbitrage, eqns == 0 must always hold true with positive pU and pD.
eqns = payoff*[pD; pU] - prices
eqns =
pD r + 1 + pU r + 1 − 1
SD pD − S0 + SU pU
−C0 − pU K − SU
eqns =
pDrn + pUrn − 1
SD pDrn SU pUrn
− S0 +
r+1 r+1
pUrn K − SU
−C0 −
r+1
3-157
3 Mathematics
The unknown variables are pDrn, pUrn, and C0. Transform the linear system to a matrix form using
these unknown variables.
[A, b] = equationsToMatrix(eqns, [pDrn, pUrn, C0]')
A =
1 1 0
SD SU
0
r+1 r+1
K − SU
0 − −1
r+1
b =
1
S0
0
Using linsolve, find the solution for the risk-neutral probabilities and call price.
x = linsolve(A, b)
x =
S0 − SU + S0 r
SD − SU
S0 − SD + S0 r
−
SD − SU
K − SU S0 − SD + S0 r
SD − SU r + 1
Verify that under risk-neutral probabilities, x(1:2), the expected rate of return for the portfolio,
E_return equals the risk-free rate, r.
E_return = diag(prices)\(payoff - [prices,prices])*x(1:2);
E_return = simplify(subs(E_return, C0, x(3)))
E_return =
r
r
r
As an example of testing no-arbitrage violations, use the following values: r = 5%, S0 = 100, and K
= 100. For SU < 105, the no-arbitrage condition is violated because pDrn = xSol(1) is negative
(SU >= SD). Further, for any call price other than xSol(3), there is arbitrage.
xSol = simplify(subs(x, [r,S0,K], [0.05,100,100]))
xSol =
SU − 105
−
SD − SU
SD − 105
SD − SU
20 SD − 105 SU − 100
21 SD − SU
3-158
Explore Single-Period Asset Arbitrage
Plot the call price, C0 = xSol(3), for 50 <= SD <= 100 and 105 <= SU <= 150. Note that the
call is worth more when the "variance" of the underlying stock price is higher for example, SD = 50,
SU = 150.
fsurf(xSol(3), [50,100,105,150])
xlabel SD
ylabel SU
title 'Call Price'
Reference
3-159
3 Mathematics
This example shows how to derive analytical solutions for the inverse kinematics of the head chain of
a humanoid robot.
Describe the kinematics of the head-chain link (the link between the torso and the head) of the NAO
humanoid robot [1] using the Denavit-Hartenberg (DH) parameters and notations based on a study by
Kofinas et al. [2]. The following transformation defines the head-chain link.
where:
• ABase, 0 is the translation from the base (torso) to the joint or reference frame 0
• T0, 1 is the orientation of reference 1 relative to 0
• T1, 2 is the orientation of reference 2 relative to 1
• Rx is the roll rotation
• Ry is the pitch rotation
• A2, Head is the translation from reference 2 to the end-effector point (the head)
T(1: 3, 4) defines the coordinates of the head, which are xc, yc, zc.
In this example, you analytically solve the inverse kinematics problem by returning all orientations of
individual joints in the head-chain link given head coordinates of xc, yc, and zc within the reachable
space. Then, you convert the analytical results to purely numeric functions for efficiency.
Solving analytically (when doing so is possible) lets you perform computations in real time and avoid
singularities, which cause difficulty for numerical methods.
The function getKinematicChain returns the specific kinematic chain for the NAO robot in terms of
symbolic variables. For details on getKinematicChain, see the Helper Functions section.
kinChain = 'head';
dhInfo = getKinematicChain(kinChain);
T = dhInfo.T
T =
r11 r12 r13 xc
r21 r22 r23 yc
r31 r32 r33 zc
0 0 0 1
Express the forward kinematics transformation matrix T as the following sequence of products: T =
ABase0*T01*T12*Rx*Ry*A2Head. Define the individual matrices as follows.
3-160
Analytical Solutions of the Inverse Kinematics of a Humanoid Robot
ABase0 = dhInfo.ABase0
ABase0 =
100 0
010 0
0 0 1 NeckOffsetZ
000 1
T01 = dhInfo.T01
T01 =
cos θ1 −sin θ1 0 0
sin θ1 cos θ1 0 0
0 0 10
0 0 01
T12 = dhInfo.T12
T12 =
π π
cos θ2 − 0 −sin θ2 − 0
2 2
0 0 1 0
π π
−sin θ2 − −cos θ2 − 0 0
2 2
0 0 0 1
Rx = dhInfo.Rx
Rx =
1 0 0 0
0 0 −1 0
0 1 0 0
0 0 0 1
Ry = dhInfo.Ry
Ry =
0 0 1 0
0 1 0 0
−1 0 0 0
0 0 0 1
A2Head = dhInfo.A2Head
3-161
3 Mathematics
A2Head =
1 0 0 CameraX
010 0
0 0 1 CameraZ
000 1
The known parameters of this problem are CameraX, CameraZ, NeckOffsetZ, and the positions xc,
yc, and zc. The unknown parameters are θ1 and θ2. After finding θ1 and θ2, you can compute the
individual transformations of T. The robot can then achieve the desired position xc, yc, zc.
Although you can see these parameters in the transformation matrices, they do not exist as variables
in the MATLAB base workspace. This is because these parameters originate from a function.
Functions do not use the base workspace. Each function workspace is separate from the base
workspace and all other workspaces to protect the data integrity. Thus, to use these variables outside
of the function getKinematicChain, use syms to create them.
syms CameraX CameraZ NeckOffsetZ xc yc zc theta_1 theta_2 real;
Rewrite the equation T = ABase0*T01*T12*Rx*Ry*A2Head, separating the terms that describe the
torso and head movements of the robot: inv(T01)*inv(ABase0)*T = T12*Rx*Ry*A2Head.
Simplify the left and right sides of the equation, and define equations of interest matching the
expressions for coordinate positions.
LHS = simplify(inv(T01)*inv(ABase0)*T);
RHS = simplify(T12*Rx*Ry*A2Head);
eqns = LHS(1:3,end) - RHS(1:3,end)
eqns =
xc cos θ1 − CameraZ sin θ2 − CameraX cos θ2 + yc sin θ1
yc cos θ1 − xc sin θ1
zc − NeckOffsetZ − CameraZ cos θ2 + CameraX sin θ2
This system of equations contains two variables for which you want to find solutions, θ1 and θ2.
However, the equations also imply that you cannot arbitrarily choose xc, yc, and zc. Therefore, also
consider yc as a variable. All other unknowns of the system are symbolic parameters.
This example follows a typical algebraic approach for solving inverse kinematics problems [3]. The
idea is to get a compact representation of the solution, where the expression of each variable is in
terms of parameters and variables for which you already solved the equations. As a first step, find
either θ1 or θ2 in terms of the parameters. Then, express the other variable in terms of the known
variable and parameters. To do this, start by identifying the equation that has only one variable.
intersect(symvar(eqns(1)),[theta_1,theta_2,yc])
ans = θ1 θ2 yc
intersect(symvar(eqns(2)),[theta_1,theta_2,yc])
ans = θ1 yc
intersect(symvar(eqns(3)),[theta_1,theta_2,yc])
ans = θ2
3-162
Analytical Solutions of the Inverse Kinematics of a Humanoid Robot
The third equation contains only one variable, θ2. Solve this equation first.
[theta_2_sol,theta_2_params,theta_2_conds] = ...
solve(eqns(3),theta_2,'Real',true,'ReturnConditions',true)
theta_2_sol =
2 2 2
CameraX − CameraX + CameraZ − NeckOffsetZ + 2 NeckOffsetZ zc − zc2
2 π k − 2 atan
CameraZ − NeckOffsetZ + zc
2 2 2
CameraX + CameraX + CameraZ − NeckOffsetZ + 2 NeckOffsetZ zc − zc2
2 π k − 2 atan
CameraZ − NeckOffsetZ + zc
theta_2_params = k
theta_2_conds =
2 2 2
k ∈ ℤ ∧ CameraZ + zc ≠ NeckOffsetZ ∧ NeckOffsetZ − zc ≤ CameraX + CameraZ
2 2 2
k ∈ ℤ ∧ CameraZ + zc ≠ NeckOffsetZ ∧ NeckOffsetZ − zc ≤ CameraX + CameraZ
The solutions have an additive 2πk term with the parameter k. Without loss of generalization, you can
set k equal to 0 in the solutions and conditions.
theta_2_sol = subs(theta_2_sol,theta_2_params,0)
theta_2_sol =
2 2 2
CameraX − CameraX + CameraZ − NeckOffsetZ + 2 NeckOffsetZ zc − zc2
−2 atan
CameraZ − NeckOffsetZ + zc
2 2 2
CameraX + CameraX + CameraZ − NeckOffsetZ + 2 NeckOffsetZ zc − zc2
−2 atan
CameraZ − NeckOffsetZ + zc
for p = 1:numel(theta_2_conds)
theta_2_conds(p) = simplify(subs(theta_2_conds(p),theta_2_params,0));
end
Now solve for the variables θ1 and yc in terms of the variable θ2 and other symbolic parameters.
[theta_1_sol,yc_sol,yc_theta_1_params,yc_theta_1_conds] = ...
solve(eqns(1:2),theta_1,yc,'Real',true,'ReturnConditions',true);
theta_1_sol
theta_1_sol =
3-163
3 Mathematics
2 π k − σ1
σ2 + 2 π k
2 π k − σ2
π
2πk−
2
σ1 + 2 π k
2 atan x + 2 π k
π
+2πk
2
π
2πk−
2
π
+2πk
2
where
CameraX + xc CameraX − xc
σ1 = 2 atan
CameraX − xc
σ3 σ5 σ3
σ5 + 1
+ σ +1
5
σ2 = 2 atan
σ4
θ2
σ3 = − xc − CameraX + CameraX σ5 + xc σ5 − 2 CameraZ tan σ4
2
θ2
σ4 = CameraX + xc − CameraX σ5 + xc σ5 + 2 CameraZ tan
2
θ2 2
σ5 = tan
2
yc_sol
yc_sol =
3-164
Analytical Solutions of the Inverse Kinematics of a Humanoid Robot
CameraX + xc CameraX − xc
σ1
−σ1
CameraX
− CameraX + xc CameraX − xc
0
σ2
−σ2
−CameraX
where
θ2 2 θ2 2
− xc − CameraX + σ3 + xc tan 2 − σ4 CameraX + xc − σ3 + xc tan 2 + σ4
σ1 =
θ2 2
tan 2 +1
−σ3 + σ4 + CameraX
σ2 =
θ2 2
tan 2 +1
θ2 2
σ3 = CameraX tan
2
θ2
σ4 = 2 CameraZ tan
2
yc_theta_1_params
yc_theta_1_params = k x
The solutions have an additive 2πk term. Without loss of generalization, you can set k equal to 0 in
the solution for theta_1_sol and the conditions yc_theta_1_conds.
theta_1_sol = simplify(subs(theta_1_sol,yc_theta_1_params,[0,0]))
theta_1_sol =
3-165
3 Mathematics
CameraX + xc CameraX − xc
−2 atan
CameraX − xc
σ1
−σ1
π
−
2
CameraX + xc CameraX − xc
2 atan
CameraX − xc
0
π
2
π
−
2
π
2
where
for p = 1:numel(yc_theta_1_conds)
yc_theta_1_conds(p) = simplify(subs(yc_theta_1_conds(p),yc_theta_1_params,[0,0]));
end
A similar substitution is not required for yc_sol since there is no dependency on the parameters.
intersect(symvar(yc_sol),yc_theta_1_params)
ans =
Starting with an arbitrary set of known numeric values for θ1 and θ2, compute the numeric values of
the end-effector positions xc, yc, and zc with forward kinematics. Then, work backwards from xc,
yc, and zc to compute all possible numeric values for θ1 and θ2 using the inverse kinematics
expressions from the previous computation. Verify that one set of the inverse solutions matches the
starting set of numeric values for θ1 and θ2.
Set the fixed parameters for the robot. The values in this example are for illustration purposes only.
CameraXValue = 53.9;
CameraZValue = 67.9;
NeckOffsetZValue = -5;
Using forward computations, find the end-effector positions corresponding to the values θ1 and θ2.
Tfk = ABase0*T01*T12*Rx*Ry*A2Head;
xyz = Tfk(1:3,end);
3-166
Analytical Solutions of the Inverse Kinematics of a Humanoid Robot
For forward kinematics, specify two variables theta_1_known and theta_2_known that contain an
arbitrary starting set of values for θ1 and θ2.
theta_1_known = [pi/4,pi/6,pi/8,pi/10];
theta_2_known = [pi/8,-pi/12,pi/16,-pi/10];
numPts = numel(theta_1_known);
num_theta_2 = numel(theta_2_sol);
num_theta_1 = numel(theta_1_sol);
Note that there are potentially num_theta_1 solutions for each num_theta_2 solution.
1 Loop over (theta_1_known,theta_2_known). For each point, compute the end positions
x_known, y_known, and z_known, which are then "known".
2 Loop over the solutions for θ2 corresponding to x_known and z_known. For each solution, check
to see if the corresponding condition cond_theta_2 is valid. If the condition is valid, compute
the corresponding numeric solution theta_2_derived.
3 Loop over the solutions for θ1 corresponding to x_known, z_known, and theta_2_derived. For
each solution, check to see if the corresponding condition cond_theta_1 is valid. If the
condition is valid, check to see if y_derived numerically matches y_known within relative and
absolute tolerances through the condition cond_yc. If this condition is valid, then compute
theta_1_derived.
4 Collect the results in a table T for display purposes.
T = table([],[],[],[],'VariableNames',{'theta_1_known','theta_2_known',...
'theta_1_derived','theta_2_derived'});
3-167
3 Mathematics
T = vertcat(T,table(theta_1_known(ix1),theta_2_known(ix1),theta_1_derived,...
theta_2_derived,'VariableNames',T.Properties.VariableNames));
end
end
end
end
end
end
T
T=8×4 table
theta_1_known theta_2_known theta_1_derived theta_2_derived
_____________ _____________ _______________ _______________
References
1 SoftBank Robotics. NAO. https://www.aldebaran.com/en/nao.
2 Kofinas, N., E. Orfanoudakis, and M. G. Lagoudakis. "Complete Analytical Inverse Kinematics for
NAO." In 2013 13th International Conference on Autonomous Robot Systems. Lisbon, Portugal:
Robotica, 2013.
3 Kendricks, K. "Solving the Inverse Kinematic Robotics Problem: A Comparison Study of the
Denavit-Hartenberg Matrix and Groebner Basis Theory." Ph.D. Thesis. Auburn University,
Auburn, AL, 2007.
Helper Functions
function kinChain = getKinematicChain(link)
% This function returns the kinematic chain of the NAO humanoid robot
% represented using Denavit-Hartenberg (DH) parameters.
% The function uses as a reference the paper: Complete analytical inverse
% kinematics for NAO by Kofinas, N., Orfanoudakis, E., Lagoudakis, M.G.,
% 2013 13th International Conference on Autonomous Robot Systems
% (Robotica), Publication Year: 2013.
if nargin < 1
link = 'head';
end
% Notation: A, R, and T are the translation, rotation, and DH
% transformation matrices, respectively.
% Specify DH parameters for the desired end configuration.
syms r11 r12 r13 r21 r22 r23 r31 r32 r33 xc yc zc real;
R = [r11 r12 r13;r21 r22 r23;r31 r32 r33];
kinChain.T = [R,[xc;yc;zc];0,0,0,1];
switch link
3-168
Analytical Solutions of the Inverse Kinematics of a Humanoid Robot
3-169
3 Mathematics
end
function A = getA(vec)
% This function returns the translation matrix.
A = [1 0 0 vec(1);
0 1 0 vec(2);
0 0 1 vec(3);
0 0 0 1];
end
function R = getR(orientation,theta)
% This function returns the rotation matrix.
switch orientation
case 'x'
R = [1 0 0 0;
0 cos(theta) -sin(theta) 0;
0 sin(theta) cos(theta) 0
0 0 0 1];
case 'y'
R = [cos(theta) 0 sin(theta) 0;
0 1 0 0;
-sin(theta) 0 cos(theta) 0;
0 0 0 1];
case 'z'
R = [cos(theta) -sin(theta) 0 0;
sin(theta) cos(theta) 0 0;
0 0 1 0;
0 0 0 1];
end
end
function T = getT(a,alpha,d,theta)
% This function returns the Denavit-Hartenberg (DH) matrix.
T = [cos(theta),-sin(theta),0,a;
sin(theta)*cos(alpha),cos(theta)*cos(alpha),-sin(alpha),-sin(alpha)*d;
sin(theta)*sin(alpha),cos(theta)*sin(alpha),cos(alpha),cos(alpha)*d;
0,0,0,1];
end
See Also
Functions
simplify | solve | subs | double
3-170
Differentiation
Differentiation
To illustrate how to take derivatives using Symbolic Math Toolbox software, first create a symbolic
expression:
syms x
f = sin(5*x);
The command
diff(f)
y =
exp(x)*cos(x) - exp(x)*sin(x)
To find the derivative of g for a given value of x, substitute x for the value using subs and return a
numerical value using vpa. Find the derivative of g at x = 2.
vpa(subs(y,x,2))
ans =
-9.7937820180676088383807818261614
ans =
-2*exp(x)*sin(x)
You can get the same result by taking the derivative twice:
diff(diff(g))
ans =
-2*exp(x)*sin(x)
In this example, MATLAB software automatically simplifies the answer. However, in some cases,
MATLAB might not simplify an answer, in which case you can use the simplify command. For an
example of such simplification, see “More Examples” on page 3-173.
Note that to take the derivative of a constant, you must first define the constant as a symbolic
expression. For example, entering
c = sym('5');
diff(c)
3-171
3 Mathematics
returns
ans =
0
diff(5)
MATLAB returns
ans =
[]
syms s t
f = sin(s*t);
the command
diff(f,t)
ans =
s*cos(s*t)
diff(f,s)
which returns:
ans =
t*cos(s*t)
If you do not specify a variable to differentiate with respect to, MATLAB chooses a default variable.
Basically, the default variable is the letter closest to x in the alphabet. See the complete set of rules in
“Find a Default Symbolic Variable” on page 2-2. In the preceding example, diff(f) takes the
derivative of f with respect to t because the letter t is closer to x in the alphabet than the letter s is.
To determine the default variable that MATLAB differentiates with respect to, use symvar:
symvar(f,1)
ans =
t
diff(f,t,2)
3-172
Differentiation
ans =
-s^2*sin(s*t)
Note that diff(f,2) returns the same answer because t is the default variable.
More Examples
To further illustrate the diff command, define a, b, x, n, t, and theta in the MATLAB workspace by
entering
syms a b x n t theta
f diff(f)
syms x n diff(f)
f = x^n;
ans =
n*x^(n - 1)
syms a b t diff(f)
f = sin(a*t + b);
ans =
a*cos(b + a*t)
syms theta diff(f)
f = exp(i*theta);
ans =
exp(theta*1i)*1i
To differentiate the Bessel function of the first kind, besselj(nu,z), with respect to z, type
syms nu z
b = besselj(nu,z);
db = diff(b)
which returns
db =
(nu*besselj(nu,z))/z - besselj(nu + 1,z)
The diff function can also take a symbolic matrix as its input. In this case, the differentiation 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 command
diff(A)
3-173
3 Mathematics
returns
ans =
[ -a*sin(a*x), a*cos(a*x)]
[ -a*cos(a*x), -a*sin(a*x)]
You can also perform differentiation of a vector function with respect to a vector argument. Consider
the transformation from Cartesian coordinates (x, y, z) to spherical coordinates (r, λ, φ) as given by
x = rcosλcosφ, y = rcosλsinϕ, and z = rsinλ. Note that λ corresponds to elevation or latitude while φ
denotes azimuth or longitude.
To calculate the Jacobian matrix, J, of this transformation, use the jacobian function. The
mathematical notation for J is
∂(x, y, z)
J= .
∂ r, λ, φ
For the purposes of toolbox syntax, use l for λ and f for φ. The commands
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])
returns
detJ =
-r^2*cos(l)
The arguments of the jacobian function can be column or row vectors. Moreover, since the
determinant of the Jacobian is a rather complicated trigonometric expression, you can use simplify
to make trigonometric substitutions and reductions (simplifications).
3-174
Differentiation
d f
2 diff(f,b,2)
2
db
∂(r, t) J = jacobian([r; t],[u; v])
J=
∂(u, v)
See Also
diff | int | jacobian | gradient | curl | laplacian | functionalDerivative
External Websites
• Calculus Derivatives (MathWorks Teaching Resources)
3-175
3 Mathematics
Integration
If f is a symbolic expression, then
int(f)
attempts to find another symbolic expression, F, so that diff(F) = f. That is, int(f) returns the
indefinite integral or antiderivative of f (provided one exists in closed form). Similar to
differentiation,
int(f,v)
uses the symbolic object v as the variable of integration, rather than the variable determined by
symvar. See how int works by looking at this table.
0
∫ sin(2x)dx = 1 pi/2)
Nevertheless, in many cases, MATLAB can perform symbolic integration successfully. For example,
create the symbolic variables
syms a b theta x y n u z
f int(f)
syms x n int(f)
f = x^n;
ans =
piecewise(n == -1, log(x), n ~= -1,...
x^(n + 1)/(n + 1))
3-176
Integration
f int(f)
syms y int(f)
f = y^(-1);
ans =
log(y)
syms x n int(f)
f = n^x;
ans =
n^x/log(n)
syms a b theta int(f)
f = sin(a*theta+b);
ans =
-cos(b + a*theta)/a
syms u int(f)
f = 1/(1+u^2);
ans =
atan(u)
syms x int(f)
f = exp(-x^2);
ans =
(pi^(1/2)*erf(x))/2
In the last example, exp(-x^2), there is no formula for the integral involving standard calculus
expressions, such as trigonometric and exponential functions. In this case, MATLAB returns an
answer in terms of the error function erf.
If MATLAB is unable to find an answer to the integral of a function f, it just returns int(f).
int(f, v, a, b)
∫
b
f (v)dv
a
f a, b int(f, a, b)
syms x a = 0; int(f, a, b)
f = x^7; b = 1;
ans =
1/8
syms x a = 1; int(f, a, b)
f = 1/x; b = 2;
ans =
log(2)
syms x a = 0; int(f, a, b)
f = log(x)*sqrt(x); b = 1;
ans =
-4/9
3-177
3 Mathematics
f a, b int(f, a, b)
syms x a = 0; int(f, a, b)
f = exp(-x^2); b = inf;
ans =
pi^(1/2)/2
syms z a = 0; int(f, a, b)
f = besselj(1,z)^2; b = 1;
ans =
hypergeom([3/2, 3/2],...
[2, 5/2, 3], -1)/12
For the Bessel function (besselj) example, it is possible to compute a numerical approximation to
the value of the integral, using the double function. The commands
syms z
a = int(besselj(1,z)^2,0,1)
return
a =
hypergeom([3/2, 3/2], [2, 5/2, 3], -1)/12
a = double(a)
returns
a =
0.0717
is the positive, bell shaped curve that tends to 0 as x tends to ±∞. You can create an example of this
curve, for a = 1/2.
syms x
a = sym(1/2);
f = exp(-a*x^2);
fplot(f)
3-178
Integration
−∞
∫e −ax2dx
without assigning a value to a, MATLAB assumes that a represents a complex number, and therefore
returns a piecewise answer that depends on the argument of a. If you are only interested in the case
when a is a positive real number, use assume to set an assumption on a:
syms a
assume(a > 0)
Now you can calculate the preceding integral using the commands
syms x
f = exp(-a*x^2);
int(f, x, -inf, inf)
This returns
ans =
pi^(1/2)/a^(1/2)
3-179
3 Mathematics
−∞
∫a 1
2 + x2
dx
syms a x
f = 1/(a^2 + x^2);
F = int(f, x, -inf, inf)
Use syms to clear all the assumptions on variables. For more information about symbolic variables
and assumptions on them, see “Use Assumptions on Symbolic Variables” on page 1-41.
F =
(pi*signIm(1i/a))/a
To evaluate F at a = 1 + i, enter
g = subs(F, 1 + i)
g =
pi*(1/2 - 1i/2)
double(g)
ans =
1.5708 - 1.5708i
3-180
Integration
syms u
f = besseli(5,25*x).*exp(-x*25);
fun = @(u)besseli(5,25*u).*exp(-u*25);
usingVpaintegral =
0.688424
See Also
int | diff | vpaintegral
External Websites
• Calculus Integrals (MathWorks Teaching Resources)
3-181
3 Mathematics
Taylor Series
The statements
syms x
f = 1/(5 + 4*cos(x));
T = taylor(f, 'Order', 8)
return
T =
(49*x^6)/131220 + (5*x^4)/1458 + (2*x^2)/81 + 1/9
which is all the terms up to, but not including, order eight in the Taylor series for f(x):
∞ (n)
nf (a)
∑ (x − a)
n!
.
n=0
These commands
syms x
g = exp(x*sin(x));
t = taylor(g, 'ExpansionPoint', 2, 'Order', 12);
generate the first 12 nonzero terms of the Taylor series for g about x = 2.
size(char(t))
ans =
1 99791
to find that t has about 100,000 characters in its printed form. In order to proceed with using t, first
simplify its presentation:
t = simplify(t);
size(char(t))
ans =
1 6988
Next, plot these functions together to see how well this Taylor approximation compares to the actual
function g:
xd = 1:0.05:3;
yd = subs(g,x,xd);
fplot(t, [1, 3])
hold on
plot(xd, yd, 'r-.')
title('Taylor approximation vs. actual function')
legend('Taylor','Function')
3-182
Taylor Series
Special thanks is given to Professor Gunnar Bäckstrøm of UMEA in Sweden for this example.
3-183
3 Mathematics
1 Declare equations.
2 Solve equations.
3 Substitute values.
4 Plot results.
5 Analyze results.
Fourier transform can be used to solve ordinary and partial differential equations. For example, you
can model the deflection of an infinitely long beam resting on an elastic foundation under a point
force. A corresponding real-world example is railway tracks on a foundation. The railway tracks are
the infinitely long beam while the foundation is elastic.
3-184