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
Fourier and Inverse Fourier Transforms
Let
Define the function y(x) and the variables. Assume E, I, and k are positive.
syms Y(x) w E I k f
assume([E I k] > 0)
u = symunit;
Eu = E*u.Pa; % Pascal
Iu = I*u.m^4; % meter^4
ku = k*u.N/u.m^2; % Newton/meter^2
X = x*u.m;
F = f*u.N/u.m;
eqn(x) =
diff(Y(x), x, x, x, x)*(1/[m]^4) + ((k*Y(x))/(E*I))*([N]/([Pa]*[m]^6)) == ...
(f/(E*I))*([N]/([Pa]*[m]^5))
eqn = subs(eqn,f,dirac(x))
eqn(x) =
diff(Y(x), x, x, x, x)*(1/[m]^4) + ((k*Y(x))/(E*I))*([N]/([Pa]*[m]^6)) == ...
(dirac(x)/(E*I))*([N]/([Pa]*[m]^5))
3-185
3 Mathematics
Solve Equations
Calculate the Fourier transform of eqn by using fourier on both sides of eqn. The Fourier transform
converts differentiation into exponents of w.
eqnFT =
w^4*fourier(Y(x), x, w)*(1/[m]^4) + ((k*fourier(Y(x), x, w))/(E*I))*([N]/([Pa]*[m]^6)) ...
== (1/(E*I))*([N]/([Pa]*[m]^5))
eqnFT =
fourier(Y(x), x, w) == (1/(E*I*w^4*[Pa]*[m]^2 + k*[N]))*[N]*[m]
Calculate Y(x) by calculating the inverse Fourier transform of the right side. Simplify the result.
YSol = ifourier(rhs(eqnFT));
YSol = simplify(YSol)
YSol =
((exp(-(2^(1/2)*k^(1/4)*abs(x))/(2*E^(1/4)*I^(1/4)))*sin((2*2^(1/2)*k^(1/4)*abs(x) + ...
pi*E^(1/4)*I^(1/4))/(4*E^(1/4)*I^(1/4))))/(2*E^(1/4)*I^(1/4)*k^(3/4)))*[m]
Check that YSol has the correct dimensions by substituting YSol into eqn and using the
checkUnits function. checkUnits returns logical 1 (true), meaning eqn now has compatible units
of the same physical dimensions.
checkUnits(subs(eqn,Y,YSol))
ans =
struct with fields:
Consistent: 1
Compatible: 1
YSol = separateUnits(YSol)
YSol =
(exp(-(2^(1/2)*k^(1/4)*abs(x))/(2*E^(1/4)*I^(1/4)))*sin((2*2^(1/2)*k^(1/4)*abs(x) + ...
pi*E^(1/4)*I^(1/4))/(4*E^(1/4)*I^(1/4))))/(2*E^(1/4)*I^(1/4)*k^(3/4))
Substitute Values
Use the values E = 106 Pa, I = 10-3 m4, and k = 106 N/m2. Substitute these values into YSol and
convert to floating point by using vpa with 16 digits of accuracy.
YSol =
0.0000158113883008419*exp(-2.23606797749979*abs(x))*sin(2.23606797749979*abs(x) + ...
0.7853981633974483)
3-186
Fourier and Inverse Fourier Transforms
Plot Results
fplot(YSol)
xlabel('x')
ylabel('Deflection y(x)')
Analyze Results
The plot shows that the deflection of a beam due to a point force is highly localized. The deflection is
greatest at the point of impact and then decreases quickly. The symbolic result enables you to analyze
the properties of the result, which is not possible with numeric results.
Notice that YSol is a product of terms. The term with sin shows that the response is vibrating
oscillatory behavior. The term with exp shows that the oscillatory behavior is quickly damped by the
exponential decay as the distance from the point of impact increases.
See Also
External Websites
• Fourier Analysis (MathWorks Teaching Resources)
3-187
3 Mathematics
Solve differential equations of an RLC circuit by using Laplace transforms in Symbolic Math
Toolbox™ with this workflow. For simple examples on the Laplace transform, see laplace and
ilaplace.
∫
∞
Fs = f t e−tsdt .
0
Symbolic workflows keep calculations in the natural symbolic form instead of numeric form. This
approach helps you understand the properties of your solution and use exact symbolic values. You
substitute numbers in place of symbolic variables only when you require a numeric result or you
cannot continue symbolically. For details, see “Choose Numeric or Symbolic Arithmetic” on page 2-
32. Typically, the steps are:
1 Declare equations.
2 Solve equations.
3 Substitute values.
4 Plot results.
5 Analyze results.
Declare Equations
You can use the Laplace transform to solve differential equations with initial conditions. For example,
you can solve resistance-inductor-capacitor (RLC) circuits, such as this circuit.
3-188
Solve Differential Equations of RLC Circuit Using Laplace Transform
Apply Kirchhoff's voltage and current laws to get the following equations.
I1 = I2 + I3
dI1
L + I1R1 + I2R2 = 0
dt
Q
E t + I2R2 − − I3R3 = 0
C
Substitute the relation I3 = dQ/dt (which is the rate of the capacitor being charged) to the above
equations to get the differential equations for the RLC circuit.
dI1 R2 dQ R1 + R2
− = − I1
dt L dt L
dQ 1 Q R2
= Et − + I
dt R2 + R3 C R2 + R3 1
Declare the variables. Because the physical quantities have positive values, set the corresponding
assumptions on the variables. Let E(t) be an alternating voltage of 1 V.
3-189
3 Mathematics
dI1 = diff(I1,t);
dQ = diff(Q,t);
eqn1 = dI1 - (R(2)/L)*dQ == -(R(1)+R(2))/L*I1
eqn1(t) =
∂
∂ R2 ∂t Q t I1 t R1 + R2
I1 t − =−
∂t L L
eqn2(t) =
Qt
∂ sin t − C R2 I1 t
Qt = +
∂t R2 + R3 R2 + R3
Solve Equations
eqn1LT =
R2 Q 0 − s laplace Q t , t, s R1 + R2 laplace I1 t , t, s
s laplace I1 t , t, s − I1 0 + =−
L L
eqn2LT = laplace(eqn2,t,s)
eqn2LT =
C
− laplace Q t , t, s
R2 laplace I1 t , t, s s2 + 1
s laplace Q t , t, s − Q 0 = +
R2 + R3 C R2 + R3
The function solve solves only for symbolic variables. Therefore, to use solve, first substitute
laplace(I1(t),t,s) and laplace(Q(t),t,s) with the variables I1_LT and Q_LT.
syms I1_LT Q_LT
eqn1LT = subs(eqn1LT,[laplace(I1,t,s) laplace(Q,t,s)],[I1_LT Q_LT])
eqn1LT =
R2 Q 0 − QLT s I1, LT R1 + R2
I1, LT s − I1 0 + =−
L L
eqn2LT =
C
QLT − 2
I1, LT R2 s +1
QLT s − Q 0 = −
R2 + R3 C R2 + R3
I1_LT =
L I1 0 − R2 Q 0 + C R2 s + L s2 I1 0 − R2 s2 Q 0 + C L R2 s3 I1 0 + C L R3 s3 I1 0 + C L R2 s I1 0 + C L R3 s I1 0
s2 + 1 R1 + R2 + L s + C L R2 s2 + C L R3 s2 + C R1 R2 s + C R1 R3 s + C R2 R3 s
3-190
Solve Differential Equations of RLC Circuit Using Laplace Transform
Q_LT =
C R1 + R2 + L s + L R2 I1 0 + R1 R2 Q 0 + R1 R3 Q 0 + R2 R3 Q 0 + L R2 s2 I1 0 + L R2 s3 Q 0 + L R3 s3 Q 0 + R1 R2 s2 Q
s2 + 1 R1 + R2 + L s + C L R2 s2 + C L R3 s2 + C R1 R2 s + C R1 R3 s +
Compute I1 and Q by computing the inverse Laplace transform of I1_LT and Q_LT. Simplify the
result. Suppress the output because it is long.
I1sol = ilaplace(I1_LT,s,t);
Qsol = ilaplace(Q_LT,s,t);
I1sol = simplify(I1sol);
Qsol = simplify(Qsol);
Substitute Values
Before plotting the result, substitute symbolic variables by the numeric values of the circuit elements.
Let R1 = 4 Ω, R2 = 2 Ω, R3 = 3 Ω, C = 1/4 F, L = 1 . 6 H. Assume that the initial current is I1(0) = 2 A
and the initial charge is Q(0) = 2 C.
I1sol =
1761 t
81 t 742529 1761 sinh
1761 t 40
16122 e− 40 cosh 40
− 14195421
200 cos t 405 sin t
+ +
8161 8161 8161
Qsol = subs(Qsol,vars,values)
Qsol =
1761 t
81 t 1109425 1761 sinh
1761 t 40
17377 e− 40 cosh 40
+ 30600897
924 sin t 1055 cos t
− +
8161 8161 8161
Plot Results
Plot the current I1sol and charge Qsol. Show both the transient and steady state behavior by using
two different time intervals: 0 ≤ t ≤ 15 and 2 ≤ t ≤ 25.
subplot(2,2,1)
fplot(I1sol,[0 15])
title('Current')
ylabel('I1(t)')
xlabel('t')
subplot(2,2,2)
fplot(Qsol,[0 15])
title('Charge')
ylabel('Q(t)')
xlabel('t')
subplot(2,2,3)
fplot(I1sol,[2 25])
title('Current')
3-191
3 Mathematics
ylabel('I1(t)')
xlabel('t')
text(3,-0.1,'Transient')
text(15,-0.07,'Steady State')
subplot(2,2,4)
fplot(Qsol,[2 25])
title('Charge')
ylabel('Q(t)')
xlabel('t')
text(3,0.35,'Transient')
text(15,0.22,'Steady State')
Analyze Results
Initially, the current and charge decrease exponentially. However, over the long term, they are
oscillatory. These behaviors are called "transient" and "steady state", respectively. With the symbolic
result, you can analyze the result's properties, which is not possible with numeric results.
Visually inspect I1sol and Qsol. They are a sum of terms. Find the terms by using children. Then,
find the contributions of the terms by plotting them over [0 15]. The plots show the transient and
steady state terms.
I1terms = children(I1sol);
I1terms = [I1terms{:}];
Qterms = children(Qsol);
Qterms = [Qterms{:}];
3-192
Solve Differential Equations of RLC Circuit Using Laplace Transform
figure;
subplot(1,2,1)
fplot(I1terms,[0 15])
ylim([-0.5 2.5])
title('Current terms')
subplot(1,2,2)
fplot(Qterms,[0 15])
ylim([-0.5 2.5])
title('Charge terms')
The plots show that I1sol has a transient and steady state term, while Qsol has a transient and two
steady state terms. From visual inspection, notice I1sol and Qsol have a term containing the exp
function. Assume that this term causes the transient exponential decay. Separate the transient and
steady state terms in I1sol and Qsol by checking terms for exp using has.
I1transient = I1terms(has(I1terms,'exp'))
I1transient =
1761 t
81 t 742529 1761 sinh
1761 t 40
16122 e− 40 cosh 40
− 14195421
8161
I1steadystate = I1terms(~has(I1terms,'exp'))
I1steadystate =
3-193
3 Mathematics
Similarly, separate Qsol into transient and steady state terms. This result demonstrates how symbolic
calculations help you analyze your problem.
Qtransient = Qterms(has(Qterms,'exp'))
Qtransient =
1761 t
81 t 1109425 1761 sinh
1761 t 40
17377 e− 40 cosh 40
+ 30600897
8161
Qsteadystate = Qterms(~has(Qterms,'exp'))
Qsteadystate =
1055 cos t 924 sin t
−
8161 8161
3-194
Solve Difference Equations Using Z-Transform
Solve difference equations by using Z-transforms in Symbolic Math Toolbox™ with this workflow. For
simple examples on the Z-transform, see ztrans and iztrans.
Definition: Z-transform
Symbolic workflows keep calculations in the natural symbolic form instead of numeric form. This
approach helps you understand the properties of your solution and use exact symbolic values. You
substitute numbers in place of symbolic variables only when you require a numeric result or you
cannot continue symbolically. For details, see “Choose Numeric or Symbolic Arithmetic” on page 2-
32. Typically, the steps are:
1 Declare equations.
2 Solve equations.
3 Substitute values.
4 Plot results.
5 Analyze results.
Declare Equations
You can use the Z-transform to solve difference equations, such as the well-known "Rabbit Growth"
problem. If a pair of rabbits matures in one year, and then produces another pair of rabbits every
year, the rabbit population p(n) at year n is described by this difference equation.
p n+2 =p n+1 +p n
Declare the equation as an expression assuming the right side is 0. Because n represents years,
assume that n is a positive integer. This assumption simplifies the results.
syms p(n) z
assume(n>=0 & in(n,"integer"))
f = p(n+2) - p(n+1) - p(n)
f = p n+2 −p n+1 −p n
Solve Equations
fZT = ztrans(f,n,z)
3-195
3 Mathematics
The function solve solves only for symbolic variables. Therefore, to use solve, first substitute
ztrans(p(n),n,z) with the variables pZT.
syms pZT
fZT = subs(fZT,ztrans(p(n),n,z),pZT)
pZT = solve(fZT,pZT)
pZT =
z p 1 − z p 0 + z2 p 0
−
−z2 + z + 1
Calculate p(n) by computing the inverse Z-transform of pZT. Simplify the result.
pSol = iztrans(pZT,z,n);
pSol = simplify(pSol)
pSol =
2−n n−1 1−n n−1
n/2 π 1 2 5 5+1 σ1 22 5 1− 5 σ1
2 −1 p 1 cos n + asin i + −
2 2 5 5
where
p0
σ1 = −p 1
2
Substitute Values
To plot the result, first substitute the values of the initial conditions. Let p(0) and p(1) be 1 and 2,
respectively.
pSol =
2−n n−1 1−n n−1
n/2 π 1 32 5 5+1 32 5 1− 5
4 −1 cos n + asin i − +
2 2 10 5
Plot Results
nValues = 1:10;
pSolValues = subs(pSol,n,nValues);
pSolValues = double(pSolValues);
pSolValues = real(pSolValues);
stem(nValues,pSolValues)
title("Rabbit Population")
xlabel("Years (n)")
ylabel("Population p(n)")
grid on
3-196
Solve Difference Equations Using Z-Transform
Analyze Results
The plot shows that the solution appears to increase exponentially. However, because the solution
pSol contains many terms, finding the terms that produce this behavior requires analysis.
Because all the functions in pSol can be expressed in terms of exp, rewrite pSol to exp. Simplify
the result by using simplify with 80 additional simplification steps. Now, you can analyze pSol.
pSol = rewrite(pSol,"exp");
pSol = simplify(pSol,"Steps",80)
pSol =
n n n n
22 2 1− 5 6 5 5+1 6 5 1− 5
n
+ n
− n
− n
5−1 2 52 5+1 52 5−1
Visually inspect pSol. Notice that pSol is a sum of terms. Each term is a ratio that can increase or
decrease as n increases. For each term, you can confirm this hypothesis in several ways:
For simplicity, use the third approach. Calculate the terms at n = 100, and then verify the approach.
First, find the individual terms by using children, substitute for n, and convert to double.
pSolTerms = children(pSol);
pSolTerms = [pSolTerms{:}];
3-197
3 Mathematics
pSolTermsDbl = subs(pSolTerms,n,100);
pSolTermsDbl = double(pSolTermsDbl)
pSolTermsDbl = 1×4
1021 ×
The result shows that some terms are 0 while other terms have a large magnitude. Hypothesize that
the large-magnitude terms produce the exponential behavior. Approximate pSol with these terms.
pApprox =
n n
22 6 5 5+1
n
− n
5−1 52 5+1
Verify the hypothesis by plotting the approximation error between pSol and pApprox. As expected,
the error goes to 0 as n increases. This result demonstrates how symbolic calculations help you
analyze your problem.
3-198
Solve Difference Equations Using Z-Transform
References
[1] Andrews, L.C., Shivamoggi, B.K., Integral Transforms for Engineers and Applied Mathematicians,
Macmillan Publishing Company, New York, 1986
[2] Crandall, R.E., Projects in Scientific Computation, Springer-Verlag Publishers, New York, 1994
[3] Strang, G., Introduction to Applied Mathematics, Wellesley-Cambridge Press, Wellesley, MA, 1986
3-199
3 Mathematics
Symbolic Summation
Symbolic Math Toolbox provides two functions for calculating sums:
• sum finds the sum of elements of symbolic vectors and matrices. Unlike the MATLAB sum, the
symbolic sum function does not work on multidimensional arrays. For details, follow the MATLAB
sum page.
• symsum finds the sum of a symbolic series.
In this section...
“Comparing symsum and sum” on page 3-200
“Computational Speed of symsum versus sum” on page 3-200
“Output Format Differences Between symsum and sum” on page 3-201
10
1
Consider the definite sum S = ∑ 2
. First, find the terms of the definite sum by substituting the
k=1k
index values for k in the expression. Then, sum the resulting vector using sum.
syms k
f = 1/k^2;
V = subs(f, k, 1:10)
S_sum = sum(V)
V =
[ 1, 1/4, 1/9, 1/16, 1/25, 1/36, 1/49, 1/64, 1/81, 1/100]
S_sum =
1968329/1270080
Find the same sum by using symsum by specifying the index and the summation limits. sum and
symsum return identical results.
S_symsum =
1968329/1270080
You can demonstrate that symsum can be faster than sum by summing a large definite series such as
100000
2
S= ∑ k .
k=1
3-200
Symbolic Summation
syms k
tic
sum(sym(1:100000).^2);
toc
tic
symsum(k^2, k, 1, 100000);
toc
syms x
assume(x > 1)
S_sum = sum(x.^(1:10))
S_symsum = symsum(x^k, k, 1, 10)
S_sum =
x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x
S_symsum =
x^11/(x - 1) - x/(x - 1)
Show that the outputs are equal by using isAlways. The isAlways function returns logical 1
(true), meaning that the outputs are equal.
isAlways(S_sum == S_symsum)
ans =
logical
1
assume(x, 'clear')
3-201
3 Mathematics
Padé Approximant
The Padé approximant of order [m, n] approximates the function f(x) around x = x0 as
m
a0 + a1 x − x0 + ... + am x − x0
n
.
1 + b1 x − x0 + ... + bn x − x0
The Padé approximant is a rational function formed by a ratio of two power series. Because it is a
rational function, it is more accurate than the Taylor series in approximating functions with poles.
The Padé approximant is represented by the Symbolic Math Toolbox function pade.
When a pole or zero exists at the expansion point x = x0, the accuracy of the Padé approximant
decreases. To increase accuracy, an alternative form of the Padé approximant can be used which is
p m
x − x0 a0 + a1 x − x0 + ... + am x − x0
n
.
1 + b1 x − x0 + ... + bn x − x0
The pade function returns the alternative form of the Padé approximant when you set the
OrderMode input argument to Relative.
The Padé approximant is used in control system theory to model time delays in the response of the
system. Time delays arise in systems such as chemical and transport processes where there is a delay
between the input and the system response. When these inputs are modeled, they are called dead-
time inputs. This example shows how to use the Symbolic Math Toolbox to model the response of a
first-order system to dead-time inputs using Padé approximants.
dy t
τ + y t = ax t .
dt
F = laplace(F,t,s)
Assume the response of the system at t = 0 is 0. Use subs to substitute for y(0) = 0.
F = subs(F,y(0),0)
F = simplify(F)
F = s τ + 1 laplace y t , t, s = a laplace x t , t, s
For readability, replace the Laplace transforms of x(t) and y(t) with xS(s) and yS(s).
3-202
Padé Approximant
F = yS s s τ + 1 = a xS s
The Laplace transform of the transfer function is yS(s)/xS(s). Divide both sides of the equation by
xS(s) and use subs to replace yS(s)/xS(s) with H(s).
F = F/xS(s);
F = subs(F,yS(s)/xS(s),H(s))
F = H s sτ+1 = a
Solve the equation for H(s). Substitute for H(s) with a dummy variable, solve for the dummy
variable using solve, and assign the solution back to H(s).
F = subs(F,H(s),tmp);
H(s) = solve(F,tmp)
H(s) =
a
sτ+1
The input to the first-order system is a time-delayed step input. To represent a step input, use
heaviside. Delay the input by three time units. Find the Laplace transform using laplace.
step = heaviside(t - 3);
step = laplace(step)
step =
e−3 s
s
Find the response of the system, which is the product of the transfer function and the input.
y = H(s)*step
y =
a e−3 s
s sτ+1
To allow plotting of the response, set parameters a and tau to their values. For a and tau, choose
values 1 and 3, respectively.
y = subs(y,[a tau],[1 3]);
y = ilaplace(y,s);
Find the Padé approximant of order [2 2] of the step input using the Order input argument to
pade.
stepPade22 = pade(step,'Order',[2 2])
stepPade22 =
3 s2 − 4 s + 2
2s s+1
Find the response to the input by multiplying the transfer function and the Padé approximant of the
input.
yPade22 = H(s)*stepPade22
3-203
3 Mathematics
yPade22 =
a 3 s2 − 4 s + 2
2s sτ+1 s+1
yPade22 = ilaplace(yPade22,s)
yPade22 =
s
− 2
9 a e−s a e τ 2 τ + 4 τ + 3
a+ −
2τ−2 τ 2τ−2
To plot the response, set parameters a and tau to their values of 1 and 3, respectively.
yPade22 =
s
9 e−s 11 e− 3
− +1
4 4
Plot the response of the system y and the response calculated from the Padé approximant yPade22.
hold on
grid on
fplot([y yPade22],[0 20])
title('Pade Approximant for dead-time step input')
legend('Response to dead-time step input',...
'Pade approximant [2 2]',...
'Location', 'Best')
3-204
Padé Approximant
The [2 2] Padé approximant does not represent the response well because a pole exists at the
expansion point of 0. To increase the accuracy of pade when there is a pole or zero at the expansion
point, set the OrderMode input argument to Relative and repeat the steps. For details, see pade.
stepPade22Rel =
3 s2 − 6 s + 4
s 3 s2 + 6 s + 4
yPade22Rel = H(s)*stepPade22Rel
yPade22Rel =
a 3 s2 − 6 s + 4
s s τ + 1 3 s2 + 6 s + 4
yPade22Rel = ilaplace(yPade22Rel)
yPade22Rel =
t 3t 3t 36 a − 72 a τ
a e− τ 4 τ2 + 6 τ + 3 12 a τ e−t cos 3 − 3 sin 3 36 a τ
+1
a− +
σ1 σ1
where
σ1 = 4 τ2 − 6 τ + 3
3-205
3 Mathematics
yPade22Rel =
3t
2 3 sin
3t 3
12 e−t cos 3
+ 3 t
19 e− 3
− +1
7 7
The accuracy of the Padé approximant can also be increased by increasing its order. Increase the
order to [4 5] and repeat the steps. The [n-1 n] Padé approximant is better at approximating the
response at t = 0 than the [n n] Padé approximant.
stepPade45 = pade(step,'Order',[4 5])
stepPade45 =
27 s4 − 180 s3 + 540 s2 − 840 s + 560
s 27 s4 + 180 s3 + 540 s2 + 840 s + 560
yPade45 = H(s)*stepPade45
yPade45 =
a 27 s4 − 180 s3 + 540 s2 − 840 s + 560
s s τ + 1 27 s4 + 180 s3 + 540 s2 + 840 s + 560
3-206
Padé Approximant
yPade45 =
27 s4 − 180 s3 + 540 s2 − 840 s + 560
s 3 s + 1 27 s4 + 180 s3 + 540 s2 + 840 s + 560
yPade45 = ilaplace(yPade45)
yPade45 =
eσ2 t σ2 et σ2 σ22
4
101520 ∑k = 1 4 et σ2 4
294120 ∑k = 1 46440
t 172560 ∑k = 1 σ
12 90 σ2 + 45 σ22 + 9 σ23 + 70 2721 e− 3 1
σ1
− + + +
143 1001 143 1001
where
σ1 = 12 9 σ23 + 45 σ22 + 90 σ2 + 70
20 z3 280 z 560
σ2 = root z4 + + 20 z2 + + , z, k
3 9 27
yPade45 = vpa(yPade45)
3-207
3 Mathematics
3-208
Limits
Limits
The fundamental idea in calculus is to make calculations on functions as a variable “gets close to” or
approaches a certain value. Recall that the definition of the derivative is given by a limit
f (x + h) − f (x)
f ′(x) = lim ,
h 0 h
provided this limit exists. Symbolic Math Toolbox software enables you to calculate the limits of
functions directly. The commands
syms h n x
limit((cos(x+h) - cos(x))/h, h, 0)
which return
ans =
-sin(x)
and
which returns
ans =
exp(x)
illustrate two of the most important limits in mathematics: the derivative (in this case of cos(x)) and
the exponential function.
One-Sided Limits
You can also calculate one-sided limits with Symbolic Math Toolbox software. For example, you can
calculate the limit of x/|x|, whose graph is shown in the following figure, as x approaches 0 from the
left or from the right.
syms x
fplot(x/abs(x), [-1 1], 'ShowPoles', 'off')
3-209
3 Mathematics
x
lim ,
− x
x 0
enter
syms x
limit(x/abs(x), x, 0, 'left')
ans =
-1
x
lim = 1,
+ x
x 0
enter
syms x
limit(x/abs(x), x, 0, 'right')
ans =
1
3-210
Limits
Since the limit from the left does not equal the limit from the right, the two- sided limit does not exist.
In the case of undefined limits, MATLAB returns NaN (not a number). For example,
syms x
limit(x/abs(x), x, 0)
returns
ans =
NaN
Observe that the default case, limit(f) is the same as limit(f,x,0). Explore the options for the
limit command in this table, where f is a function of the symbolic object x.
3-211
3 Mathematics
This example describes how to analyze a simple function to find its asymptotes, maximum, minimum,
and inflection point.
Define a Function
3x2 + 6x − 1
f x = .
x2 + x − 3
f =
3 x2 + 6 x − 1
x2 + x − 3
Plot the function by using fplot. The fplot function automatically shows vertical asymptotes.
fplot(f)
3-212
Find Asymptotes, Critical, and Inflection Points
Find Asymptotes
To find the horizontal asymptote of f mathematically, take the limit of f as x approaches positive
infinity.
limit(f,Inf)
ans = 3
The limit as x approaches negative infinity is also 3. This result means the line y = 3 is a horizontal
asymptote to f .
To find the vertical asymptotes of f , set the denominator equal to 0 and solve it.
roots = solve(denom)
roots =
13 1
− −
2 2
13 1
−
2 2
−1 − 13
x= 2
and
−1 + 13
x= 2
.
You can see from the graph that f has a local maximum between the points x = – 2 and x = 0. It also
has a local minimum between x = – 6 and x = – 2. To find the x-coordinates of the maximum and
minimum, first take the derivative of f .
f1 = diff(f)
f1 =
6x+6 2 x + 1 3 x2 + 6 x − 1
−
x2 + x − 3 x2 + x − 3
2
f1 =
3 x2 + 16 x + 17
− 2
x2 + x − 3
Next, set the derivative equal to 0 and solve for the critical points.
crit_pts = solve(f1)
crit_pts =
3-213
3 Mathematics
13 8
− −
3 3
13 8
−
3 3
−8 − 13
x1 = 3
−8 + 13
x1 = 3
.
To find the inflection point of f , set the second derivative equal to 0 and solve for this condition.
3-214
Find Asymptotes, Critical, and Inflection Points
f2 = diff(f1);
inflec_pt = solve(f2,'MaxDegree',3);
double(inflec_pt)
-5.2635 + 0.0000i
-1.3682 - 0.8511i
-1.3682 + 0.8511i
In this example, only the first element is a real number, so this is the only inflection point. MATLAB®
does not always return the roots to an equation in the same order.
Instead of selecting the real root by indexing into inter_pt, identify the real root by determining
which roots have a zero-valued imaginary part.
idx = imag(double(inflec_pt)) == 0;
inflec_pt = inflec_pt(idx)
inflec_pt =
13 169 2197 1/3 8
− − − −
169 2197 1/3 54 18 3
9 54 − 18
Plot the inflection point. The extra argument [-9 6] in fplot extends the range of x values in the
plot so that you can see the inflection point more clearly, as the figure shows.
fplot(f,[-9 6])
hold on
plot(double(inflec_pt), double(subs(f,inflec_pt)),'ro')
title('Inflection Point of f')
text(-7,1,'Inflection point')
hold off
3-215
3 Mathematics
3-216
Functional Derivatives Tutorial
This example shows how to use functional derivatives in the Symbolic Math Toolbox™ using the
example of the wave equation. This example performs calculations symbolically to obtain analytic
results. The wave equation for a string fixed at its ends is solved using functional derivatives. A
functional derivative is the derivative of a functional with respect to the function that the functional
depends on. The Symbolic Math Toolbox implements functional derivatives using the
functionalDerivative function.
Solving the wave equation is one application of functional derivatives. It describes the motion of
waves, from the motion of a string to the propagation of an electromagnetic wave, and is an
important equation in physics. You can apply the techniques illustrated in this example to applications
in the calculus of variations from solving the Brachistochrone problem to finding minimal surfaces of
soap bubbles.
Consider a string of length L suspended between the two points x = 0 and x = L. The string has a
characteristic density per unit length and a characteristic tension. Define the length, mass density,
and tension as constants for later use. For simplicity, set these constants to 1.
Length = 1;
Density = 1;
Tension = 1;
If the string is in motion, the string's kinetic and potential energy densities are a function of its
displacement from rest S(x,t), which varies with position x and time t. If d is the mass density per
unit length, the kinetic energy density is
2
d d
T= S(x, t) .
2 dt
2
r d
V= S(x, t) ,
2 dx
Enter these equations in MATLAB®. Since length must be positive, set this assumption. This
assumption allows simplify to simplify the resulting equations into the expected form.
syms S(x,t) d r v L
assume(L>0)
T(x,t) = d/2*diff(S,t)^2;
V(x,t) = r/2*diff(S,x)^2;
The action density A is T-V. The Principle of Least Action states that action is always minimized.
Determine the condition for minimum action by finding the functional derivative of A with respect to
S using functionalDerivative and equate it to zero.
A = T-V;
eqn = functionalDerivative(A,S) == 0
eqn(x, t) =
3-217
3 Mathematics
∂2 ∂2
r 2
S x, t − d 2 S x, t = 0
∂x ∂t
Simplify the equation using simplify. Convert the equation into its expected form by substituting
for r/d with the square of the wave velocity v.
eqn = simplify(eqn)/r;
eqn = subs(eqn,r/d,v^2)
eqn(x, t) =
∂2
S x, t
∂t2 ∂2
= S x, t
v2 ∂x2
Solve the equation using the method of separation of variables. Set S(x,t) = U(x)*V(t) to
separate the dependence on position x and time t. Separate both sides of the resulting equation
using children.
syms U(x) V(t)
eqn2 = subs(eqn,S(x,t),U(x)*V(t));
eqn2 = eqn2/(U(x)*V(t))
eqn2(x, t) =
∂2 ∂2
V t Ux
∂t2 ∂x2
=
v2 V t Ux
tmp = children(eqn2);
Both sides of the equation depend on different variables, yet are equal. This is only possible if each
side is a constant. Equate each side to an arbitrary constant C to get two differential equations.
syms C
eqn3 = tmp(1) == C
eqn3 =
∂2
V t
∂t2
=C
v2 V t
eqn4 = tmp(2) == C
eqn4 =
∂2
Ux
∂x2
=C
Ux
Solve the differential equations using dsolve with the condition that displacement is 0 at x = 0 and
t = 0. Simplify the equations to their expected form using simplify with the Steps option set to
50.
V(t) = dsolve(eqn3,V(0)==0,t);
U(x) = dsolve(eqn4,U(0)==0,x);
V(t) = simplify(V(t),'Steps',50)
V(t) = −2 C1 sinh C t v
3-218
Functional Derivatives Tutorial
U(x) = simplify(U(x),'Steps',50)
U(x) = 2 C1 sinh C x
p1 = setdiff(symvar(U(x)),sym([C,x]))
p1 = C1
p2 = setdiff(symvar(V(t)),sym([C,v,t]))
p2 = C1
The string is fixed at the positions x = 0 and x = L. The condition U(0) = 0 already exists. Apply
the boundary condition that U(L) = 0 and solve for C.
eqn_bc = U(L) == 0;
[solC,param,cond] = solve(eqn_bc,C,'ReturnConditions',true)
solC =
2
k π2
−
L2
param = k
cond = k ∈ ℤ ∧ C1 ≠ 0 ∧ 1 ≤ k
assume(cond)
The solution S(x,t) is the product of U(x) and V(t). Find the solution, and substitute the
characteristic values of the string into the solution to obtain the final form of the solution.
S(x,t) = U(x)*V(t);
S = subs(S,C,solC);
S = subs(S,[L v],[Length sqrt(Tension/Density)]);
The parameters p1 and p2 determine the amplitude of the vibrations. Set p1 and p2 to 1 for
simplicity.
The string has different modes of vibration for different values of k. Plot the first four modes for an
arbitrary value of time t. Use the param argument returned by solve to address parameter k.
Splot(x) = S(x,0.3);
figure(1)
hold on
grid on
ymin = double(coeffs(Splot));
for i = 1:4
yplot = subs(Splot,param,i);
fplot(yplot,[0 Length])
end
ylim([-ymin ymin])
3-219
3 Mathematics
The wave equation is linear. This means that any linear combination of the allowed modes is a valid
solution to the wave equation. Hence, the full solution to the wave equation with the given boundary
conditions and initial values is a sum over allowed modes
m
F(x, t) = ∑ Aksin(πkt)sin(πkx),
k=n
Use symsum to sum the first five modes of the string. On a new figure, display the resulting waveform
at the same instant of time as the previous waveforms for comparison.
figure(2)
S5(x) = 1/5*symsum(S,param,1,5);
fplot(subs(S5,t,0.3),[0 Length])
ylim([-ymin ymin])
grid on
xlabel('Position (x)')
ylabel('Displacement (S)')
title('Summation of first 5 modes')
3-220
Functional Derivatives Tutorial
The figure shows that summing modes allows you to model a qualitatively different waveform. Here,
we specified the initial condition is S(x, t = 0) = 0 for all x.
m
You can calculate the values Ak in the equation F(x, t) = ∑ Aksin(πkt)sin(πkx) by specifying a
k=n
condition for initial velocity
ut(x, t = 0) = Ft(x, 0) .
The appropriate summation of modes can represent any waveform, which is the same as using the
Fourier series to represent the string's motion.
3-221
3 Mathematics
Learn calculus and applied mathematics using the Symbolic Math Toolbox™. The example shows
introductory functions fplot and diff.
syms x
Once a symbolic variable is defined, you can build and visualize functions with fplot.
f(x) = 1/(5+4*cos(x))
f(x) =
1
4 cos x + 5
fplot(f)
f(pi/2)
ans =
1
5
3-222
Learn Calculus in the Live Editor
Many functions can work with symbolic variables. For example, diff differentiates a function.
f1 = diff(f)
f1(x) =
4 sin x
2
4 cos x + 5
fplot(f1)
diff can also find the Nth derivative. Here is the second derivative.
f2 = diff(f,2)
f2(x) =
2
4 cos x 32 sin x
2
+ 3
4 cos x + 5 4 cos x + 5
fplot(f2)
3-223
3 Mathematics
int integrates functions of symbolic variables. The following is an attempt to retrieve the original
function by integrating the second derivative twice.
g = int(int(f2))
g(x) =
8
−
x 2
tan 2 + 9
fplot(g)
3-224
Learn Calculus in the Live Editor
At first glance, the plots for f and g look the same. Look carefully, however, at their formulas and
their ranges on the y-axis.
subplot(1,2,1)
fplot(f)
subplot(1,2,2)
fplot(g)
3-225
3 Mathematics
e is the difference between f and g. It has a complicated formula, but its graph looks like a constant.
e = f - g
e(x) =
8 1
+
x 2 4 cos x + 5
tan 2 + 9
To show that the difference really is a constant, simplify the equation. This confirms that the
difference between them really is a constant.
e = simplify(e)
e(x) = 1
3-226
Differentiation
Differentiation
This example shows how to analytically find and evaluate derivatives using Symbolic Math Toolbox™.
In the example you will find the 1st and 2nd derivative of f(x) and use these derivatives to find local
maxima, minima and inflection points.
Computing the first derivative of an expression helps you find local minima and maxima of that
expression. Before creating a symbolic expression, declare symbolic variables:
syms x
By default, solutions that include imaginary components are included in the results. Here, consider
only real values of x by setting the assumption that x is real:
assume(x, 'real')
As an example, create a rational expression (i.e., a fraction where the numerator and denominator
are polynomial expressions).
f =
3 x3 + 17 x2 + 6 x + 1
2 x3 − x + 3
3-227
3 Mathematics
Plotting this expression shows that the expression has horizontal and vertical asymptotes, a local
minimum between -1 and 0, and a local maximum between 1 and 2:
fplot(f)
grid
To find the horizontal asymptote, compute the limits of f for x approaching positive and negative
infinities. The horizontal asymptote is y = 3/2:
lim_left =
3
2
lim_right =
3
2
hold on
plot(xlim, [lim_right lim_right], 'LineStyle', '-.', 'Color', [0.25 0.25 0.25])
3-228
Differentiation
pole_pos = poles(f, x)
pole_pos =
1 3 241 432 1/3
− − −
3 241 432 1/3 4 432
6 4− 432
double(pole_pos)
ans = -1.2896
Now find the local minimum and maximum of f. If a point is a local extremum (either minimum or
maximum), the first derivative of the expression at that point is equal to zero. Compute the derivative
of f using diff:
g = diff(f, x)
g =
9 x2 + 34 x + 6 6 x2 − 1 3 x3 + 17 x2 + 6 x + 1
−
2 x3 − x + 3 2 x3 − x + 3
2
3-229
3 Mathematics
g0 = solve(g, x)
g0 =
σ2 15
− σ1 −
6 σ31/6 68
σ2 15
+ σ1 −
6 σ31/6 68
where
3 3 178939632355 2198209
337491 6
9826
+
9826 2841 σ31/3 σ2 361 σ2
39304
+ 578
− 9 σ32/3 σ2 − 289
σ1 =
6 σ31/6 σ21/4
3 178939632355 2198209
σ3 = +
176868 530604
double(g0)
ans = 2×1
-0.1892
1.2860
The expression f has a local maximum at x = 1.286 and a local minimum at x = -0.189. Obtain
the function values at these points using subs:
f0 = subs(f,x,g0)
f0 =
3-230
Differentiation
15 2 11
3 σ2 − 17 σ5 − σ6 + 68 − σ4 + σ1 + 34
219
σ6 + 2 σ2 − σ5 − 68
15 2 11
σ4 + 17 σ6 + σ5 − 68 + 3 σ3 + σ1 − 34
− 219
σ6 − 2 σ3 + σ5 − 68
where
σ7
σ1 = 1/6
σ9 σ81/4
15 3
σ2 = σ5 − σ6 +
68
15 3
σ3 = σ6 + σ5 −
68
σ8
σ4 =
σ91/6
σ7
σ5 = 1/6
6 σ9 σ81/4
σ8
σ6 =
6 σ91/6
3 3 178939632355 2198209
337491 6 9826
+ 9826 2841 σ91/3 σ8 361 σ8
σ7 = + − 9 σ92/3 σ8 −
39304 578 289
3 178939632355 2198209
σ9 = +
176868 530604
Approximate the exact solution numerically by using the double function on the variable f0:
double(f0)
ans = 2×1
0.1427
7.2410
3-231
3 Mathematics
Computing the second derivative lets you find inflection points of the expression. The most efficient
way to compute second or higher-order derivatives is to use the parameter that specifies the order of
the derivative:
h = diff(f, x, 2)
h =
2 2 2
18 x + 34 2 6 x − 1 9 x + 34 x + 6 12 x σ2 2 6 x2 − 1 σ2
− − +
σ1 σ12 σ12 σ13
where
σ1 = 2 x3 − x + 3
σ2 = 3 x3 + 17 x2 + 6 x + 1
h = simplify(h)
h =
2 68 x6 + 90 x5 + 18 x4 − 699 x3 − 249 x2 + 63 x + 172
3
2 x3 − x + 3
3-232
Differentiation
To find inflection points of f, solve the equation h = 0. Here, use the numeric solver vpasolve to
calculate floating-point approximations of the solutions:
h0 = vpasolve(h, x)
h0 =
0.57871842655441748319601085860196
1.8651543689917122385037075917613
−1.4228127856020972275345064554049 − 1.8180342567480118987898749770461 i
−1.4228127856020972275345064554049 + 1.8180342567480118987898749770461 i
−0.46088831805332057449182335801198 + 0.47672261854520359440077796751805 i
−0.46088831805332057449182335801198 − 0.47672261854520359440077796751805 i
The expression f has two inflection points: x = 1.865 and x = 0.579. Note that vpasolve also
returns complex solutions. Discard those:
h0(imag(h0)~=0) = []
h0 =
0.57871842655441748319601085860196
1.8651543689917122385037075917613
3-233
3 Mathematics
3-234
Integration
Integration
This example shows how to compute definite integrals using Symbolic Math Toolbox™.
Definite Integral
b
Show that the definite integral ∫ f (x)dx for f (x) = sin(x) on [ π2 , 3π2 ] is 0.
a
syms x
int(sin(x),pi/2,3*pi/2)
ans = 0
syms a x
assume(a >= 0);
F = int(sin(a*x)*sin(x/a),x,-a,a)
3-235
3 Mathematics
F =
sin 2
1− if a = 1
2
2 a sin a2 cos 1 − a2 cos a2 sin 1
if a ≠ 1
a4 − 1
Note the special case here for a = 1. To make computations easier, use assumeAlso to ignore this
possibility (and later check that a = 1 is not the maximum):
assumeAlso(a ~= 1);
F = int(sin(a*x)*sin(x/a),x,-a,a)
F =
2 a sin a2 cos 1 − a2 cos a2 sin 1
a4 − 1
fplot(F,[0 10])
Fa = diff(F,a)
Fa =
3-236
Integration
where
The maximum is between 1 and 2. Use vpasolve to find an approximation of the zero of Fa in this
interval:
a_max = vpasolve(Fa,a,[1,2])
a_max = 1.5782881585233198075558845180583
The result still contains exact numbers sin(1) and cos(1). Use vpa to replace these by numerical
approximations:
3-237
3 Mathematics
vpa(F_max)
ans = 1.2099496860938456039155811226054
Check that the excluded case a = 1 does not result in a larger value:
vpa(int(sin(x)*sin(x),x,-1,1))
ans = 0.54535128658715915230199006704413
Multiple Integration
integral2(@(x,y) x.^2-y.^2,0,1,0,1)
ans = 4.0127e-19
There are no such special functions for higher-dimensional symbolic integration. Use nested one-
dimensional integrals instead:
syms x y
int(int(x^2-y^2,y,0,1),x,0,1)
ans = 0
Line Integrals
syms x y z
F(x,y,z) = [x^2*y*z, x*y, 2*y*z];
syms t
ux(t) = sin(t);
uy(t) = t^2-t;
uz(t) = t;
The line integral of F along the curve u is defined as ∫ f ⋅ du = ∫ f (ux(t), uy(t), uz(t)) ⋅ du
dt
dt, where
the ⋅ on the right-hand-side denotes a scalar product.
Use this definition to compute the line integral for t from [0, 1]
F_int = int(F(ux,uy,uz)*diff([ux;uy;uz],t),t,0,1)
F_int =
19 cos 1 cos 3 sin 3 395
− − 12 sin 1 + +
4 108 27 54
vpa(F_int)
ans = −0.20200778585035447453044423341349
3-238
Interactive Calculus in Live Editor
This example shows how you can add interactive controls to solve a calculus problem in a live script.
An interactive control can be used to change the values of variables in your live script. To add a
numeric slider, go to the Insert tab, click the Control button, and select Numeric Slider. For more
information, see “Add Interactive Controls to a Live Script”.
xMax
∫0
cx2 dx
syms x;
xMax = ;
numRectangles = ;
c = ;
f(x) = c*x^2;
yMax = double(f(xMax));
fplot(f);
xlim([0 xMax]); ylim([0 yMax]);
legend({}, 'Location', 'north', 'FontSize', 20);
title('Riemann Sum', 'FontSize', 20);
Calculate the rectangular areas that approximate the area under the curve of the integral. Plot the
rectangles.
width = xMax/numRectangles;
sum = 0;
3-239
3 Mathematics
for i = 0:numRectangles-1
xval = i*width;
height = double(f(xval));
rectangle('Position', [xval 0 width height], 'EdgeColor', 'r');
sum = sum + width*height;
end
text(xMax/10, yMax/3, ['Area = ' num2str(sum)], 'FontSize', 20);
Calculate the integral analytically. Use vpa to numerically approximate the exact symbolic result to
32 significant digits.
fInt = int(f,0,xMax)
fInt =
160
3
vpa(fInt)
ans = 53.333333333333333333333333333333
3-240
Maxima, Minima, and Inflection Points
This demonstration shows how to find extrema of functions using analytical and numerical techniques
using the Symbolic Math Toolbox™.
Computing the first derivative of an expression helps you find local minima and maxima of that
expression. For example, create a rational expression where the numerator and the denominator are
polynomial expressions.
syms x
f = (3 * x^3 + 17 * x^2 + 6 * x + 1)/(2 * x^3 + x * -1 + 3)
f =
3 x3 + 17 x2 + 6 x + 1
2 x3 − x + 3
Plotting this expression shows that it has horizontal and vertical asymptotes, a local minimum
between -1 and 0, and a local maximum between 1 and 2.
fplot(f)
3-241
3 Mathematics
By default, when you operate on this expression, results can include both real and imaginary
numbers. If you are interested in real numbers only, you can set the permanent assumption that x
belongs to the set of real numbers. This allows you to avoid complex numbers in the solutions and it
also can improve performance.
assume(x, 'real')
To find a horizontal asymptote, compute the limit of f for x approaching positive and negative
infinities. The horizontal asymptote is x = 3/2.
ans =
3 3
2 2
To find a vertical asymptote of f , find the roots of the polynomial expression that represents the
denominator of f .
ans =
z 3
root z3 − + , z, 3
2 2
To get an explicit solution for such equations, try calling the solver with the option MaxDegree. The
option specifies the maximum degree of polynomials for which the solver tries to return explicit
3-242
Maxima, Minima, and Inflection Points
solutions. By default, MaxDegree = 2. Increasing this value, you can get explicit solutions for higher-
order polynomials. For example, specifying MaxDegree = 3 results in an explicit solution.
ans =
1 3 241 432 1/3
− − −
3 241 432 1/3 4 432
6 4− 432
You can approximate the exact solution numerically by using the vpa function.
vpa(ans,6)
ans = −1.28962
Now find the local minimum and maximum of the expression f. If the point is a local extremum
(either minimum or maximum), the first derivative of the expression at that point is equal to zero. To
compute the derivative of an expression, use the diff function.
g = diff(f, x)
g =
9 x2 + 34 x + 6 6 x2 − 1 3 x3 + 17 x2 + 6 x + 1
−
2 x3 − x + 3 2 x3 − x + 3
2
To find the local extrema of f, solve the equation g = 0. If you use the MaxDegree option, the solver
returns the long explicit solution, which can be approximated by using the vpa function.
extrema =
−0.189245
1.28598
The plot of the expression f shows that x = -0.189 is a local minimum of the expression, and x =
1.286 is its local maximum.
fplot(f)
hold on
plot(extrema, subs(f,extrema), '*')
hold off
3-243
3 Mathematics
Computing the second derivative lets you find inflection points of the expression.
h(x) =
2 68 x6 + 90 x5 + 18 x4 − 699 x3 − 249 x2 + 63 x + 172
3
2 x3 − x + 3
To find inflection points of f , solve the equation h = 0. For this equation the symbolic solver returns
a complicated result even if you use the MaxDegree option.
solve(h == 0, x, 'MaxDegree', 4)
ans =
root σ1, z, 1
root σ1, z, 4
where
45 z5 9 z4 699 z3 249 z2 63 z 43
σ1 = z6 + + − − + +
34 34 68 68 68 17
To get the simpler numerical result, solve the equation numerically by using vpasolve; specify the
search range to restrict the returned results to all real solutions of the expression.
3-244
Maxima, Minima, and Inflection Points
inflection =
0.57871842655441748319601085860196
1.8651543689917122385037075917613
fplot(f)
hold on
plot(extrema, subs(f,extrema), '*')
plot(inflection, subs(f,inflection), '*')
hold off
Suprema
π
is very flat at the origin and it oscillates infinitely often near − , becomes linear as it approaches
2
zero and oscillates again near π.
f = @(x) tan(sin(x))-sin(tan(x))
3-245
3 Mathematics
Most important for our purposes here, fplot has picked the limit on the y-axes to be
ylim
ans = 1×2
-2.5488 2.5572
π
What is happening at ?
2
π
MATLAB® uses double precision arithmetic, so evaluates to one of the oscillations.
2
pi/2
ans = 1.5708
f(pi/2)
ans = 2.5161
The Symbolic Math Toolbox uses exact arithmetic, which shows the function is undefined.
syms x
sym(pi/2)
ans =
π
2
F = sym(f)
subs(F,x,sym(pi/2))
ans = NaN
Taylor Series
T = taylor(F,x,'Order',10,'ExpansionPoint',0)
T =
29 x9 x7
+
756 30
vpa(subs(T,x,pi/2))
ans = 3.0198759869735883213825972535797
3-246
Maxima, Minima, and Inflection Points
hold on
fplot(T)
ylim ([-3 3])
hold off
Calculus
We learn in calculus that a maximum occurs at a zero of the derivative. But this function is not
π
differentiable in the vicinity of . We can analytically differentiate f (x) using the Symbolic Math
2
Toolbox.
diff(F)
2 2
ans = cos x tan sin x + 1 − cos tan x tan x +1
3-247
3 Mathematics
Sampling
π
We can sample the function N times near to get a numerical approximation to the value of the
2
maximum. Is that good enough?
N = 100;
xValues = 3*pi/8 + pi/4*rand(1,N)
xValues = 1×100
1.8180 1.8895 1.2778 1.8955 1.6748 1.2547 1.3968 1.6076 1.9301 1.9
ySoln = f(xValues)
ySoln = 1×100
0.7260 1.5080 1.5932 1.5614 1.3796 1.3158 2.0658 2.4586 1.8194 1.8
max(ySoln)
ans = 2.5387
Proof
3-248
Maxima, Minima, and Inflection Points
sin(x) ≤ 1
f (x) ≤ 1 + tan(1)
π
As x , tan(x) oscillates and blows up; sof (x) is actually not defined at all at this point as was
2
shown above
format long
1 + tan(1)
ans =
2.557407724654902
3-249
3 Mathematics
This example shows how to find the extremum of a multivariate function and its approximation near
the extremum point. This example uses symbolic matrix variables to represent the multivariate
function and its derivatives. Symbolic matrix variables are available starting in R2021a.
Consider the multivariate function f x = sin xT A x , where x is a 2-by-1 vector and A is a 2-by-2
matrix. To find a local extremum of this function, compute a root of the derivative of f (x). In other
words, find the solution of the derivative ∇ f (x0) = 0.
Create the vector x and the matrix A as symbolic matrix variables. Define the function
f x = sin xT A x .
syms x [2 1] matrix
syms A [2 2] matrix
f = sin(x.'*A*x)
f = sin xT A x
Compute the derivative D of the function f (x) with respect to the vector x. The derivative D is
displayed in compact matrix notation in terms of x and A.
D = diff(f,x)
D = cos xT A x xT A + xT AT
The symbolic matrix variables x, A, f, and D are symmatrix objects. These objects represent
matrices, vectors, and scalars in compact matrix notation. To show the components of these variables,
convert the symmatrix objects to sym objects using symmatrix2sym.
xsym = symmatrix2sym(x)
xsym =
x1
x2
Asym = symmatrix2sym(A)
Asym =
A1, 1 A1, 2
A2, 1 A2, 2
fsym = symmatrix2sym(f)
Dsym = symmatrix2sym(D)
Dsym = cos x1 A1, 1 x1 + A1, 2 x2 + x2 A2, 1 x1 + A2, 2 x2 2 A1, 1 x1 + A1, 2 x2 + A2, 1 x2 cos x1 A1, 1 x1 + A1, 2 x2 + x2 A2, 1 x
3-250
Find Extremum of Multivariate Function and Its Approximation
Suppose you are interested in the case where the value of A is [2 -1; 0 3]. Substitute this value
into the function fsym.
Then, apply the symbolic function solve to get a root of the derivative.
[xmin,ymin] = solve(Dsym,xsym,'PrincipalValue',true);
x0 = [xmin; ymin]
x0 =
0
0
Plot the function f (x) together with the extremum solution x0. Set the plot interval to −1 < x1 < 1 and
−1 < x2 < 1 as the second argument of fsurf. Use fplot3 to plot the coordinates of the extremum
solution.
fsurf(fsym,[-1 1 -1 1])
hold on
fplot3(xmin,ymin,subs(fsym,xsym,x0),'ro')
view([-68 13])
3-251
3 Mathematics
You can approximate a multivariate function around a point x0 with a multinomial using the Taylor
expansion.
1 T
f (x) ≈ f (x0) + ∇ f (x0) ⋅ (x − x0) + (x − x0) H(f (x0)) (x − x0)
2
Here, the term ∇ f (x0) is the gradient vector, and H(f (x0)) is the Hessian matrix of the multivariate
function f x calculated at x0.
Find the Hessian matrix and return the result as a symbolic matrix variable.
H = diff(f,x,x.')
H = −sin xT A x AT x + A x xT A + xT AT + cos xT A x AT + A
Convert the Hessian matrix H(f (x0)) to the sym data type, which represents the matrix in its
component form. Use subs to evaluate the Hessian matrix for A = [2 -1; 0 3] at the minimum
point x0.
Hsym = symmatrix2sym(H);
Hsym = subs(Hsym,Asym,[2 -1; 0 3]);
H0 = subs(Hsym,xsym,x0)
H0 =
3-252
Find Extremum of Multivariate Function and Its Approximation
4 −1
−1 6
D0 = subs(Dsym,xsym,x0)
D0 = 0 0
fapprox =
x2 x1
x1 2 x1 − − x2 − 3 x2
2 2
Plot the function approximation on the same graph that shows f (x) and x0.
hold on
fsurf(fapprox,[-1 1 -1 1])
zlim([-1 3])
3-253
3 Mathematics
This example shows how to use a Padé approximant in control system theory to model time delays in
the response of a first-order system. Time delays arise in systems such as chemical and transport
processes where there is a delay between the input and the system response. When these inputs are
modeled, they are called dead-time inputs.
This example uses Symbolic Math Toolbox™ to solve for the transfer function of a first-order system
and find the system response to dead-time step input using Padé approximant. This example performs
calculations symbolically to obtain analytic results.
Introduction
The Padé approximant of order [m, n] approximates the function f(x) around x = x0 as
m
a0 + a1 (x − x0) + ⋯ + am (x − x0)
n
.
1 + b1 (x − x0) + ⋯ + bn (x − x0)
The Padé approximant is a rational function formed by a ratio of two power series. Because it is a
rational function, it is more accurate than the Taylor series in approximating functions with poles.
The Padé approximant is represented by the Symbolic Math Toolbox™ function pade.
When a pole or zero exists at the expansion point x = x0, the accuracy of the Padé approximant
decreases. To increase accuracy, use an alternative form of the Padé approximant which is
p m
(x − x0) a0 + a1 (x − x0) + ⋯ + am (x − x0)
n
.
1 + b1 (x − x0) + ⋯ + bn (x − x0)
The pade function returns the alternative form of the Padé approximant when you set the
OrderMode input argument to Relative.
dy(t)
τ + y(t) = ax(t) .
dt
Assume the response of the system at t = 0 is 0. Use subs to substitute for y(0) = 0.
F = subs(F,y(0),0)
3-254
Padé Approximant of Time-Delay Input
F = simplify(F)
F = s τ + 1 laplace y t , t, s = a laplace x t , t, s
For readability, replace the Laplace transforms of x(t) and y(t) with xS(s) and yS(s).
F = yS s s τ + 1 = a xS s
The Laplace transform of the transfer function is yS(s)/xS(s). Divide both sides of the equation by
xS(s) and use subs to replace yS(s)/xS(s) with H(s).
F = F/xS(s);
F = subs(F,yS(s)/xS(s),H(s))
F = H s sτ+1 = a
Solve the equation for H(s). Substitute for H(s) with a dummy variable, solve for the dummy
variable using solve, and assign the solution to Hsol(s).
F = subs(F,H(s),tmp);
Hsol(s) = solve(F,tmp)
Hsol(s) =
a
sτ+1
The input to the first-order system is a time-delayed step input. To represent a step input, use
heaviside. Delay the input by three time units. Find the Laplace transform using laplace.
step =
e−3 s
s
Find the response of the system, which is the product of the transfer function and the input.
y = Hsol(s)*step
y =
a e−3 s
s sτ+1
To allow plotting of the response, set parameters a and tau to specific values. For a and tau, choose
values 1 and 3, respectively.
Find the Padé approximant of order [2 2] of the step input using the Order input argument to pade.
3-255
3 Mathematics
stepPade22 =
3 s2 − 4 s + 2
2s s+1
Find the response to the input by multiplying the transfer function and the Padé approximant of the
input.
yPade22 = Hsol(s)*stepPade22
yPade22 =
a 3 s2 − 4 s + 2
2s sτ+1 s+1
yPade22 = ilaplace(yPade22,s)
yPade22 =
s
− 2
9 a e−s a e τ 2 τ + 4 τ + 3
a+ −
2τ−2 τ 2τ−2
To plot the response, set parameters a and tau to their values of 1 and 3, respectively.
yPade22 =
s
9 e−s 11 e− 3
− +1
4 4
Plot the response of the system y and the response calculated from the Padé approximant yPade22.
fplot(y,[0 20])
hold on
fplot(yPade22, [0 20])
grid on
title 'Padé approximant for dead-time step input'
legend('Response to dead-time step input', 'Padé approximant [2 2]',...
'Location', 'Best');
3-256
Padé Approximant of Time-Delay Input
The [2 2] Padé approximant does not represent the response well because a pole exists at the
expansion point of 0. To increase the accuracy of pade when there is a pole or zero at the expansion
point, set the OrderMode input argument to Relative and repeat the steps. For details, see pade.
stepPade22Rel =
3 s2 − 6 s + 4
s 3 s2 + 6 s + 4
yPade22Rel = Hsol(s)*stepPade22Rel
yPade22Rel =
a 3 s2 − 6 s + 4
s s τ + 1 3 s2 + 6 s + 4
yPade22Rel = ilaplace(yPade22Rel);
yPade22Rel = subs(yPade22Rel,[a tau],[1 3])
yPade22Rel =
3t
2 3 sin
3t 3
12 e−t cos 3
+ 3 t
19 e− 3
− +1
7 7
3-257
3 Mathematics
You can increase the accuracy of the Padé approximant by increasing its order. Increase the order to
[4 5] and repeat the steps. The [n-1 n] Padé approximant is better at approximating the response
at t = 0 than the [n n] Padé approximant.
stepPade45 =
27 s4 − 180 s3 + 540 s2 − 840 s + 560
s 27 s4 + 180 s3 + 540 s2 + 840 s + 560
yPade45 = Hsol(s)*stepPade45
yPade45 =
a 27 s4 − 180 s3 + 540 s2 − 840 s + 560
s s τ + 1 27 s4 + 180 s3 + 540 s2 + 840 s + 560
yPade45 =
27 s4 − 180 s3 + 540 s2 − 840 s + 560
s 3 s + 1 27 s4 + 180 s3 + 540 s2 + 840 s + 560
3-258
Padé Approximant of Time-Delay Input
Find the inverse Laplace transform of yPade45 using ilaplace. Approximate yPade45 numerically
using vpa. Plot the response calculated from the Padé approximant yPade45.
yPade45 = vpa(ilaplace(yPade45));
fplot(yPade45, [0 20], 'DisplayName', 'Padé approximant [4 5]')
Conclusions
See Also
Functions
pade | diff | heaviside | laplace | ilaplace | subs
3-259
3 Mathematics
This example shows how to solve a partial differential equation (PDE) of nonlinear heat transfer in a
thin plate.
The plate is square, and its temperature is fixed along the bottom edge. No heat is transferred from
the other three edges since the edges are insulated. Heat is transferred from both the top and bottom
faces of the plate by convection and radiation. Because radiation is included, the problem is
nonlinear.
The purpose of this example is to show how to represent the nonlinear PDE symbolically using
Symbolic Math Toolbox™ and solve the PDE problem using finite element analysis in Partial
Differential Equation Toolbox™. In this example, perform transient analysis and solve the
temperature in the plate as a function of time. The transient analysis shows the time duration until
the plate reaches its equilibrium temperature at steady state.
The plate has planar dimensions 1 m by 1 m and is 1 cm thick. Because the plate is relatively thin
compared with the planar dimensions, the temperature can be assumed to be constant in the
thickness direction, and the resulting problem is 2-D.
Assume that convection and radiation heat transfers take place between the two faces of the plate
and the environment with a specified ambient temperature.
The amount of heat transferred from each plate face per unit area due to convection is defined as
Qc = hc(T − Ta),
where Ta is the ambient temperature, T is the temperature at a particular x and y location on the
plate surface, and hc is a specified convection coefficient.
The amount of heat transferred from each plate face per unit area due to radiation is defined as
Qr = ϵσ(T 4 − Ta4),
where ϵ is the emissivity of the face and σ is the Stefan-Boltzmann constant. Because the heat
transferred due to radiation is proportional to the fourth power of the surface temperature, the
problem is nonlinear.
∂T
ρCptz − ktz ∇2 T + 2Qc + 2Qr = 0
∂t
where ρ is the material density of the plate, Cp is its specific heat, tz is its plate thickness, k is its
thermal conductivity, and the factors of two account for the heat transfer from both of its faces.
Set up the PDE problem by defining the values of the parameters. The plate is composed of copper,
which has the following properties.
3-260
Solve Partial Differential Equation of Nonlinear Heat Transfer
Define the PDE in symbolic form with the plate temperature as a dependent variable T(t, x, y).
syms T(t,x,y)
syms eps sig tz hc Ta rho Cp k
Qc = hc*(T - Ta);
Qr = eps*sig*(T^4 - Ta^4);
pdeeq = (rho*Cp*tz*diff(T,t) - k*tz*laplacian(T,[x,y]) + 2*Qc + 2*Qr)
pdeeq(t, x, y) =
4 ∂2 ∂2 ∂
2 eps sig T t, x, y − Ta4 − k tz T t, x, y + T t, x, y − 2 hc Ta − T t, x, y + Cp ρ tz T t, x, y
∂x 2 ∂y 2 ∂t
Now, create coefficients to use as inputs in the PDE model as required by Partial Differential Equation
Toolbox. To do this, first extract the coefficients of the symbolic PDE as a structure of symbolic
expressions using the pdeCoefficients function.
symCoeffs = pdeCoefficients(pdeeq,T,'Symbolic',true)
Next, substitute the symbolic variables that represent the PDE parameters with their numeric values.
Finally, since the fields symCoeffs are symbolic objects, use the pdeCoefficientsToDouble
function to convert the coefficients to the double data type, which makes them valid inputs for
Partial Differential Equation Toolbox.
coeffs = pdeCoefficientsToDouble(symCoeffs)
3-261
3 Mathematics
Now, using Partial Differential Equation Toolbox, solve the PDE problem using finite element analysis
based on these coefficients.
numberOfPDE = 1;
model = createpde(numberOfPDE);
Specify the geometry for the PDE model—in this case, the dimension of the square.
width = 1;
height = 1;
Define a geometry description matrix. Create the square geometry using the decsg (Partial
Differential Equation Toolbox) function. For a rectangular geometry, the first row contains 3, and the
second row contains 4. The next four rows contain the x-coordinates of the starting points of the
edges, and the four rows after that contain the y-coordinates of the starting points of the edges.
Convert the DECSG geometry into a geometry object and include it in the PDE model.
geometryFromEdges(model,g);
figure;
pdegplot(model,'EdgeLabels','on');
axis([-0.1 1.1 -0.1 1.1]);
title('Geometry with Edge Labels Displayed');
3-262
Solve Partial Differential Equation of Nonlinear Heat Transfer
Next, create the triangular mesh in the PDE model with a mesh size of approximately 0.1 in each
direction.
3-263
3 Mathematics
specifyCoefficients(model,'m',coeffs.m,'d',coeffs.d, ...
'c',coeffs.c,'a',coeffs.a,'f',coeffs.f);
Apply the boundary conditions. Three of the plate edges are insulated. Because a Neumann boundary
condition equal to zero is the default in the finite element formulation, you do not need to set the
boundary conditions on these edges. The bottom edge of the plate is fixed at 1000 K. Specify this
using a Dirichlet condition on all nodes on the bottom edge (edge E1).
applyBoundaryCondition(model,'dirichlet','edge',1,'u',1000);
Specify the initial temperature to be 0 K everywhere, except at the bottom edge. Set the initial
temperature on the bottom edge E1 to the value of the constant boundary condition, 1000 K.
setInitialConditions(model,0);
setInitialConditions(model,1000,'edge',1);
Define the time domain to find the transient solution of the PDE problem.
endTime = 10000;
tlist = 0:50:endTime;
3-264
Solve Partial Differential Equation of Nonlinear Heat Transfer
model.SolverOptions.RelativeTolerance = 1.0e-3;
model.SolverOptions.AbsoluteTolerance = 1.0e-4;
Solve the problem using solvepde. Plot the temperature along the top edge of the plate as a
function of time.
R = solvepde(model,tlist);
u = R.NodalSolution;
figure;
plot(tlist,u(3,:));
grid on
title 'Temperature Along the Top Edge of the Plate as a Function of Time'
xlabel 'Time (s)'
ylabel 'Temperature (K)'
Based on the plot, the transient solution starts to reach its steady state value after 6000 seconds. The
equilibrium temperature of the top edge approaches 450 K after 6000 seconds.
figure;
pdeplot(model,'XYData',u(:,end),'Contour','on','ColorMap','jet');
title(sprintf('Temperature in the Plate, Transient Solution (%d seconds)\n', ...
tlist(1,end)));
xlabel 'X-coordinate, meters'
ylabel 'Y-coordinate, meters'
axis equal;
3-265
3 Mathematics
u(3,end)
ans = 449.7950
See Also
Functions
pdeCoefficients | pdeCoefficientsToDouble | subs
3-266
Symbolic Matrix Computation
This example shows how to perform simple matrix computations using Symbolic Math Toolbox™.
H = sym(hilb(5))
H =
1 1 1 1
1
2 3 4 5
1 1 1 1 1
2 3 4 5 6
1 1 1 1 1
3 4 5 6 7
1 1 1 1 1
4 5 6 7 8
1 1 1 1 1
5 6 7 8 9
d = det(H)
d =
1
266716800000
3-267
3 Mathematics
X = inv(H)
X =
25 −300 1050 −1400 630
−300 4800 −18900 26880 −12600
1050 −18900 79380 −117600 56700
−1400 26880 −117600 179200 −88200
630 −12600 56700 −88200 44100
I =
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
p =
563 x4 735781 x3 852401 x2 61501 x 1
x5 − + − + −
315 2116800 222264000 53343360000 266716800000
ans =
1
266716800000 x5 − 476703360000 x4 + 92708406000 x3 − 1022881200 x2 + 307505 x − 1
266716800000
The result indicates that the characteristic polynomial cannot be factored over the rational numbers.
e =
1.5670506910982307955330110055207246339493152522334
0.20853421861101333590500251006882005503858202260343
0.01140749162341980655945145886658934504234843052664
0.00030589804015119172687949784069272282565614514909247
0.0000032879287721718629571150047605447313997367890230746
H =
3-268
Symbolic Matrix Computation
1 1
− − σ σ3 σ1
t−2 t−3 5
1
− σ5 σ3 σ1 σ2
t−3
σ5 σ3 σ1 σ2 σ4
1
σ3 σ1 σ2 σ4 −
t−9
1 1
σ1 σ2 σ4 − −
t − 9 t − 10
where
1
σ1 = −
t−6
1
σ2 = −
t−7
1
σ3 = −
t−5
1
σ4 = −
t−8
1
σ5 = −
t−4
subs(H,t,1)
ans =
1 1 1 1
1
2 3 4 5
1 1 1 1 1
2 3 4 5 6
1 1 1 1 1
3 4 5 6 7
1 1 1 1 1
4 5 6 7 8
1 1 1 1 1
5 6 7 8 9
d = 1/det(H)
d =
2 3 4 5 4 3 2
t−2 t−3 t−4 t−5 t−6 t−7 t−8 t−9 t − 10
−
82944
d = expand(d)
d =
3-269
3 Mathematics
t25 25 t24 5375 t23 40825 t22 15940015 t21 21896665 t20 240519875 t19
− + − + − + −
82944 13824 41472 6912 82944 4608 2592
18 17 16
1268467075 t 1588946776255 t 2885896606895 t 79493630114675 t15
+ − + −
864 82944 13824 41472
14 13
34372691161375 t 8194259295156385 t 7707965729450845 t12 55608098247105175 t11
+ − + −
2304 82944 13824 20736
10 9
37909434298793825 t 197019820623693025 t 10640296363350955 t8
+ − +
3456 5184 96
38821472549340925 t7 12958201048605475 t6 1748754621252377 t5
− + − + 1115685328012530 t4
144 24 2
− 1078920141906600 t3 + 742618453752000 t2 − 323874210240000 t + 67212633600000
X =
t − 2 t − 3 t − 4 t − 5 t − 6 σ4 t − 3 t − 4 t − 5 t − 6 t − 7 t4 − 17 t3 + 1
−
576 144
t − 2 t − 3 t − 4 t − 5 t − 6 σ3 t − 3 t − 4 t − 5 t − 6 t − 7 t4 − 21 t3 +
−
144 36
t − 2 t − 3 t − 4 t − 5 t − 6 σ2 t − 3 t − 4 t − 5 t − 6 t − 7 t4 − 25 t3 + 2
−
96 24
t − 2 t − 3 t − 4 t − 5 t − 6 σ1 t − 3 t − 4 t − 5 t − 6 t − 7 t4 − 29 t3 + 3
−
144 36
4 3 2
t − 2 t − 3 t − 4 t − 5 t − 6 t − 34 t + 431 t − 2414 t + 5040 t − 3 t − 4 t − 5 t − 6 t − 7 t4 − 33 t3 + 40
−
576 144
where
X =
25 −300 1050 −1400 630
−300 4800 −18900 26880 −12600
1050 −18900 79380 −117600 56700
−1400 26880 −117600 179200 −88200
630 −12600 56700 −88200 44100
X = double(X)
X = 5×5
3-270
Symbolic Matrix Computation
A =
−9 11 −21 63 −252
70 −69 141 −421 1684
−575 575 −1149 3451 −13801
3891 −3891 7782 −23345 93365
1024 −1024 2048 −6144 24572
ans =
0000 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
5
p = λ
You should now be able to compute the matrix eigenvalues in your head. They are the zeros of the
equation lambda^5 = 0.
lambda =
0
0
0
0
0
Numeric computation involves roundoff error and finds the zeros of an equation that is something like
lambda^5 = eps*norm(A) So the computed eigenvalues are roughly lambda = (eps*norm(A))^(1/5)
Here are the eigenvalues, computed by the Symbolic Toolbox using 16 digit floating point arithmetic.
It is not obvious that they should all be zero.
digits(16)
lambda = eig(vpa(A))
3-271
3 Mathematics
lambda =
0.0005617448486395847
0.0001737348850386136 − 0.0005342985684139864 i
0.0001737348850386136 + 0.0005342985684139864 i
−0.000454607309358406 + 0.0003303865815979566 i
−0.000454607309358406 − 0.0003303865815979566 i
This matrix is also "defective". It is not similar to a diagonal matrix. Its Jordan Canonical Form is not
diagonal.
J = jordan(A)
J =
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1
0 0 0 0 0
The matrix exponential, expm(t*A), is usually expressed in terms of scalar exponentials involving the
eigenvalues, exp(lambda(i)*t). But for this matrix, the elements of expm(t*A) are all polynomials in t.
t = sym('t');
E = simplify(expm(t*A))
E =
2 t3 11 t2 t 4 t2 − 27 t + 33 t 20 t2 − 117 t + 126
− + −9t+1 −
3 2 3 6
3 2 3 2
t 7 t − 81 t + 230 t − 140 301 t2 t 35 t − 293 t + 598 t − 282
− 7 t4 − 67 t3 + − 69 t + 1 −
2 2 2
3 2 3 2
t 142 t − 1710 t + 5151 t − 3450 t 142 t − 1426 t + 3438 t − 1725 355 t4 3139 t3 4585 t2
− − + − 1149 t
6 3 3 3 2
t 973 t3 − 11675 t2 + 35022 t − 23346 t 1946 t3 − 19458 t2 + 46695 t − 23346 t 4865 t3 − 42807 t2 + 93390 t − 46
− −
6 6 6
3 2 3 2
128 t t − 12 t + 36 t − 24 256 t t − 10 t + 24 t − 12 128 t 5 t − 44 t2 + 96 t − 48
3
− −
3 3 3
3-272
Symbolic Matrix Computation
X = exp(t*A)
X =
e−9 t e11 t e−21 t e63 t e−252 t
e70 t e−69 t e141 t e−421 t e1684 t
e−575 t e575 t e−1149 t e3451 t e−13801 t
e3891 t e−3891 t e7782 t e−23345 t e93365 t
e1024 t e−1024 t e2048 t e−6144 t e24572 t
3-273
3 Mathematics
Generate the 3-by-3 Hilbert matrix. With format short, MATLAB prints the output shown.
H = hilb(3)
H =
1.0000 0.5000 0.3333
0.5000 0.3333 0.2500
0.3333 0.2500 0.2000
The computed elements of H are floating-point numbers that are the ratios of small integers. H is a
MATLAB array of class double.
H = sym(H)
H =
[ 1, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
inv(H)
ans =
[ 9, -36, 30]
[ -36, 192, -180]
[ 30, -180, 180]
det(H)
ans =
1/2160
3-274
Linear Algebraic Operations
You can use the backslash operator to solve a system of simultaneous linear equations. For example,
solve H*x = b.
b = [1; 1; 1];
x = H\b
x =
3
-24
30
All three results—the inverse, the determinant, and the solution to the linear system—are the exact
results corresponding to the infinite-precision, rational, Hilbert matrix.
Variable-Precision Arithmetic
Contrast the preceding operations with variable-precision arithmetic using 20 digits of precision.
digits(20)
V = vpa(H)
V =
The decimal points in the representation of the individual elements indicate that MATLAB is using
variable-precision arithmetic. The result of each arithmetic operation is rounded to 20 significant
decimal digits.
Invert the matrix and note that errors are magnified by the matrix condition number, which for
hilb(3) is about 500.
cond(V)
ans =
524.0567775860608
Compute the difference of the inverses of the infinite-precision and variable-precision versions.
ih = inv(H)
ih =
[ 9, -36, 30]
[ -36, 192, -180]
[ 30, -180, 180]
iv = inv(V)
iv =
3-275
3 Mathematics
Although these matrices look the same, calculate the difference to see that they are not.
dhv = ih - iv
dhv =
Solve the equation V*y = b. The answer looks the same as the solution to H*x = b.
y = V\b
y =
3.0
-24.0
30.0
Calculate the difference between x and y to see the small difference between the two solutions.
x-y
ans =
8.0779356694631608874e-27
-6.4623485355705287099e-26
7.1085833891275815809e-26
Using vpa with digits(16) offers comparable precision to using standard double-precision
MATLAB routines.
syms s
Hs = H;
Hs(1,1) = s
Z = det(Hs)
sol = solve(Z)
Hs =
[ s, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
Z =
s/240 - 1/270
sol =
8/9
Hs = subs(Hs, s, sol)
3-276
Linear Algebraic Operations
Hs =
[ 8/9, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
det(Hs)
ans =
0
Find the null space and column space of Hs. Both spaces are nontrivial.
N = null(Hs)
C = colspace(Hs)
N=
3/10
-6/5
1
C =
[ 1, 0]
[ 0, 1]
[ -3/10, 6/5]
Hs*N
ans =
0
0
0
3-277
3 Mathematics
The Givens transformation produces a plane rotation through the angle t. The statements
syms t
G = [cos(t) sin(t); -sin(t) cos(t)]
G =
[ cos(t), sin(t)]
[ -sin(t), cos(t)]
Applying the Givens transformation twice should simply be a rotation through twice the angle. The
corresponding matrix can be computed by multiplying G by itself or by raising G to the second power.
Both
A = G*G
and
A = G^2
produce
A =
[ cos(t)^2 - sin(t)^2, 2*cos(t)*sin(t)]
[ -2*cos(t)*sin(t), cos(t)^2 - sin(t)^2]
A = simplify(A)
uses a trigonometric identity to return the expected form by trying several different identities and
picking the one that produces the shortest representation.
A =
[ cos(2*t), sin(2*t)]
[ -sin(2*t), cos(2*t)]
The Givens rotation is an orthogonal matrix, so its transpose is its inverse. Confirming this by
I = G.' *G
which produces
I =
[ cos(t)^2 + sin(t)^2, 0]
[ 0, cos(t)^2 + sin(t)^2]
and then
I = simplify(I)
3-278
Basic Algebraic Operations
I =
[ 1, 0]
[ 0, 1]
3-279
3 Mathematics
To compute the singular value decomposition of a matrix, use svd. This function lets you compute
singular values of a matrix separately or both singular values and singular vectors in one function
call. To compute singular values only, use svd without output arguments
svd(A)
S = svd(A)
To compute singular values and singular vectors of a matrix, use three output arguments:
[U,S,V] = svd(A)
svd returns two unitary matrices, U and V, the columns of which are singular vectors. It also returns
a diagonal matrix, S, containing singular values on its diagonal. The elements of all three matrices
are floating-point numbers. The accuracy of computations is determined by the current setting of
digits.
Create the n-by-n matrix A with elements defined by A(i,j) = 1/(i - j + 1/2). The most
obvious way of generating this matrix is
n = 3;
for i = 1:n
for j = 1:n
A(i,j) = sym(1/(i-j+1/2));
end
end
A =
[ 2, -2, -2/3]
[ 2/3, 2, -2]
[ 2/5, 2/3, 2]
Compute the singular values of this matrix. If you use svd directly, it will return exact symbolic
result. For this matrix, the result is very long. If you prefer a shorter numeric result, convert the
elements of A to floating-point numbers using vpa. Then use svd to compute singular values of this
matrix using variable-precision arithmetic:
S = svd(vpa(A))
S =
3.1387302525015353960741348953506
3.0107425975027462353291981598225
1.6053456783345441725883965978052
3-280
Singular Value Decomposition
[U,S,V] = svd(A)
U =
[ 0.53254331027335338470683368360204, 0.76576895948802052989304092179952,...
0.36054891952096214791189887728353]
[ -0.82525689650849463222502853672224, 0.37514965283965451993171338605042,...
0.42215375485651489522488031917364]
[ 0.18801243961043281839917114171742, -0.52236064041897439447429784257224,...
0.83173955292075192178421874331406]
S =
[ 3.1387302525015353960741348953506, 0,...
0]
[ 0, 3.0107425975027462353291981598225,...
0]
[ 0, 0,...
1.6053456783345441725883965978052]
V =
[ 0.18801243961043281839917114171742, 0.52236064041897439447429784257224,...
0.83173955292075192178421874331406]
[ -0.82525689650849463222502853672224, -0.37514965283965451993171338605042,...
0.42215375485651489522488031917364]
[ 0.53254331027335338470683368360204, -0.76576895948802052989304092179952,...
0.36054891952096214791189887728353]
3-281
3 Mathematics
Eigenvalues
The symbolic eigenvalues of a square matrix A or the symbolic eigenvalues and eigenvectors of A are
computed, respectively, using the commands E = eig(A) and [V,E] = eig(A).
The eigenvalues of A are the zeros of the characteristic polynomial of A, det(A-x*I), which is
computed by charpoly(A).
The matrix H from the last section provides the first example:
H =
[ 8/9, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
The matrix is singular, so one of its eigenvalues must be zero. The statement
[T,E] = eig(H)
produces the matrices T and E. The columns of T are the eigenvectors of H and the diagonal elements
of E are the eigenvalues of H:
T =
[ 3/10, 218/285 - (4*12589^(1/2))/285, (4*12589^(1/2))/285 + 218/285]
[ -6/5, 292/285 - 12589^(1/2)/285, 12589^(1/2)/285 + 292/285]
[ 1, 1, 1]
E =
[ 0, 0, 0]
[ 0, 32/45 - 12589^(1/2)/180, 0]
[ 0, 0, 12589^(1/2)/180 + 32/45]
It may be easier to understand the structure of the matrices of eigenvectors, T, and eigenvalues, E, if
you convert T and E to decimal notation. To do so, proceed as follows. The commands
Td = double(T)
Ed = double(E)
return
Td =
0.3000 -0.8098 2.3397
-1.2000 0.6309 1.4182
1.0000 1.0000 1.0000
Ed =
0 0 0
0 0.0878 0
0 0 1.3344
The first eigenvalue is zero. The corresponding eigenvector (the first column of Td) is the same as the
basis for the null space found in the last section. The other two eigenvalues are the result of applying
64 253
the quadratic formula to x2 − x+ which is the quadratic factor in factor(charpoly(H,
45 2160
x)):
3-282
Eigenvalues
syms x
g = factor(charpoly(H, x))/x
solve(g(3))
g =
[ 1/(2160*x), 1, (2160*x^2 - 3072*x + 253)/x]
ans =
32/45 - 12589^(1/2)/180
12589^(1/2)/180 + 32/45
Closed form symbolic expressions for the eigenvalues are possible only when the characteristic
polynomial can be expressed as a product of rational polynomials of degree four or less. The Rosser
matrix is a classic numerical analysis test matrix that illustrates this requirement. The statement
R = sym(rosser)
generates
R =
[ 611, 196, -192, 407, -8, -52, -49, 29]
[ 196, 899, 113, -192, -71, -43, -8, -44]
[ -192, 113, 899, 196, 61, 49, 8, 52]
[ 407, -192, 196, 611, 8, 44, 59, -23]
[ -8, -71, 61, 8, 411, -599, 208, 208]
[ -52, -43, 49, 44, -599, 411, 208, 208]
[ -49, -8, 8, 59, 208, 208, 99, -911]
[ 29, -44, 52, -23, 208, 208, -911, 99]
The commands
p = charpoly(R, x);
factor(p)
produce
ans =
The characteristic polynomial (of degree 8) factors nicely into the product of two linear terms and
three quadratic terms. You can see immediately that four of the eigenvalues are 0, 1020, and a double
root at 1000. The other four roots are obtained from the remaining quadratics. Use
eig(R)
The Rosser matrix is not a typical example; it is rare for a full 8-by-8 matrix to have a characteristic
polynomial that factors into such simple form. If you change the two “corner” elements of R from 29
to 30 with the commands
3-283
3 Mathematics
S = R;
S(1,8) = 30;
S(8,1) = 30;
p = charpoly(S, x)
you find
p =
x^8 - 4040*x^7 + 5079941*x^6 + 82706090*x^5...
- 5327831918568*x^4 + 4287832912719760*x^3...
- 1082699388411166000*x^2 + 51264008540948000*x...
+ 40250968213600000
You also find that factor(p) is p itself. That is, the characteristic polynomial cannot be factored
over the rationals.
F = eig(S)
returns
F =
-1020.053214255892
-0.17053529728769
0.2180398054830161
999.9469178604428
1000.120698293384
1019.524355263202
1019.993550129163
1020.420188201505
Notice that these values are close to the eigenvalues of the original Rosser matrix.
It is also possible to try to compute eigenvalues of symbolic matrices, but closed form solutions are
rare. The Givens transformation is generated as the matrix exponential of the elementary matrix
0 1
A= .
−1 0
syms t
A = sym([0 1; -1 0]);
G = expm(t*A)
return
G =
[ exp(-t*1i)/2 + exp(t*1i)/2,
(exp(-t*1i)*1i)/2 - (exp(t*1i)*1i)/2]
[ - (exp(-t*1i)*1i)/2 + (exp(t*1i)*1i)/2,
exp(-t*1i)/2 + exp(t*1i)/2]
3-284
Eigenvalues
G = simplify(G)
G =
[ cos(t), sin(t)]
[ -sin(t), cos(t)]
g = eig(G)
produces
g =
cos(t) - sin(t)*1i
cos(t) + sin(t)*1i
g = rewrite(g, 'exp')
g =
exp(-t*1i)
exp(t*1i)
3-285
3 Mathematics
J = jordan(A)
[V,J] = jordan(A)
also computes the similarity transformation where J = inv(V)*A*V. The columns of V are the
generalized eigenvectors of A.
The Jordan form is extremely sensitive to changes. Almost any change in A causes its Jordan form to
be diagonal. This implies that A must be known exactly (i.e., without round-off error, etc.) and makes
it very difficult to compute the Jordan form reliably with floating-point arithmetic. Thus, computing
the Jordan form with floating-point values is unreliable and not recommended.
A = sym([12,32,66,116;-25,-76,-164,-294;
21,66,143,256;-6,-19,-41,-73])
A =
[ 12, 32, 66, 116]
[ -25, -76, -164, -294]
[ 21, 66, 143, 256]
[ -6, -19, -41, -73]
Then
[V,J] = jordan(A)
produces
V =
[ 4, -2, 4, 3]
[ -6, 8, -11, -8]
[ 4, -7, 10, 7]
[ -1, 2, -3, -2]
J =
[ 1, 1, 0, 0]
[ 0, 1, 0, 0]
[ 0, 0, 2, 1]
[ 0, 0, 0, 2]
Show that J and inv(V)*A*V are equal by using isequal. The isequal function returns logical 1
(true) meaning that the inputs are equal.
3-286
Jordan Canonical Form
isequal(J, inv(V)*A*V)
ans =
logical
1
From J, we see that A has a double eigenvalue at 1, with a single Jordan block, and a double
eigenvalue at 2, also with a single Jordan block. The matrix has only two eigenvectors, V(:,1) and
V(:,3). They satisfy
A*V(:,1) = 1*V(:,1)
A*V(:,3) = 2*V(:,3)
The other two columns of V are generalized eigenvectors of grade 2. They satisfy
In mathematical notation, with vj = v(:,j), the columns of V and eigenvalues satisfy the
relationships
(A − λ1I)v2 = v1
(A − λ2I)v4 = v3 .
3-287
3 Mathematics
This example shows how to solve the eigenvalue problem of the Laplace operator on an L-shaped
region.
Membrane Problem
Consider a membrane that is fixed at the boundary ∂Ω of a region Ω in the plane. Its displacement
u(x, y) is described by the eigenvalue problem Δu = λu, where Δu = uxx + uyy is the Laplace operator
and λ is a scalar parameter. The boundary condition is u(x, y) = 0 for all (x, y) ∈ ∂Ω.
The Laplace operator is self-adjoint and negative definite, that is, only real negative eigenvalues λ
exist. There is a maximal (negative) discrete eigenvalue, the corresponding eigenfunction u is called
the ground state. In this example, Ω is an L-shaped region, and the ground state associated with this
region is the L-shaped membrane that is the MATLAB® logo.
The simplest approach to the eigenvalue problem is to approximate the Laplacian Δu by a finite
difference approximation (a stencil) on a square grid of points with distances hx in x direction and
distances hy in y direction. In this example, approximate Δu with a sum S_h of nine regular grid
points around the midpoint (x, y). The unknowns are the weights a−1 − 1, …, a11.
syms u(x,y) Eps a11 a10 a1_1 a01 a00 a0_1 a_11 a_10 a_1_1
syms hx hy positive
S_h = a_11 * u(x - Eps*hx,y + Eps*hy) +...
a01 * u(x,y + Eps*hy) +...
a11 * u(x + Eps*hx,y + Eps*hy) +...
a_10 * u(x - Eps*hx,y) +...
a00 * u(x,y) +...
a10 * u(x + Eps*hx,y) +...
a_1_1* u(x - Eps*hx,y - Eps*hy) +...
a0_1 * u(x,y - Eps*hy) +...
a1_1 * u(x + Eps*hx,y - Eps*hy);
Use the symbolic parameter Eps to sort the expansion of this expression by powers of hx and hy.
Knowing the weights, you can approximate the Laplacian by setting Eps = 1.
Use the coeffs function to extract their coefficients of terms with the same powers of Eps. Each
coefficient is an expression containing powers of hx, hy, and derivatives of u with respect to x and y.
Since S_h represents uxx + uyy, the coefficients of all other derivatives of u must be zero. Extract the
coefficients by replacing all derivatives of u, except uxx and uyy, by 0. Replace uxx and uyy by 1. This
reduces the Taylor expansion to the coefficient you want to compute, and leads to the following six
linear equations.
3-288
Eigenvalues of the Laplace Operator
Since there are nine unknown weights in S_h, add further equations by requiring that all third-order
derivatives of u are 0.
Solve the resulting ten equations for the nine unknown weights. Use ReturnConditions to find all
solutions including arbitrary parameters.
[a11,a10,a1_1,a01,a00,a0_1,a_11,a_10,a_1_1,parameters,conditions] = ...
solve([eq0,eq11,eq12,eq21,eq22,eq23,eq31,eq32,eq33,eq34], ...
[a11,a10,a1_1,a01,a00,a0_1,a_11,a_10,a_1_1], ...
'ReturnConditions',true);
expand([a_11,a01,a11;...
a_10,a00,a01;...
a1_1,a0_1,a_1_1])
ans =
1
z 2
−2z z
hy
1 2 2 1
2
−2z 4z− 2
− 2 2
−2z
hx hx hy hy
1
z 2
−2z z
hy
parameters
parameters = z
Use the subs function to replace the weights by their computed values.
C = simplify(subs(C));
The expressions C(7), C(6), and C(4) containing the 0th, 1st, and 3rd derivatives of u vanish.
ans = 0 0 0
C(5)
ans =
∂2 ∂2
2
u x, y + u x, y
∂x ∂y2
Thus, with the values of the weights computed above, the stencil S_h approximates the Laplacian up
to order hx^2, hy^2 for any values of the arbitrary parameter z, provided that z is chosen to be of
order O(1/hx^2,1/hy^2).
3-289
3 Mathematics
Although the solution contains a free parameter z, the expression C(3) containing the fourth-order
derivatives of u cannot be turned into zero by a suitable choice of z. Another option is to turn it into a
multiple of the square of the Laplace operator.
syms d
Laplace = @(u) laplacian(u,[x,y]);
expand(d*Laplace(Laplace(u)))
ans(x, y) =
∂4 ∂2 ∂2 ∂4
d u x, y + 2 d u x, y + d u x, y
∂x4 ∂y2 ∂x2 ∂y4
Pick different derivatives of u in C(3), and equate their coefficients with the corresponding terms.
subs(C(3),[diff(u,x,x,x,x),diff(u,x,x,y,y),diff(u,y,y,y,y)],[1,0,0]) == d
ans =
2
hx
=d
12
subs(C(3),[diff(u,x,x,x,x),diff(u,x,x,y,y),diff(u,y,y,y,y)],[0,1,0]) == 2*d
2 2
ans = hx hy z = 2 d
subs(C(3),[diff(u,x,x,x,x),diff(u,x,x,y,y),diff(u,y,y,y,y)],[0,0,1]) == d
ans =
2
hy
=d
12
Therefore, you can choose d = hx^2/12 = hy^2/12 and z = 2*d/(hx^2*hy^2), implying that
hx = hy and z = 1/(6*hx*hy). Hence, the stencil S_h approximates a modified Laplacian on a
square grid with hx = hy = h.
2
h 3
Sh = Δu + Δ2u + O(h ) . (1)
12
syms h
hx = h;
hy = h;
d = h^2/12;
Replace hx and hy by h.
C = subs(C);
Replace z by its value, 1/(6*h^2). Because z does not exist in the MATLAB workspace, you can
access it only as the value stored in the parameters array.
C = subs(C,parameters,1/(6*h^2));
ans(x, y) = 0
3-290
Eigenvalues of the Laplace Operator
ans = 0
3
Since no such terms exist in the expansion of the stencil, the term O(h ) in (1) is in fact of order
4
O(h ). Consider the fourth-order terms of the stencil.
factor(simplify(C(1)))
ans =
1 ∂6 ∂2 ∂4 ∂4 ∂2 ∂6
hhhh u x, y + 5 u x, y + 5 u x, y + u x, y
360 ∂x6 ∂y2 ∂x4 ∂y4 ∂x2 ∂y6
Check if these terms can be identified with yet another power of the Laplace operator. However,
comparison with
Laplace(Laplace(Laplace(u)))
ans(x, y) =
∂6 ∂2 ∂4 ∂4 ∂2 ∂6
u x, y + 3 u x, y + 3 u x, y + u x, y
∂x6 ∂y2 ∂x4 ∂y4 ∂x2 ∂y6
4
shows that the expressions of order O(h ) cannot be identified as some multiple of the third power of
the Laplace operator because the coefficients cannot be matched.
Summary
For a square grid with distance h between neighboring grid points and the above choices of the
weights, you get:
2
h 4
Sh = Δu + Δ2u + O(h ) . (2)
12
Use this expansion for the numeric approach to the eigenvalue problem Δu = λu. Add some multiple
2
of Δ2u = λ u to the eigenvalue equation.
2 2
h h 2
Δu + Δ2u = (λ + λ ) u.
12 12
The left side of this equation is well approximated by the stencil Sh. Thus, using (2), a numerical
eigenvalue μ of the stencil satisfying Shu = μu must be an approximation of the eigenvalue λ of the
Laplace operator with
2
h 2 4
μ= λ+ λ + O(h ) .
12
For given μ, solve for λ to obtain a better approximation of the Laplace eigenvalue. Note that in the
solution of the quadratic equation in λ the correct sign of the square root is given by the requirement
that λ μ for h 0.
2
6 μh 2μ
λ= 1+ −1 = . (3)
h
2 3 μh
2
1+ 3
+1
3-291
3 Mathematics
xmin =-1;
xmax = 1;
ymin =-1;
ymax = 1;
Consider a square grid consisting of an odd number Nx=2*nx-1 of grid points in x direction and an
odd number Ny=2*ny-1 of grid points in y direction.
nx = 6;
Nx = 2*nx-1;
hx = (xmax-xmin)/(Nx-1);
ny = 6;
Ny = 2*ny-1;
hy = (ymax-ymin)/(Ny-1);
Create an Ny-by- Nx symbolic matrix u. Its entries u(i,j) represent the values u(xmin + (j -
1)*hx,ymin + (i - 1)*hy) of the solution u(x,y) of the eigenvalue problem Δu = λu.
u = sym('u',[Ny,Nx]);
The region with 0 < x ≤ 1 and 0 < y ≤ 1 does not belong to Ω. Set the corresponding matrix entries
(i = ny + 1:Ny, j = nx + 1:Nx) to zero. They play no further role and will be ignored.
u =
3-292
Eigenvalues of the Laplace Operator
0 0 0 0 0 0 0 0 0 0 0
0 u2, 2 u2, 3 u2, 4 u2, 5 u2, 6 u2, 7 u2, 8 u2, 9 u2, 10 0
0 u3, 2 u3, 3 u3, 4 u3, 5 u3, 6 u3, 7 u3, 8 u3, 9 u3, 10 0
0 u4, 2 u4, 3 u4, 4 u4, 5 u4, 6 u4, 7 u4, 8 u4, 9 u4, 10 0
0 u5, 2 u5, 3 u5, 4 u5, 5 u5, 6 u5, 7 u5, 8 u5, 9 u5, 10 0
0 u6, 2 u6, 3 u6, 4 u6, 5 0 0 0 0 0 0
0 u7, 2 u7, 3 u7, 4 u7, 5 0 0 0 0 0 0
0 u8, 2 u8, 3 u8, 4 u8, 5 0 0 0 0 0 0
0 u9, 2 u9, 3 u9, 4 u9, 5 0 0 0 0 0 0
0 u10, 2 u10, 3 u10, 4 u10, 5 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
The interior points of the region Ω ∖ ∂Ω correspond to the indices (i, j) that contain the unknown
values u(i, j) of the problem. Collect these unknowns in a vector vars.
[I,J] = find(u~=0);
vars = u(u~=0);
Associate a symbolic expression (given by the stencil derived in the first part of this example) with
each index (that is, with each unknown).
n = length(vars);
Lu = sym(zeros(n,1));
for k=1:n
i = I(k);
j = J(k);
Lu(k) = 1/6*u(i+1,j-1) + 2/3*u(i+1,j) + 1/6*u(i+1,j+1) ...
+ 2/3*u( i ,j-1) - 10/3*u( i ,j) + 2/3*u( i ,j+1) ...
+ 1/6*u(i-1,j-1) + 2/3*u(i-1,j) + 1/6*u(i-1,j+1);
end
Lu = Lu/hx^2;
Because this expression is linear in the unknown elements of u (stored in vars), you can treat it as a
matrix acting on the vector vars.
You can treat S_h as a matrix approximation of the Laplace operator. Compute its eigenvectors and
eigenvalues.
[V,D] = eig(vpa(S_h));
The three maximal eigenvalues are given by the first diagonal elements of D.
Since for this approximation you used a grid with a small number of points, only the leading digits of
the eigenvalues are correct.
The third highest eigenvalue of the Laplace operator on the L-shaped region Ω is known exactly. The
exact eigenfunction of the Laplace operator is the function u(x, y) = sin(πx) sin(πy) associated with
3-293
3 Mathematics
the (exact) eigenvalue −2π2 = − 19 . 7392 . . .. Indeed, using equation (3) above, you can derive a
better approximation of the Laplace eigenvalue λ from the stencil eigenvalue μ:
mu = D(3,3)
mu = −18.490392088545609858994660377955
lambda = −19.796765119155672176257649532142
When you use symbolic matrices, increasing the number of grid points drastically is not
recommended because symbolic computations are significantly slower than numerical computations
with MATLAB double-precision matrices. This part of the example demonstrates how to use sparse
double arithmetic which allows to refine the numerical grid. The L-shaped region Ω is set up the same
way as before. Instead of denoting the interior points by symbolic unknowns, initialize the grid values
3-294
Eigenvalues of the Laplace Operator
u by ones and define Ω by setting the values of boundary points and exterior points to zero. Instead of
defining a symbolic expression for each interior point and computing the stencil as the Jacobian, set
up the stencil matrix directly as a sparse matrix.
xmin =-1;
xmax = 1;
ymin =-1;
ymax = 1;
nx = 30;
Nx = 2*nx-1;
hx = (xmax-xmin)/(Nx-1);
ny = 30;
Ny = 2*ny-1;
hy = (ymax-ymin)/(Ny-1);
u = ones(Ny,Nx);
u(:,1) = 0; % left boundary
u(1:ny,Nx) = 0; % right boundary, upper part
u(ny:Ny,nx) = 0; % right boundary, lower part
u(1,:) = 0; % lower boundary
u(Ny,1:nx) = 0; % upper boundary, left part
u(ny,nx:Nx) = 0; % upper boundary, right part
u(ny + 1:Ny,nx + 1:Nx) = 0;
Here, S_h is the (sparse) stencil matrix. Use eigs that handles sparse matrices to compute the three
largest eigenvalues.
[V,D] = eigs(S_h,3,'la');
ans = 1×3
3-295
3 Mathematics
D(3,3) approximates the exact eigenvalue −2π2 = − 19 . 7392088 . . .. Using the equation (3) above,
derive a more accurate approximation of the Laplace eigenvalue λ from the stencil eigenvalue μ.
mu = D(3,3)
mu = -19.7006
lambda = -19.7393
v = V(:,3);
for k=1:n
u(I(k),J(k)) = v(k);
end
surf(xmin:hx:xmax, ymin:hy:ymax,u');
view(125, 30);
Note that the MATLAB membrane function computes the eigenfunctions of the Laplace operator by
different methods.
membrane(3, nx - 1, 8, 8);
3-296
Eigenvalues of the Laplace Operator
See Also
Functions
diff | laplacian | solve | subs | taylor
3-297
3 Mathematics
This example shows how to compute the inverse of a Hilbert matrix using Symbolic Math Toolbox™.
1
Definition : A Hilbert matrix is a square matrix with entries being the unit fraction. Hi j = .
i+ j−1
1 1
1
2 3
1 1 1
For example, the 3x3 Hilbert matrix is H =
2 3 4
1 1 1
3 4 5
Symbolic computations give accurate results for these ill-conditioned matrices, while purely
numerical methods fail.
Find the condition number of this matrix. Hilbert matrices are ill-conditioned, meaning that they have
large condition numbers indicating that such matrices are nearly singular. Note that computing
condition numbers is also prone to numeric errors.
cond(H)
ans = 2.1211e+18
Therefore, inverting Hilbert matrices is numerically unstable. When you compute a matrix inverse,
H*inv(H) must return an identity matrix or a matrix close to the identity matrix within some error
margin.
First, compute the inverse of H by using the inv function. A warning is thrown due to the numerical
instability.
H*inv(H)
3-298
Hilbert Matrices and Their Inverses
Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 1.30973
ans = 20×20
Now, use the MATLAB® invhilb function that offers better accuracy for Hilbert matrices. This
function finds exact inverses of Hilbert matrices up to 15-by-15. For a 20-by-20 Hilbert matrix,
invhilb finds the approximation of the matrix inverse.
H*invhilb(20)
ans = 20×20
1010 ×
0.0000 0.0000 0.0000 -0.0000 -0.0000 -0.0003 0.0027 -0.0113 -0.0526 -0.1
-0.0000 0.0000 -0.0000 -0.0000 -0.0000 -0.0001 -0.0015 0.0114 -0.0749 0.2
0.0000 0.0000 0.0000 -0.0000 -0.0000 -0.0003 -0.0005 -0.0029 0.0180 -0.1
0.0000 -0.0000 0.0000 -0.0000 -0.0000 0.0000 0.0012 0.0152 -0.0434 -0.1
-0.0000 0.0000 -0.0000 -0.0000 -0.0000 -0.0001 0.0007 0.0127 -0.1088 0.1
0.0000 -0.0000 0.0000 -0.0000 0.0000 -0.0002 0.0003 -0.0044 0.0231 0.0
-0.0000 0.0000 -0.0000 0.0000 -0.0000 0.0001 -0.0003 0.0170 -0.0938 0.0
0.0000 0.0000 0.0000 -0.0000 0.0000 -0.0003 0.0024 -0.0078 0.0091 -0.2
-0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0000 -0.0006 0.0113 -0.0708 0.1
0.0000 0.0000 0.0000 -0.0000 -0.0000 -0.0001 0.0001 0.0023 -0.0149 -0.0
⋮
To avoid round-off errors, use exact symbolic computations. For this, create the symbolic Hilbert
matrix.
Hsym = sym(H)
Hsym =
3-299
3 Mathematics
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
Get the value of the condition number. It has been derived by symbolic methods and is free of
numerical errors.
vpa(cond(Hsym))
ans = 24521565858153031724608315432.509
Although its condition number is large, you can compute the exact inverse of the matrix.
Hsym*inv(Hsym)
ans =
3-300
Hilbert Matrices and Their Inverses
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
3-301
3 Mathematics
This example shows how to derive the symbolic stationary distribution of a trivial Markov chain by
computing its eigen decomposition.
The stationary distribution represents the limiting, time-independent, distribution of the states for a
Markov process as the number of steps or transitions increase.
Define (positive) transition probabilities between states A through F as shown in the above image.
syms a b c d e f cCA cCB positive;
Add further assumptions bounding the transition probabilities. This will be helpful in selecting
desirable stationary distributions later.
assumeAlso([a, b, c, e, f, cCA, cCB] < 1 & d == 1);
Define the transition matrix. States A through F are mapped to the columns and rows 1 through 6.
Note the values in each row sum up to one.
P = sym(zeros(6,6));
P(1,1:2) = [a 1-a];
P(2,1:2) = [1-b b];
P(3,1:4) = [cCA cCB c (1-cCA-cCB-c)];
P(4,4) = d;
P(5,5:6) = [e 1-e];
P(6,5:6) = [1-f f];
P
P =
a 1−a 0 0 0 0
1−b b 0 0 0 0
cCA cCB c 1 − cCA − cCB − c 0 0
0 0 0 d 0 0
0 0 0 0 e 1−e
0 0 0 0 1−f f
Compute all possible analytical stationary distributions of the states of the Markov chain. This is the
problem of extracting eig with corresponding eigenvalues that can be equal to 1 for some value of
the transition probabilities.
[V,D] = eig(P');
Analytical eigenvectors
3-302
Markov Chain Analysis and Stationary Distribution
V =
b−1 c − d cCB − b cCA − b cCB + c cCA b − 1
0 0 − 0 0 −1 0
a−1 σ1 a−d
c − d cCA − a cCA − a cCB + c cCB
1 0 0 − 1 0 0 1 0
σ1
c−d
0 0 0 − 0 0 0 0 0
c + cCA + cCB − 1
0 1 0 1 0 1 0 0 0
f −1 f −1
0 0 0 0 0 − 0 −1
e−1 d−e
0 1−d 1 0 0 0 1 0 1
where
σ1 = c + cCA + cCB − 1 a + b − a c − b c + c2 − 1
Analytical eigenvalues
diag(D)
ans =
1
1
c
d
a+b−1
e+f −1
Find eigenvalues that are exactly equal to 1. If there is any ambiguity in determining this condition
for any eigenvalue, stop with an error - this way we are sure that below list of indices is reliable when
this step is successful.
ix = find(isAlways(diag(D) == 1,'Unknown','error'));
diag(D(ix,ix))
ans =
1
1
d
Extract the analytical stationary distributions. The eigenvectors are normalized with the 1-norm or
sum(abs(X)) prior to display.
for k = ix'
V(:,k) = simplify(V(:,k)/norm(V(:,k)),1);
end
Probability = V(:,ix)
Probability =
3-303
3 Mathematics
b−1 σ5
0
a − 1 σ1 σ2
1 σ6
0
σ1 σ2
c−1
0 0−
σ3 c + cCA + cCB − 1
1
0 1
σ3
0 0 0
0 0 0
where
2
b−1
σ1 = 2
+1
a−1
σ2 = σ3 c + cCA + cCB − 1 a + b − c − 1
c−1
2 σ62 σ52
σ3 = + + +1
c + cCA + cCB − 1
2 σ4 σ4
2 2
σ4 = c + cCA + cCB − 1 a+b−c−1
The probability of the steady state being A or B in the first eigenvector case is a function of the
transition probabilities a and b. Visualize this dependency.
fsurf(Probability(1), [0 1 0 1]);
xlabel a
ylabel b
title('Probability of A');
3-304
Markov Chain Analysis and Stationary Distribution
figure(2);
fsurf(Probability(2), [0 1 0 1]);
xlabel a
ylabel b
title('Probability of B');
3-305
3 Mathematics
The stationary distributions confirm the following (Recall states A through F correspond to row
indices 1 through 6 ):
• State C is never reached and is therefore transient i.e. the third row is entirely zero.
• The rest of the states form three groups, { A , B }, { D } and { E , F } that do not communicate
with each other and are recurrent.
3-306
Matrix Rotations and Transformations
This example shows how to do rotations and transforms in 3-D using Symbolic Math Toolbox™ and
matrices.
syms u v
x = cos(u)*sin(v);
y = sin(u)*sin(v);
z = cos(v)*sin(v);
fsurf(x,y,z)
axis equal
Create 3-by-3 matrices Rx, Ry, and Rz representing plane rotations by an angle t about the x-, y-,
and z-axis, respectively.
3-307
3 Mathematics
syms t
Rx =
1 0 0
0 cos t −sin t
0 sin t cos t
Ry =
cos t 0 sin t
0 1 0
−sin t 0 cos t
Rz =
cos t −sin t 0
sin t cos t 0
0 0 1
xyzRx = Rx*[x;y;z];
Rx45 = subs(xyzRx, t, pi/4);
3-308
Matrix Rotations and Transformations
xyzRz = Rz*Rx45;
Rx45Rz90 = subs(xyzRz, t, -pi/2);
3-309
3 Mathematics
xyzRy = Ry*Rx45Rz90;
Rx45Rz90Ry45 = subs(xyzRy, t, -pi/4);
3-310
Matrix Rotations and Transformations
Scale the surface by the factor 3 along the z-axis. You can multiply the expression for z by 3, z =
3*z. The more general approach is to create a scaling matrix, and then multiply the scaling matrix by
the vector of coordinates.
S = [1 0 0; 0 1 0; 0 0 3];
xyzScaled = S*[x; y; z]
xyzScaled =
cos u sin v
sin u sin v
3 cos v sin v
3-311
3 Mathematics
Rotate the scaled surface about the x-, y-, and z-axis by 45 degrees clockwise, in order z, then y,
then x. The rotation matrix for this transformation is as follows.
R = Rx*Ry*Rz
R =
2
cos t −cos t sin t sin t
2 3
σ1 cos t − sin t −cos t sin t
2 2 2
sin t − cos t sin t σ1 cos t
where
2
σ1 = cos t sin t + cos t sin t
xyzScaledRotated = R*xyzScaled;
xyzSR45 = subs(xyzScaledRotated, t, -pi/4);
3-312
Matrix Rotations and Transformations
Rotation matrices are orthogonal matrices. Thus, the transpose of R is also its inverse, and the
determinant of R is 1.
simplify(R.'*R)
ans =
100
010
001
simplify(det(R))
ans = 1
3-313
3 Mathematics
syms x
assume(x > 0)
If you clear the variable x using the command clear x, the MATLAB workspace does not clear the
assumption from the symbolic engine workspace.
clear x
assumptions
ans =
0 < x
To clear the assumption for the variable x, use the command assume(x,'clear').
syms x
assume(x > 0)
assume(x,'clear')
assumptions
ans =
Empty sym: 1-by-0
Alternatively, you can create a fresh symbolic variable without assumptions using syms.
syms x
If you want to clear a symbolic variable and also reset the symbolic engine, use the command clear
all.
syms x positive
clear all
whos
assumptions
ans =
Empty sym: 1-by-0
The following shows how the MATLAB workspace and symbolic engine workspace differ in their
responses to a sequence of commands.
3-314
Clear Assumptions and Reset the Symbolic Engine
assumptions(x)
If the function returns an empty symbolic object, there are no additional assumptions on the variable.
The default assumption is that x represents any complex number. Otherwise, there are additional
assumptions on the value that the variable represents.
For example, while declaring the symbolic variable x, make an assumption that the value of this
variable is a real number.
syms x real
assumptions(x)
ans =
in(x, 'real')
syms z
assume(z ~= 0);
assumptions(z)
ans =
z ~= 0
To see assumptions set on all variables in the MATLAB workspace, use assumptions without input
arguments.
assumptions
ans =
[ in(x, 'real'), z ~= 0]
assume([x z],'clear')
assumptions
ans =
Empty sym: 1-by-0
syms x z
3-315
3 Mathematics
syms x
solve(x^4 == 1, x)
ans =
-1
1
-1i
1i
syms x real
solve(x^4 == 1, x)
ans =
-1
1
Use the assumeAlso function to add the assumption that x is also positive.
assumeAlso(x > 0)
solve(x^4 == 1, x)
ans =
1
Clearing x does not change the underlying assumptions that x is real and positive.
clear x
x = sym('x');
assumptions(x)
solve(x^4 == 1, x)
ans =
[ in(x, 'real'), 0 < x]
ans =
1
syms x
assumptions(x)
ans =
Empty sym: 1-by-0
3-316
Recognize and Avoid Round-Off Errors
In this section...
“Use Symbolic Computations When Possible” on page 3-317
“Perform Calculations with Increased Precision” on page 3-317
“Compare Symbolic and Numeric Results” on page 3-319
“Plot the Function or Expression” on page 3-319
pi
sym(pi)
ans =
3.1416
ans =
pi
heaviside(sin(sym(pi)))
heaviside(sin(pi))
ans =
1/2
ans =
1
syms y
fplot(abs(zeta(1/2 + i*y)), [0 30])
3-317
3 Mathematics
Use the numeric solver vpasolve to approximate the first three zeros of this Zeta function:
ans =
14.134725141734693790457251983562
ans =
21.022039638771554992628479593897
ans =
25.010857580145688763213790992563
1000000001
Now, consider the same function, but slightly increase the real part, ζ + iy . According
2000000000
to the Riemann hypothesis, this function does not have a zero for any real value y. If you use
vpasolve with the 10 significant decimal digits, the solver finds the following (nonexisting) zero of
the Zeta function:
old = digits;
digits(10)
vpasolve(zeta(1000000001/2000000000 + i*y), y, 15)
ans =
14.13472514
3-318
Recognize and Avoid Round-Off Errors
Increasing the number of digits shows that the result is incorrect. The Zeta function
1000000001
ζ + iy does not have a zero for any real value 14 < y < 15:
2000000000
digits(15)
vpasolve(zeta(1000000001/2000000000 + i*y), y, 15)
digits(old)
ans =
14.1347251417347 + 0.000000000499989207306345i
digits(old)
B = besselj(53/2, sym(pi))
B =
(351*2^(1/2)*(119409675/pi^4 - 20300/pi^2 - 315241542000/pi^6...
+ 445475704038750/pi^8 - 366812794263762000/pi^10 +...
182947881139051297500/pi^12 - 55720697512636766610000/pi^14...
+ 10174148683695239020903125/pi^16 - 1060253389142977540073062500/pi^18...
+ 57306695683177936040949028125/pi^20 - 1331871030107060331702688875000/pi^22...
+ 8490677816932509614604641578125/pi^24 + 1))/pi^2
vpa(B, 10)
ans =
-2854.225191
Now, call the Bessel function with the floating-point parameter. Significant difference between these
two approximations indicates that one or both results are incorrect:
besselj(53/2, pi)
ans =
6.9001e-23
Increase the numeric working precision to obtain a more accurate approximation for B:
vpa(B, 50)
ans =
0.000000000000000000000069001456069172842068862232841396473796597233761161
3-319
3 Mathematics
B = besselj(53/2, sym(pi));
vpa(B, 10)
ans =
-2854.225191
Plot this Bessel function for the values of x around 53/2. The function plot shows that the
approximation is incorrect:
syms x
fplot(besselj(x, sym(pi)), [26 27])
3-320
Increase Speed by Reducing Precision
For example, finding the Riemann zeta function of the large matrix C takes a long time. First,
initialize C.
[X,Y] = meshgrid((0:0.0025:.75),(5:-0.05:0));
C = X + Y*i;
Now, repeat this operation with a lower precision by using vpa. First, change the precision used by
vpa to a lower precision of 10 digits by using digits. Then, use vpa to reduce the precision of C and
find zeta(C) again. The operation is significantly faster.
digits(10)
vpaC = vpa(C);
tic
zeta(vpaC);
toc
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.
For larger matrices, the difference in computation time can be even more significant. For example,
consider the 1001-by-301 matrix C.
[X,Y] = meshgrid((0:0.0025:.75),(5:-0.005:0));
C = X + Y*i;
Running zeta(vpa(C)) with 10-digit precision takes 15 minutes, while running zeta(C) takes
three times as long.
digits(10)
vpaC = vpa(C);
tic
zeta(vpaC);
toc
tic
zeta(C);
toc
3-321
3 Mathematics
Note If you want to increase precision, see “Increase Precision of Numeric Calculations” on page 2-
36.
3-322
Prime Factorizations
Prime Factorizations
This example shows how to use some elementary functions on sym objects using the Symbolic Math
Toolbox™.
The built-in integer types of MATLAB® are suitable for integers smaller than 2^64. However, we
want to carry out statistical investigations on prime factorizations of larger integers. To do this, we
use symbolic integers because their size is unlimited. Investigate the integers between N0 + 1 and
23
N0 + 100, where N0 = 3 * 10 . The built-in data types cannot store such values exactly. Thus, wrap
the innermost number with sym to use symbolic representation in the calculations. This avoids
rounding or overflow errors:
N0 = 3*sym(10)^23;
disp(['Roundng error for doubles: ' char(3*10^23 - N0)]);
In arithmetical operations, symbolic numbers can be combined with doubles, and the conversion
takes place before the operation. Thus, the following definition cannot cause rounding errors:
A = N0 + (1:100);
Compute the prime factorizations of the elements of A using factor. The number of prime factors
differs. Arrays cannot contain vectors of different lengths, but cell arrays can. To avoid memory re-
allocations, initialize the cell array first, then compute the factorizations in a loop:
A more efficient approach is to use arrayfun. Setting UniformOutput to false returns the result
as a cell array.
Bcell{1:5}
Obtain the largest prime factor using max. Note that if the output consists of sym objects, the option
UniformOutput always has to be set to false even if the output is uniform.
3-323
3 Mathematics
Mcell{1:5}
ans = 2303316007278478583
ans = 171805943
ans = 549797184491917
ans = 76910994983
ans = 3610146697
Convert the cell array to a symbolic vector, and investigate the ratio of the lengths of the largest
prime factor and the number as a whole. You can apply arithmetical operations elementwise to
symbolic vectors, in the same way as for doubles. Note that most statistical functions require their
arguments to be double-precision numbers.
M = [Mcell{:}];
histogram(double(log(M)./log(A)), 20);
title('Ratio of lengths of the largest prime factor and the number');
In the same way, now investigate the distribution of the number of prime factors. Here, the result
contains uniform numeric data. Therefore, you do not need to set UniformOutput to false.
3-324
Prime Factorizations
A(omega == 1)
We check that the maximal prime factors are about equally often in the residue classes 1 and 3
modulo 4. Note that equations of sym objects are symbolic objects themselves and not logical values;
we have to convert them before we can sum them:
sum(logical(mod(M, 4) == 1))
ans = 49
sum(logical(mod(M, 4) == 3))
ans = 51
3-325
3 Mathematics
This example shows how to work with large integers and their decimal representation using the
Symbolic Math Toolbox™.
Palindromes
A character string is called a palindrome if it is the same when read backwards. A positive integer is
called a palindrome if its decimal representation is a palindrome. For example, 191, 313 and 5885 are
all palindromes.
• Start with any positive integer N and add it to its mirror image.
• Repeat this step with the resulting number until you obtain a palindrome.
For example, let N=89; then the first 3 iterations give ...
89 + 98 = 187
3-326
Handling Large Integers to Solve the 196 Problem
187
968
1837
9218
17347
91718
173437
907808
1716517
8872688
17735476
85189247
159487405
664272356
1317544822
3602001953
7193004016
13297007933
47267087164
93445163438
176881317877
955594506548
1801200002107
8813200023188
Finished in iteration 24
The 196-Problem
The problem is still open, and palindrome aficionados have invested many CPU years into the
N = 196 case which gave the problem its name. In order to play with this problem in MATLAB®,
3-327
3 Mathematics
symbolic integers are useful because their size is unlimited. Use the function sym to convert strings
of decimal digits to symbolic integers, and char (not num2str !) to convert back.
Investigating the famous N = 196 case produces truly huge numbers. To see how many decimal digits
an integer has, simply use log10 :
N = sym(196);
for k=0:1000
s1 = char(N);
s2 = fliplr(s1);
N = N + sym(s2);
end
disp(['Number of digits after ' num2str(k) ' iterations: ' char(ceil(log10(N)))]);
3-328
4
Graphics
MATLAB® provides many techniques for plotting numerical data. Graphical capabilities of MATLAB
include plotting tools, standard plotting functions, graphic manipulation and data exploration tools,
and tools for printing and exporting graphics to standard formats. Symbolic Math Toolbox™ expands
these graphical capabilities and lets you plot symbolic functions using:
Plot the symbolic expression sin(6x) by using fplot. By default, fplot uses the range −5 < x < 5.
syms x
fplot(sin(6*x))
Plot a symbolic expression or function in polar coordinates r (radius) and θ (polar angle) by using
ezpolar. By default, ezpolar plots a symbolic expression or function over the interval 0 < θ < 2π.
4-2
Create Plots of Symbolic Expressions
syms t
ezpolar(sin(6*t))
As an alternative to plotting expressions symbolically, you can substitute symbolic variables with
numeric values by using subs. Then, you can use these numeric values with plotting functions in
MATLAB.
In the following expressions u and v, substitute the symbolic variables x and y with the numeric
values defined by meshgrid.
syms x y
u = sin(x^2 + y^2);
v = cos(x*y);
[X,Y] = meshgrid(-1:.1:1,-1:.1:1);
U = subs(u,[x y],{X,Y});
V = subs(v,[x y],{X,Y});
Now, you can plot U and V by using standard MATLAB plotting functions.
Create a plot of the vector field defined by the functions U(X,Y) and V(X,Y) by using the MATLAB
quiver function.
quiver(X,Y,U,V)
4-3
4 Graphics
Plot several functions on one graph by adding the functions sequentially. After plotting the first
function, add successive functions by using the hold on command. The hold on command keeps
the existing plots. Without the hold on command, each new plot replaces any existing plot. After the
hold on command, each new plot appears on top of existing plots. Switch back to the default
behavior of replacing plots by using the hold off command.
Plot f = exsin(20x) using fplot. Show the bounds of f by superimposing plots of ex and −ex as
dashed red lines. Set the title by using the DisplayName property of the object returned by fplot.
syms x y
f = exp(x)*sin(20*x)
f = sin 20 x ex
4-4
Create Plots of Symbolic Expressions
Display several functions side-by-side in one figure by dividing the figure window into several
subplots using subplot. The command subplot(m,n,p) divides the figure into a m-by-n matrix of
subplots and selects the subplot p. Display multiple plots in separate subplots by selecting the
subplot and using plotting commands. Plotting into multiple subplots is useful for side-by-side
comparisons of plots.
Compare plots of sin((x2 + y2)/a) for a = 10, 20, 50, 100 by using subplot to create side-by-side
subplots.
syms x y a
f = sin((x^2 + y^2)/a);
subplot(2,2,1)
fsurf(subs(f,a,10))
title("a = 10")
subplot(2,2,2)
fsurf(subs(f,a,20))
title("a = 20")
subplot(2,2,3)
fsurf(subs(f,a,50))
title("a = 50")
subplot(2,2,4)
4-5
4 Graphics
fsurf(subs(f,a,100))
title("a = 100")
Plot numeric and symbolic data on the same graph by using MATLAB and Symbolic Math Toolbox
functions together.
For numeric values of x between [ − 5, 5], return a noisy sine curve by finding y = sin(x) and adding
random values to y. View the noisy sine curve by using scatter to plot the points (x1, y1), (x2, y2),
and so on.
figure
rng("default")
x = linspace(-5,5);
y = sin(x) + (-1).^randi(10,1,100).*rand(1,100)./2;
scatter(x,y)
Show the underlying structure in the points by superimposing a plot of the sine function. First, use
hold on to retain the scatter plot. Then, use fplot to plot the sine function.
hold on
syms t
fplot(sin(t))
hold off
4-6
Create Plots of Symbolic Expressions
Combine symbolic and numeric plots in 3-D by using MATLAB and Symbolic Math Toolbox plotting
functions. Symbolic Math Toolbox provides these 3-D plotting functions:
x = 1 − t sin 100t
y = 1 − t cos 100t
z = 1 − x2 − y2 .
syms t
x = (1-t)*sin(100*t);
y = (1-t)*cos(100*t);
z = sqrt(1 - x^2 - y^2);
fplot3(x,y,z,[0 1])
title("Symbolic 3-D Parametric Line")
4-7
4 Graphics
Superimpose a plot of a sphere with radius 1 and center at (0,0,0). Find points on the sphere
numerically by using sphere. Plot the sphere by using mesh. The resulting plot shows the symbolic
parametric line wrapped around the top hemisphere.
hold on
[X,Y,Z] = sphere;
mesh(X,Y,Z)
colormap(gray)
title("Symbolic Parametric Plot and a Sphere")
hold off
4-8
Create Plots of Symbolic Expressions
4-9
4 Graphics
This example shows how to transform a symbolic expression from spherical coordinates to Cartesian
coordinates, and plot the converted expression analytically without explicitly generating numerical
data.
In the spherical coordinate system, the location of a point P can be characterized by three variables.
Different textbooks have different conventions for the variables used to describe spherical
coordinates. For these examples, this convention is used:
The transformation of the point P from spherical coordinates (ρ, θ, ϕ) to Cartesian coordinates (x, y, z)
is given by
x = ρ sin ϕ cos θ,
y = ρ sin ϕ sin θ,
z = ρ cos ϕ .
By transforming symbolic expressions from spherical coordinates to Cartesian coordinates, you can
then plot the expressions using Symbolic Math Toolbox™ graphics functions, such as fplot3 and
fsurf.
4-10
Transform Spherical Coordinates to Cartesian Coordinates and Plot Analytically
Transform the spherical coordinates to Cartesian coordinates (xP, yP, zP). Because the converted
coordinates contain numerical values, use plot3 to plot the point.
rho = 1;
theta = 1.2;
phi = 0.75;
x_P = rho*sin(phi)*cos(theta);
y_P = rho*sin(phi)*sin(theta);
z_P = rho*cos(phi);
plot3(x_P,y_P,z_P,'ko','MarkerSize',10,'MarkerFaceColor','k')
hold on
Label each axis in the plot, change the line of sight, and set the axis scaling to use equal data units.
xlabel('x')
ylabel('y')
zlabel('z')
view([75 40])
axis equal;
Next, plot the line projection of the point P to the origin. This line projection in spherical coordinates
is parameterized by (r, 1 . 2, 0 . 75), with r ranging from 0 to 1. Specify this line parameterization as
symbolic expressions, and plot it by using fplot3.
syms r
xr = r*sin(phi)*cos(theta);
yr = r*sin(phi)*sin(theta);
zr = r*cos(phi);
fplot3(xr,yr,zr,[0 rho],'k')
Plot the vertical line projection to the xy-plane. This line projection in Cartesian coordinates is
parameterized by (xP, yP, z), with z ranging from 0 to zP.
syms z
fplot3(sym(x_P),sym(y_P),z,[0 z_P],'k')
Plot the top horizontal line projection to the z-axis. This line projection in Cartesian coordinates is
parameterized by (r sinϕ cosθ, r sinϕ sinθ, zP), with r ranging from 0 to 1.
fplot3(xr,yr,sym(z_P),[0 rho],'k--')
Plot the bottom horizontal line projection to the z-axis. This line projection in Cartesian coordinates is
parameterized by (r sinϕ cosθ, r sinϕ sinθ, 0), with r ranging from 0 to 1.
fplot3(xr,yr,sym(0),[0 rho],'k')
4-11
4 Graphics
Next, plot the plane that shows the span of the azimuthal angle θ in the xy-plane with the coordinate
z = 0.
syms s t
x_azimuthal = s*sin(phi)*cos(t);
y_azimuthal = s*sin(phi)*sin(t);
fsurf(x_azimuthal,y_azimuthal,0,[0 rho 0 theta],'FaceColor','b','EdgeColor','none')
Plot the plane that shows the span of the polar angle ϕ.
syms u v
x_polar = u*sin(v)*cos(theta);
y_polar = u*sin(v)*sin(theta);
z_polar = u*cos(v);
fsurf(x_polar,y_polar,z_polar,[0 rho 0 phi],'FaceColor','g','EdgeColor','none')
hold off
4-12
Transform Spherical Coordinates to Cartesian Coordinates and Plot Analytically
Plot a Sphere
In spherical coordinates, the sphere is parameterized by (4, θ, ϕ), with ϕ ranging from 0 to π and θ
ranging from 0 to 2π. Transform spherical coordinates to Cartesian coordinates by specifying the
surface parameterization as symbolic expressions. Then plot the sphere by using fsurf.
4-13
4 Graphics
In spherical coordinates, the sphere is parameterized by (4, θ, ϕ), with ϕ ranging from 0 to π/2 and θ
ranging from 0 to 2π. Transform spherical coordinates to Cartesian coordinates by specifying the
surface parameterization as symbolic expressions. Then plot the half sphere by using fsurf.
4-14
Transform Spherical Coordinates to Cartesian Coordinates and Plot Analytically
Plot a parameterized surface whose radial distance in spherical coordinates is related to the
azimuthal and polar angles.
The surface has radial coordinates ρ = 2 + sin(5ϕ + 7θ), with ϕ ranging from 0 to π and θ ranging
from 0 to 2π. Transform spherical coordinates to Cartesian coordinates by specifying the surface
parameterization as symbolic expressions. Then plot the parameterized surface by using fsurf.
4-15
4 Graphics
4-16
Tangent Plane and Normal Line of Implicit Surface
Since R2021b
This example shows how to find the tangent plane and the normal line of an implicit surface. This
example uses symbolic matrix variables (with the symmatrix data type) for compact mathematical
notation.
A surface can be defined implicitly, such as the sphere x2 + y2 + z2 = R2. In general, an implicitly
defined surface is expressed by the equation f (x, y, z) = k. This example finds the tangent plane and
the normal line of a sphere with radius R = 14.
Create a symbolic matrix variable r to represent the ⟨x, y, z⟩ coordinates. Define the spherical function
as f (r) = r ⋅ r.
f = r rT
The implicit equation f (r) = 14 represents a sphere. Convert the equation to the syms data type using
symmatrix2sym. Plot the equation by using the fimplicit3 function.
fimplicit3(feqn)
axis equal
axis([-6 6 -6 6 -6 6])
4-17
4 Graphics
Next, find the tangent plane and normal line at the point r0 = ⟨x0, y0, z0⟩.
Recall that the gradient vector of f is ∇ f (r) = ⟨f x(r), f y(r), f z(r)⟩. The equation for the tangent plane at
the point r0 is then given by f x(r0)(x − x0) + f y(r0)(y − y0) + f z(r0)(z − z0) = 0. In compact
mathematical notation, the tangent plane equation can be written as ∇ f (r0) ⋅ (r − r0) = 0.
Find the gradient of f (r) using the gradient function. Note that the result is a 3-by-1 symbolic
matrix variable.
fgrad = gradient(f,r)
fgrad = 2 r T
size(fgrad)
ans = 1×2
3 1
Define the equation for the tangent plane. Use the subs function to evaluate the gradient at the point
r0 = ⟨1, − 2, 3⟩.
r0 = [-2,1,3];
fplane = (r-r0)*subs(fgrad,r,r0)
fplane =
4-18
Tangent Plane and Normal Line of Implicit Surface
2 −Σ1 + r Σ1T
where
Σ1 = −2 1 3
Plot the point r0 using plot3, and plot the tangent plane using fimplicit3.
hold on
plot3(r0(1),r0(2),r0(3),'ro',MarkerSize = 10,MarkerFaceColor = 'r')
fimplicit3(symmatrix2sym(fplane == 0))
The equation for the normal line at the point r0 is given by n(t) = ⟨x0, y0, z0⟩ + t ⟨f x(r0), f y(r0), f z(r0)⟩.
In compact mathematical notation, the equation can be written as n(t) = r0 + t ∇ f (r0).
syms t
n = r0 + t*subs(fgrad,r,r0).'
n =
Σ1 + 2 t Σ1
where
Σ1 = −2 1 3
4-19
4 Graphics
Convert the normal line equation to the syms data type using symmatrix2sym. Extract the
parametric curves x(t), y(t), and z(t) for the normal line by indexing into n. Plot the normal line using
fplot3.
n = symmatrix2sym(n)
n = −4 t − 2 2 t + 1 6 t + 3
fplot3(n(1),n(2),n(3),[0 1],'r->')
4-20
Analytical Plotting with Symbolic Math Toolbox
Symbolic Math Toolbox™ provides analytical plotting of mathematical expressions without explicitly
generating numerical data. These plots can be in 2-D or 3-D as lines, curves, contours, surfaces, or
meshes.
These examples feature the following graphics functions that accept symbolic functions, expressions,
and equations as inputs:
• fplot
• fimplicit
• fcontour
• fplot3
• fsurf
• fmesh
• fimplicit3
4-21
4 Graphics
fplot([sin(x),cos(x),tan(x)])
syms x a
expr = sin(exp(x/a));
fplot(subs(expr,a,[1,2,4]))
legend show
4-22
Analytical Plotting with Symbolic Math Toolbox
Plot a function f (x) = x (1 + x) + 2, its derivative df (x)/dx, and its integral ∫ f (x) dx.
syms f(x)
f(x) = x*(1 + x) + 2
f(x) = x x + 1 + 2
f_diff = diff(f(x),x)
f_diff = 2 x + 1
f_int = int(f(x),x)
f_int =
x 2 x2 + 3 x + 12
6
fplot([f,f_diff,f_int])
legend({'$f(x)$','$df(x)/dx$','$\int f(x)dx$'},'Interpreter','latex','FontSize',12)
4-23
4 Graphics
Find the x0 that minimizes a function g(x, a) by solving the differential equation dg(x, a)/dx = 0.
syms g(x,a);
assume(a>0);
g(x,a) = a*x*(a + x) + 2*sqrt(a)
g(x, a) = 2 a + a x a + x
x0 = solve(diff(g,x),x)
x0 =
a
−
2
fplot(g(x0,a),[0 5])
xlabel('a')
title('Minimum Value of $g(x_0,a)$ Depending on $a$','interpreter','latex')
4-24
Analytical Plotting with Symbolic Math Toolbox
syms x y
r = 1:10;
fimplicit(x^2 + y^2 == r.^2,[-10 10])
axis square;
4-25
4 Graphics
syms x y f(x,y)
f(x,y) = x^3 - 4*x - y^2;
fcontour(f,[-3 3 -4 4],'LevelList',-6:6);
colorbar
title 'Contour of Some Elliptic Curves'
4-26
Analytical Plotting with Symbolic Math Toolbox
syms f(x)
f(x) = x*exp(-x)*sin(5*x) -2;
fplot(f,[0,3])
xs = 0:1/3:3;
ys = double(subs(f,xs));
Plot the data points and the spline interpolant that approximates the analytic function.
hold on
plot(xs,ys,'*k','DisplayName','Data Points')
fplot(@(x) spline(xs,ys,x),[0 3],'DisplayName','Spline interpolant')
grid on
legend show
hold off
4-27
4 Graphics
Find the Taylor expansion of cos(x) near x = 0 up to 5th and 7th orders.
syms x
t5 = taylor(cos(x),x,'Order',5)
t5 =
x4 x2
− +1
24 2
t7 = taylor(cos(x),x,'Order',7)
t7 =
x6 x4 x2
− + − +1
720 24 2
fplot(cos(x))
hold on;
fplot([t5 t7],'--')
axis([-4 4 -1.5 1.5])
title('Taylor Series Approximations of cos(x) up to 5th and 7th Order')
legend show
hold off;
4-28
Analytical Plotting with Symbolic Math Toolbox
A square wave of period 2π and amplitude π/4 can be approximated by the Fourier series expansion
1 1
sin(t) + sin(3t) + sin(5t) + . . . .
3 5
syms t y(t)
y(t) = piecewise(0 < mod(t,2*pi) <= pi, pi/4, pi < mod(t,2*pi) <= 2*pi, -pi/4);
fplot(y)
hold on;
n = 6;
yFourier = cumsum(sin((1:2:2*n-1)*t)./(1:2:2*n-1));
fplot(yFourier,'LineWidth',1)
hold off
4-29
4 Graphics
The Fourier series approximation overshoots at a jump discontinuity and the "ringing" does not die
out as more terms are added to the approximation. This behavior is also known as the Gibbs
phenomenon.
Plot a helix that is defined by (sin(t), cos(t), t/4) for t from –10 to 10.
syms t
fplot3(sin(t),cos(t),t/4,[-10 10],'LineWidth',2)
view([-45 45])
4-30
Analytical Plotting with Symbolic Math Toolbox
Plot a surface defined by log(x) + exp(y). Analytical plotting using fsurf (without generating
numerical data) shows the curved areas and asymptotic regions near x = 0.
syms x y
fsurf(log(x) + exp(y),[0 2 -1 3])
xlabel('x')
4-31
4 Graphics
Plot a Multivariate Surface (x(u, v), y(u, v), z(u, v)) Using fsurf
x(u, v) = u
4-32
Analytical Plotting with Symbolic Math Toolbox
Plot a Multivariate Surface (x(s, t), y(s, t), z(s, t)) Using fmesh
x = r cos(s) sin(t)
y = r sin(s) sin(t)
z = r cos(t)
where r = 8 + sin(7s + 5t). Show the plotted surface as meshes by using fmesh. Set the plot interval
of s from 0 to 2π and t from 0 to π.
syms s t
r = 8 + sin(7*s + 5*t);
x = r*cos(s)*sin(t);
y = r*sin(s)*sin(t);
z = r*cos(t);
fmesh(x,y,z,[0 2*pi 0 pi],'Linewidth',2)
axis equal
4-33
4 Graphics
syms x y z
f = 1/x^2 - 1/y^2 + 1/z^2;
fimplicit3(f)
4-34
Analytical Plotting with Symbolic Math Toolbox
Plot the surface sin(x) + sin(y) − (x2 + y2)/20 using fsurf. You can show the contours on the same
graph by setting 'ShowContours' to 'on'.
syms x y
f = sin(x)+sin(y)-(x^2+y^2)/20
f =
x2 y2
sin x + sin y − −
20 20
fsurf(f,'ShowContours','on')
view(-19,56)
4-35
4 Graphics
Next, plot the contours on a separate graph with finer contour lines.
fcontour(f,[-5 5 -5 5],'LevelStep',0.1,'Fill','on')
colorbar
Find the gradient of the surface. Create 2-D grids using meshgrid and substitute the grid
coordinates to evaluate the gradient numerically. Show the gradient using quiver.
hold on
Fgrad = gradient(f,[x,y])
Fgrad =
x
cos x −
10
y
cos y −
10
[xgrid,ygrid] = meshgrid(-5:5,-5:5);
Fx = subs(Fgrad(1),{x,y},{xgrid,ygrid});
Fy = subs(Fgrad(2),{x,y},{xgrid,ygrid});
quiver(xgrid,ygrid,Fx,Fy,'k')
hold off
4-36
Analytical Plotting with Symbolic Math Toolbox
See Also
Functions
fplot | fimplicit | fcontour | fplot3 | fsurf | fmesh | fimplicit3
4-37
4 Graphics
This example shows how to simulate the motion of a simple pendulum using Symbolic Math
Toolbox™. Derive the equation of motion of the pendulum, then solve the equation analytically for
small angles and numerically for any angle.
The pendulum is a simple mechanical system that follows a differential equation. The pendulum is
initially at rest in a vertical position. When the pendulum is displaced by an angle θ and released, the
force of gravity pulls it back towards its resting position. Its momentum causes it to overshoot and
come to an angle −θ (if there are no frictional forces), and so on. The restoring force along the
motion of the pendulum due to gravity is −mgsinθ. Thus, according to Newton's second law, the mass
times the acceleration must equal −mgsinθ.
syms m a g theta(t)
eqn = m*a == -m*g*sin(theta)
eqn(t) = a m = −g m sin θ t
For a pendulum with length r , the acceleration of the pendulum bob is equal to the angular
acceleration times r .
2
d θ
a=r .
dt2
syms r
eqn = subs(eqn,a,r*diff(theta,2))
eqn(t) =
∂2
mr θ t = −g m sin θ t
∂t2
eqn = isolate(eqn,diff(theta,2))
eqn =
4-38
Simulate the Motion of the Periodic Swing of a Pendulum
∂2 g sin θ t
θt =−
∂t2 r
Collect the constants g and r into a single parameter, which is also known as the natural frequency.
g
ω0 = r
.
syms omega_0
eqn = subs(eqn,g/r,omega_0^2)
eqn =
∂2
θ t = −ω02 sin θ t
∂t2
The equation of motion is nonlinear, so it is difficult to solve analytically. Assume the angles are small
and linearize the equation by using the Taylor expansion of sinθ.
syms x
approx = taylor(sin(x),x,'Order',2);
approx = subs(approx,x,theta(t))
approx = θ t
eqnLinear = subs(eqn,sin(theta(t)),approx)
eqnLinear =
∂2
θ t = −ω02 θ t
∂t2
Solve the equation eqnLinear by using dsolve. Specify initial conditions as the second argument.
Simplify the solution by assuming ω0 is real using assume.
thetaSol(t) =
θt0 sin ω0 t
θ0 cos ω0 t +
ω0
The term ω0t is called the phase. The cosine and sine functions repeat every 2π. The time needed to
change ω0t by 2π is called the time period.
2π r
T= = 2π .
ω0 g
4-39
4 Graphics
The time period T is proportional to the square root of the length of the pendulum and it does not
depend on the mass. For linear equation of motion, the time period does not depend on the initial
conditions.
gValue = 9.81;
rValue = 1;
omega_0Value = sqrt(gValue/rValue);
T = 2*pi/omega_0Value;
Substitute the physical parameters and initial conditions into the general solution.
fplot(thetaSolPlot(t*T)/pi, [0 5]);
grid on;
title('Harmonic Pendulum Motion');
xlabel('t/T');
ylabel('\theta/\pi');
4-40
Simulate the Motion of the Periodic Swing of a Pendulum
After finding the solution for θ(t), visualize the motion of the pendulum.
x_pos = sin(thetaSolPlot);
y_pos = -cos(thetaSolPlot);
fanimator(@fplot,x_pos,y_pos,'ko','MarkerFaceColor','k','AnimationRange',[0 5*T]);
hold on;
fanimator(@(t) plot([0 x_pos(t)],[0 y_pos(t)],'k-'),'AnimationRange',[0 5*T]);
fanimator(@(t) text(-0.3,0.3,"Timer: "+num2str(t,2)+" s"),'AnimationRange',[0 5*T]);
4-41
4 Graphics
Enter the command playAnimation to play the animation of the pendulum motion.
4-42
Simulate the Motion of the Periodic Swing of a Pendulum
To understand the nonlinear motion of the pendulum, visualize the pendulum path by using the
equation for total energy. The total energy is conserved.
1 2 dθ 2
E= mr + m g r 1 − cos θ
2 dt
2
Use the trigonometric identity 1 − cosθ = 2sin (θ/2) and the relation ω0 = g/r to rewrite the scaled
energy.
E 1 dθ 2 θ 2
= + 2ω0 sin
mr 2 2 dt 2
Since energy is conserved, the motion of the pendulum can be described by constant energy paths in
the phase space. The phase space is an abstract space with the coordinates θ and dθ/dt. Visualize
these paths using fcontour.
syms theta theta_t omega_0
E(theta, theta_t, omega_0) = (1/2)*(theta_t^2+(2*omega_0*sin(theta/2))^2);
Eplot(theta, theta_t) = subs(E,omega_0,omega_0Value);
figure;
fc = fcontour(Eplot(pi*theta, 2*omega_0Value*theta_t), 2*[-1 1 -1 1], ...
'LineWidth', 2, 'LevelList', 0:5:50, 'MeshDensity', 1+2^8);
grid on;
4-43
4 Graphics
The constant energy contours are symmetric about the θ axis and dθ/dt axis, and are periodic along
the θ axis. The figure shows two regions of distinct behavior.
The lower energies of the contour plot close upon themselves. The pendulum swings back and forth
between two maximum angles and velocities. The kinetic energy of the pendulum is not enough to
overcome gravitational energy and enable the pendulum to make a full loop.
The higher energies of the contour plot do not close upon themselves. The pendulum always moves in
one angular direction. The kinetic energy of the pendulum is enough to overcome gravitational
energy and enable the pendulum to make a full loop.
4-44
Simulate the Motion of the Periodic Swing of a Pendulum
The nonlinear equations of motion are second-order differential equations. Numerically solve these
equations by using the ode45 solver. Because ode45 accepts only first-order systems, reduce the
system to a first-order system. Then, generate function handles that are the input to ode45.
eqs(t) =
∂
θ t = θt t
∂t
∂
θ t = −ω02 sin θ t
∂t t
eqs = subs(eqs,omega_0,omega_0Value);
vars = [theta, theta_t];
Find the mass matrix M of the system and the right sides of the equations F.
[M,F] = massMatrixForm(eqs,vars)
M =
10
01
F =
θt t
981 sin θ t
−
100
dx
M t, x t = F t, x t .
dt
To simplify further computations, rewrite the system in the form dx/dt = f (t, x(t)).
f = M\F
f =
θt t
981 sin θ t
−
100
4-45
4 Graphics
Convert f to a MATLAB function handle by using odeFunction. The resulting function handle is the
input to the MATLAB ODE solver ode45.
f = odeFunction(f, vars)
Solve the ODE for the closed energy contours by using ode45.
From the energy contour plot, closed contours satisfy the condition θ0 = 0, θt0 /2ω0 ≤ 1. Store the
initial conditions of θ and dθ/dt in the variable x0.
x0 = [0; 1.99*omega_0Value];
Specify a time interval from 0 s to 10 s for finding the solution. This interval allows the pendulum to
go through two full periods.
tInit = 0;
tFinal = 10;
sols.y(1,:) represents the angular displacement θ and sols.y(2,:) represents the angular
velocity dθ/dt.
figure;
yyaxis left;
plot(sols.x, sols.y(1,:), '-o');
ylabel('\theta (rad)');
yyaxis right;
plot(sols.x, sols.y(2,:), '-o');
ylabel('\theta_t (rad/s)');
grid on;
title('Closed Path in Phase Space');
xlabel('t (s)');
4-46
Simulate the Motion of the Periodic Swing of a Pendulum
4-47
4 Graphics
Enter the command playAnimation to play the animation of the pendulum motion.
4-48
Simulate the Motion of the Periodic Swing of a Pendulum
Solve the ODE for the open energy contours by using ode45. From the energy contour plot, open
contours satisfy the condition θ0 = 0, θt0 /2ω0 > 1.
x0 = [0; 2.01*omega_0Value];
sols = ode45(f, [tInit, tFinal], x0);
figure;
yyaxis left;
plot(sols.x, sols.y(1,:), '-o');
ylabel('\theta (rad)');
yyaxis right;
plot(sols.x, sols.y(2,:), '-o');
ylabel('\theta_t (rad/s)');
grid on;
title('Open Path in Phase Space');
xlabel('t (s)');
4-49
4 Graphics
4-50
Simulate the Motion of the Periodic Swing of a Pendulum
Enter the command playAnimation to play the animation of the pendulum motion.
4-51
4 Graphics
See Also
Functions
diff | subs | dsolve | isolate | fplot | fanimator | playAnimation
4-52
Animation and Solution of Double Pendulum Motion
This example shows how to model the motion of a double pendulum by using MATLAB® and Symbolic
Math Toolbox™.
Solve the motion equations of a double pendulum and create an animation to model the double
pendulum motion.
The following figure shows the model of a double pendulum. The double pendulum consists of two
pendulum bobs and two rigid rods.
Describe the motion of the double pendulum by defining the state variables:
For simplicity, ignore the masses of the two rigid rods. Specify all variables by using syms.
syms theta_1(t) theta_2(t) L_1 L_2 m_1 m_2 g
Find the velocities by differentiating the displacements with respect to time using the diff function.
vx_1 = diff(x_1);
vy_1 = diff(y_1);
4-53
4 Graphics
vx_2 = diff(x_2);
vy_2 = diff(y_2);
ax_1 = diff(vx_1);
ay_1 = diff(vy_1);
ax_2 = diff(vx_2);
ay_2 = diff(vy_2);
First, specify the tension of the first rod as T1, and the tension of the second rod T2.
Next, construct free-body diagrams of the forces that act on both masses.
Evaluate the forces acting on m1. Define the equations of motion of the first bob by balancing the
horizontal and vertical force components. Specify these two equations as symbolic equations eqx_1
and eqy_1.
eqx_1 =
∂ 2 ∂2
−m1 L1 sin θ1 t θ1 t − L1 cos θ1 t θ1 t = T2 sin θ2 t − T1 sin θ1 t
∂t ∂t2
eqy_1 =
∂2 ∂ 2
m1 L1 sin θ1 t θ1 t + L1 cos θ1 t θ1 t = T1 cos θ1 t − g m1 − T2 cos θ2 t
∂t 2 ∂t
4-54
Animation and Solution of Double Pendulum Motion
Evaluate the forces acting on m2. Define the equations of motion of the second bob by balancing the
horizontal and vertical force components. Specify these two equations as symbolic equations eqx_2
and eqy_2.
eqx_2 =
∂ 2 ∂ 2 ∂2 ∂2
−m2 L1 sin θ1 t θ t + L2 sin θ2 t θ t − L1 cos θ1 t θ1 t − L2 cos θ2 t θ2 t
∂t 1 ∂t 2 ∂t2 ∂t2
= −T2 sin θ2 t
eqy_2 =
∂ 2 ∂ 2 ∂2 ∂2
m2 L1 cos θ1 t θ t + L2 cos θ2 t θ t + L1 sin θ1 t θ1 t + L2 sin θ2 t θ2 t
∂t 1 ∂t 2 ∂t 2
∂t2
= T2 cos θ2 t − g m2
Four equations of motion describe the kinematics of the double pendulum. Evaluate the forces acting
on the rods and reduce the set of four equations to two equations.
The equations of motion have four unknowns: θ1, θ2, T1, and T2. Evaluate the two unknowns T1 and
T2 from eqx_1 and eqy_1. Use solve function to find T1 and T2.
First, define the values for the masses in kg, the rod lengths in m, and the gravity in m/s2 (SI units).
Substitute these values into the two reduced equations.
4-55
4 Graphics
L_1 = 1;
L_2 = 1.5;
m_1 = 2;
m_2 = 1;
g = 9.8;
eqn_1 = subs(eqRed_1)
eqn_1 =
∂ 2 ∂2 2
3 sin θ2 t θ t 3 cos θ2 t θ2 t 2 sin θ2 t cos θ1 t σ1 + sin θ1
∂t 2 ∂ 2 ∂t2
cos θ1 t σ1 − − sin θ1 t θ t + =−
2 ∂t 1 2 cos θ1 t sin θ2 t − cos θ
where
∂2
σ1 = θ1 t
∂t2
eqn_2 = subs(eqRed_2)
eqn_2 =
∂ 2 ∂2 2
3 cos θ2 t θ t 3 sin θ2 t θ2 t 2 cos θ2 t cos θ1 t σ1 + sin θ1 t
∂ 2 ∂t 2 ∂t2
cos θ1 t θ t + + sin θ1 t σ1 + =
∂t 1 2 2 cos θ1 t sin θ2 t − cos θ2
where
∂2
σ1 = θ1 t
∂t2
The two equations are nonlinear second-order differential equations. To solve these equations,
convert them to first-order differential equations by using the odeToVectorField function.
[V,S] = odeToVectorField(eqn_1,eqn_2);
The elements of the vector V represent the first-order differential equations that are equal to the time
derivative of the elements of S. The elements of S are the state variables θ2, dθ2 /dt, θ1, and dθ1 /dt.
The state variables describe the angular displacements and velocities of the double pendulum.
S
S =
θ2
Dtheta2
θ1
Dtheta1
Next, convert the first order-differential equations to a MATLAB function with the handle M.
M = matlabFunction(V,'vars',{'t','Y'});
Define the initial conditions of the state variables as [pi/4 0 pi/6 0]. Use the ode45 function to
solve for the state variables. The solutions are a function of time within the interval [0 10].
initCond = [pi/4 0 pi/6 0];
sols = ode45(M,[0 10],initCond);
4-56
Animation and Solution of Double Pendulum Motion
plot(sols.x,sols.y)
legend('\theta_2','d\theta_2/dt','\theta_1','d\theta_1/dt')
title('Solutions of State Variables')
xlabel('Time (s)')
ylabel('Solutions (rad or rad/s)')
First, create four functions that use deval to evaluate the coordinates of both pendulums from the
solutions sols.
x_1 = @(t) L_1*sin(deval(sols,t,3));
y_1 = @(t) -L_1*cos(deval(sols,t,3));
x_2 = @(t) L_1*sin(deval(sols,t,3))+L_2*sin(deval(sols,t,1));
y_2 = @(t) -L_1*cos(deval(sols,t,3))-L_2*cos(deval(sols,t,1));
Next, create a stop-motion animation object of the first pendulum bob by using the fanimator
function. By default, fanimator creates an animation object with 10 generated frames per unit time
within the range of t from 0 to 10. Plot the coordinates by using the plot function. Set the x-axis and
y-axis to be equal length.
fanimator(@(t) plot(x_1(t),y_1(t),'ro','MarkerSize',m_1*10,'MarkerFaceColor','r'));
axis equal;
Next, add the animation objects of the first rigid rod, the second pendulum bob, and the second rigid
rod.
4-57
4 Graphics
hold on;
fanimator(@(t) plot([0 x_1(t)],[0 y_1(t)],'r-'));
fanimator(@(t) plot(x_2(t),y_2(t),'go','MarkerSize',m_2*10,'MarkerFaceColor','g'));
fanimator(@(t) plot([x_1(t) x_2(t)],[y_1(t) y_2(t)],'g-'));
Add a piece of text to count the elapsed time by using the text function. Use num2str to convert the
time parameter to a string.
Use the command playAnimation to play the animation of the double pendulum.
4-58
Animation and Solution of Double Pendulum Motion
4-59
4 Graphics
This example shows how to model the motion of an automotive piston by using MATLAB® and
Symbolic Math Toolbox™.
Define the motion of an automotive piston and create an animation to model the piston motion.
The following figure shows the model of an automotive piston. The moving parts of the piston consist
of a connecting rod (red line), a piston crank (green line), and a piston cylinder head (gray rectangle).
Define the origin O of the coordinate system at the crankshaft location. Label the nearest distance
between the piston head and the crankshaft location as bottom dead center (BDC). The height of BDC
is L − a. Label the farthest distance between the piston head and the crankshaft location as top dead
center (TDC). The height of TDC is L + a.
4-60
Animation and Model of Automotive Piston
2
The height of the piston relative to the origin is H = a cosθ + L2 − a2sin θ . Define the piston
height as a symbolic function by using the syms function.
syms pistHeight(L,a,theta)
pistHeight(L,a,theta) = a*cos(theta) + sqrt(L^2-a^2*sin(theta)^2);
Assume that the connecting rod length is L = 150 mm and the crank radius is a = 50 mm. Plot the
piston height as a function of the crank angle for one revolution within the interval [0 2*pi].
fplot(pistHeight(150,50,theta),[0 2*pi])
xlabel('Crank angle (rad)')
ylabel('Height (mm)')
4-61
4 Graphics
The piston head is highest when the piston is at TDC and the crank angle is 0 or 2*pi. The piston
head is lowest when the piston is at BDC and the crank angle is pi.
You can also plot the piston height for various values of a and θ. Create a surface plot of the piston
height by using the fsurf function. Show the piston height within the interval 30 mm < a < 60 mm
and 0 < θ < 2π.
fsurf(pistHeight(150,a,theta),[30 60 0 2*pi])
xlabel('Crank radius (mm)')
ylabel('Crank angle (rad)')
zlabel('Height (mm)')
4-62
Animation and Model of Automotive Piston
The length of the combustion chamber is equal to the difference between the TDC location and the
B 2
piston height. The volume of the piston cylinder can be expressed as V = π 2
L+a−H .
Define the piston volume as a symbolic function and substitute the expression for H with
pistHeight.
syms pistVol(L,a,theta,B)
pistVol(L,a,theta,B) = pi*(B/2)^2*(L+a-pistHeight)
pistVol(L, a, theta, B) =
2
π B2 L + a − a cos θ − L2 − a2 sin θ
4
Plot the piston volume as a function of the crank angle for one revolution within the interval [0
2*pi].
4-63
4 Graphics
fplot(pistVol(150,50,theta,86),[0 2*pi])
xlabel('Crank angle (rad)')
ylabel('Volume (mm^3)')
The piston volume is smallest when the piston is at TDC and the crank angle is 0 or 2*pi. The piston
volume is largest when the piston is at BDC and the crank angle is pi.
Assume the crank rotates at 30 rpm for the first 3 seconds, then steadily increases from 30 to 80 rpm
for the next 4 seconds, and then remains at 80 rpm.
Define the angular speed as a function of time by using the piecewise function. Multiply the angular
speed by 2π/60 to convert the rotational speed from rpm to rad/sec.
syms t0 t
rpmConv = 2*pi/60;
angVel(t0) = piecewise(t0<=3, 30, t0>3 & t0<=7, 30 + 50/4*(t0-3), t0>7, 80)*rpmConv
angVel(t0) =
π if t0 ≤ 3
25 t0 15
π 2
− 2
if t0 ∈ 3, 7
30
8π
if 7 < t0
3
4-64
Animation and Model of Automotive Piston
Calculate the crank angle by integrating the angular speed using the int function. Assume an initial
crank angle of θ = 0. Compute the integral of the angular speed from 0 to t.
angPos(t) = int(angVel,t0,0,t);
Find the piston height as a function of time by substituting the expression angPos for the crank
angle.
H(t) = pistHeight(150,50,angPos)
H(t) =
200 if t = 0
100 if t = 3
20625 + 25 if t = 7
2
50 cos σ1 + 22500 − 2500 sin σ1 if 7 < t
2
22500 − 2500 sin σ2 − 50 cos σ2 if t ∈ 3, 7
2
50 cos π t + 22500 − 2500 sin π t if t < 0 ∨ t ∈ 0, 3
where
31 π 8 π t − 7
σ1 = +
3 3
π 5t+9 t−3
σ2 =
24
Plot the piston height as a function of time. Notice that the oscillation of the piston height becomes
faster between 3 and 7 seconds.
fplot(H(t),[0 10])
xlabel('Time (sec)')
ylabel('Height (mm)')
4-65
4 Graphics
First, create a new figure. Plot the cylinder walls that have fixed locations. Set the x-axis and y-axis to
be equal length.
figure;
plot([-43 -43],[50 210],'k','LineWidth',3)
hold on;
plot([43 43],[50 210],'k','LineWidth',3)
plot([-43 43],[210 210],'k','LineWidth',3)
axis equal;
Next, create a stop-motion animation object of the piston head by using the fanimator function. By
default, fanimator creates an animation object by generating 10 frames per unit time within the
range of t from 0 to 10. Model the piston head as a rectangle with a thickness of 10 mm and variable
height H(t). Plot the piston head by using the rectangle function.
fanimator(@rectangle,'Position',[-43 H(t) 86 10],'FaceColor',[0.8 0.8 0.8])
Add the animation objects of the connecting rod and the piston crank. Add a piece of text to count the
elapsed time.
fanimator(@(t) plot([0 50*sin(angPos(t))],[H(t) 50*cos(angPos(t))],'r-','LineWidth',3))
fanimator(@(t) plot([0 50*sin(angPos(t))],[0 50*cos(angPos(t))],'g-','LineWidth',3))
fanimator(@(t) text(-25,225,"Timer: "+num2str(t,2)));
hold off;
4-66
Animation and Model of Automotive Piston
Use the command playAnimation to play the animation of the moving piston.
4-67
4 Graphics
4-68
5
Code Generation
For example:
syms x y
z = 30*x^4/(x*y^2 + 10) - x^3*(y^2 + 1)^2;
fortran(z)
ans =
' t0 = (x**4*3.0D+1)/(x*y**2+1.0D+1)-x**3*(y**2+1.0D0)**2'
ccode(z)
ans =
' t0 = ((x*x*x*x)*3.0E+1)/(x*(y*y)+1.0E+1)-(x*x*x)*pow(y*y+1.0,2.0);'
generates a file named fortrantest in the current folder. fortrantest consists of the following:
t2 = y**2
t0 = (x**4*3.0D+1)/(t2*x+1.0D+1)-x**3*(t2+1.0D0)**2
ccode(z,'file','ccodetest')
t2 = y*y;
t0 = ((x*x*x*x)*3.0E+1)/(t2*x+1.0E+1)-(x*x*x)*pow(t2+1.0,2.0);
ccode and fortran generate many intermediate variables. This is called optimized code. MATLAB
generates intermediate variables as a lowercase letter t followed by an automatically generated
number, such as t2. Intermediate variables can make the resulting code more efficient by reusing
intermediate expressions (such as t2 in fortrantest and ccodetest). They can also make the
code easier to read by keeping expressions short.
5-2
Generate MATLAB Functions from Symbolic Expressions
syms x y
r = sqrt(x^2 + y^2);
ht = matlabFunction(tanh(r))
ht =
function_handle with value:
@(x,y)tanh(sqrt(x.^2+y.^2))
ht(.5,.5)
ans =
0.6089
You can pass the usual MATLAB double-precision numbers or matrices to the function handle. For
example:
cc = [.5,3];
dd = [-.5,.5];
ht(cc, dd)
ans =
0.6089 0.9954
Tip Some symbolic expressions cannot be represented using MATLAB functions. matlabFunction
cannot convert these symbolic expressions, but issues a warning. Since these expressions might
result in undefined function calls, always check conversion results and verify the results by executing
the resulting function.
ht = @(x,y)tanh((x.^2 + y.^2).^(1./2))
You can specify the order of input variables in the function handle using the vars option. You specify
the order by passing a cell array of character vectors or symbolic arrays, or a vector of symbolic
variables. For example:
5-3
5 Code Generation
syms x y z
r = sqrt(x^2 + 3*y^2 + 5*z^2);
ht1 = matlabFunction(tanh(r), 'vars', [y x z])
ht1 =
function_handle with value:
@(y,x,z)tanh(sqrt(x.^2+y.^2.*3.0+z.^2.*5.0))
ht2 =
function_handle with value:
@(x,y,z)tanh(sqrt(x.^2+y.^2.*3.0+z.^2.*5.0))
ht3 =
function_handle with value:
@(x,in2)tanh(sqrt(x.^2+in2(:,1).^2.*3.0+in2(:,2).^2.*5.0))
Generate a File
You can generate a file from a symbolic expression, in addition to a function handle. Specify the file
name using the file option. Pass a character vector containing the file name or the path to the file.
If you do not specify the path to the file, matlabFunction creates this file in the current folder.
This example generates a file that calculates the value of the symbolic matrix F for double-precision
inputs t, x, and y:
syms x y t
z = (x^3 - tan(y))/(x^3 + tan(y));
w = z/(1 + t^2);
F = [w,(1 + t^2)*x/y; (1 + t^2)*x/y,3*z - 1];
matlabFunction(F,'file','testMatrix.m')
function F = testMatrix(t,x,y)
%TESTMATRIX
% F = TESTMATRIX(T,X,Y)
t2 = x.^2;
t3 = tan(y);
t4 = t2.*x;
t5 = t.^2;
t6 = t5 + 1;
t7 = 1./y;
t8 = t6.*t7.*x;
t9 = t3 + t4;
t10 = 1./t9;
F = [-(t10.*(t3 - t4))./t6,t8; t8,- t10.*(3.*t3 - 3.*t2.*x) - 1];
matlabFunction generates many intermediate variables. This is called optimized code. MATLAB
generates intermediate variables as a lowercase letter t followed by an automatically generated
number, for example t32. Intermediate variables can make the resulting code more efficient by
reusing intermediate expressions (such as t4, t6, t8, t9, and t10 in the calculation of F). Using
intermediate variables can make the code easier to read by keeping expressions short.
5-4
Generate MATLAB Functions from Symbolic Expressions
If you don't want the default alphabetical order of input variables, use the vars option to control the
order. Continuing the example,
matlabFunction(F,'file','testMatrix.m','vars',[x y t])
generates a file equivalent to the previous one, with a different order of inputs:
function F = testMatrix(x,y,t)
...
syms x y t
z = (x^3 - tan(y))/(x^3 + tan(y));
w = z/(1 + t^2);
F = [w, (1 + t^2)*x/y; (1 + t^2)*x/y,3*z - 1];
matlabFunction(F,'file','testMatrix.m','vars',[x y t])
function F = testMatrix(x,y,t)
...
syms x y t
z = (x^3 - tan(y))/(x^3 + tan(y));
w = z/(1 + t^2);
F = [w,(1 + t^2)*x/y; (1 + t^2)*x/y,3*z - 1];
matlabFunction(w + z + F,'file','testMatrix.m',...
'vars',[x y t])
the default names of output variables consist of the word out followed by the number, for example:
syms x y z
r = x^2 + y^2 + z^2;
q = x^2 - y^2 - z^2;
f = matlabFunction(r, q, 'file', 'new_function',...
'outputs', {'name1','name2'})
5-5
5 Code Generation
new_system('my_system')
open_system('my_system')
Create a symbolic expression and pass it to the matlabFunctionBlock command. Also specify the
block name:
syms x y
r = sqrt(x^2 + y^2);
matlabFunctionBlock('my_system/my_block', r)
If you use the name of an existing block, the matlabFunctionBlock command replaces the
definition of an existing block with the converted symbolic expression.
You can open and edit the generated block. To open a block, double-click it.
function r = my_block(x,y)
%#codegen
syms x y
mu = sym('mu');
dydt = -x - mu*y*(x^2 - 1);
matlabFunctionBlock('my_system/my_block', dydt,'vars', [y mu x])
5-6
Generate MATLAB Function Blocks from Symbolic Expressions
syms x y
mu = sym('mu');
dydt = -x - mu*y*(x^2 - 1);
matlabFunctionBlock('my_system/my_block', dydt,'outputs',{'name1'})
5-7
5 Code Generation
You can extend the Simscape modeling environment by creating custom components. When you
define a component, use the equation section of the component file to establish the mathematical
relationships among a component's variables, parameters, inputs, outputs, time, and the time
derivatives of each of these entities. The Symbolic Math Toolbox and Simscape software let you
perform symbolic computations and use the results of these computations in the equation section.
The simscapeEquation function translates the results of symbolic computations to Simscape
language equations.
Then, use the simscapeEquation function to rewrite the solution in the Simscape language:
simscapeEquation(s)
The variable time replaces all instances of the variable t except for derivatives with respect to t. To
use the generated equation, copy the equation and paste it to the equation section of the Simscape
component file. Do not copy the automatically generated variable ans and the equal sign that follows
it.
simscapeEquation converts any derivative with respect to the variable t to the Simscape notation,
X.der, where X is the time-dependent variable. For example, convert the following differential
equation to a Simscape equation. Also, here you explicitly specify the left and the right sides of the
equation by using the syntax simscapeEquation(LHS, RHS):
syms a x(t)
simscapeEquation(diff(x), -a^2*x)
ans =
'x.der == -a^2*x;'
5-8
Generate Simscape Equations from Symbolic Expressions
simscapeEquation also translates piecewise expressions to the Simscape language. For example,
the result of the following Fourier transform is a piecewise function:
syms v u x
assume(x, 'real')
f = exp(-x^2*abs(v))*sin(v)/v;
s = fourier(f, v, u)
s =
piecewise(x ~= 0, atan((u + 1)/x^2) - atan((u - 1)/x^2))
From this symbolic piecewise equation, simscapeEquation generates valid code for the equation
section of a Simscape component file:
simscapeEquation(s)
ans =
'if (x ~= 0.0)
s == -atan(1.0/x^2*(u-1.0))+atan(1.0/x^2*(u+1.0));
else
s == NaN;
end'
syms x
Limitations
The equation section of a Simscape component file supports a limited number of functions. For details
and the list of supported functions, see Simscape equations (Simscape). If a symbolic expression
contains functions that are not supported by Simscape, then simscapeEquation cannot represent
the symbolic expression as a Simscape equation and issues a warning instead. Always verify the
conversion result. Expressions with infinities are prone to invalid conversion.
5-9
5 Code Generation
This example shows how to generate a MATLAB® function from a symbolic expression and use the
function to create a standalone application with MATLAB Compiler™.
This example follows the steps described in “Create Standalone Application from MATLAB Function”
(MATLAB Compiler) and updates the steps to generate a MATLAB function from a symbolic
expression.
2
d y 1 dy
+ + 2y = 0.
dt2 2 dt
To solve the differential equation, convert it to first-order differential equations by using the
odeToVectorField function.
V = odeToVectorField(ode);
Next, convert the symbolic expression V to a MATLAB function file by using matlabFunction. The
converted function in the file myODE.m can be used without Symbolic Math Toolbox™. The converted
function is deployable with MATLAB Compiler.
matlabFunction(V,'vars',{'t','Y'},'File','myODE');
Write a MATLAB script named plotODESols.m that solves the differential equation using ode45 and
plots the solution. Save it in the same directory as myODE.m function.
type plotODESols.m
5-10
Deploy Generated MATLAB Functions from Symbolic Expressions with MATLAB Compiler
You can use this script to create and deploy standalone application using Application Compiler app.
On the MATLAB Apps tab, in the Apps section, click the arrow to open the apps gallery. Under
Application Deployment, click Application Compiler. The MATLAB Compiler project window
opens.
Alternately, you can open the Application Compiler app by entering applicationCompiler at the
MATLAB prompt.
In the MATLAB Compiler project window, specify the main file of the MATLAB application that you
want to deploy.
1
In the Main File section of the toolstrip, click .
2 In the Add Files dialog box, browse to the file location that contains your generated script.
Select plotODESols.m and click Open. The Application Compiler app adds the plotODESols
function to the list of main files.
Decide whether to include the MATLAB Runtime installer in the generated application by selecting
one of the two options in the Packaging Options section:
• Runtime downloaded from web — Generates an installer that downloads the MATLAB Runtime
and installs it along with the deployed MATLAB application
• Runtime included in package — Generates an installer that includes the MATLAB Runtime
installer
Customize the packaged application and its appearance by entering the following options:
5-11
5 Code Generation
• Application information — Editable information about the deployed application. You can also
customize the appearance of the standalone application by changing the application icon and
splash screen. The generated installer uses this information to populate the installed application
metadata.
• Additional installer options — Options for editing the default installation path for the generated
installer and selecting a custom logo.
• Files required for your application to run — Additional files required by the generated
application to run. The software includes these files in the generated application installer. When
you add plotODESols.m to the main file section of the toolstrip, the compiler automatically adds
myODE.m as the file required for your application to run.
• Files installed for your end user — Files that are installed with your application. These files
include the automatically generated readme.txt file and the generated executable for the target
platform.
• Additional runtime settings — Platform-specific options for controlling the generated
executable.
For details about these options, see “Customize an Application” (MATLAB Compiler).
To generate the packaged application, click Package in the Package section on the toolstrip. In the
Save Project dialog box, specify the location in which to save the project.
5-12
Deploy Generated MATLAB Functions from Symbolic Expressions with MATLAB Compiler
In the Package dialog box, verify that Open output folder when process completes is selected.
When the deployment process is complete, the output should contain the list of things below.
• for_redistribution — Folder containing the file that installs the application and the MATLAB
Runtime.
• for_testing — Folder containing all the artifacts created by mcc (such as binary, header, and
source files for a specific target). Use these files to test the installation.
• for_redistribution_files_only — Folder containing the files required for redistributing the
application. Distribute these files to users who have MATLAB or MATLAB Runtime installed on
their machines.
• PackagingLog.txt — Log file generated by MATLAB Compiler.
If you want to connect to the Internet using a proxy server, click Connection Settings. Enter the
proxy server settings in the provided dialog box. Click OK.
5-13
5 Code Generation
Ensure that you have administrator privileges on the other machines to run and deploy the
standalone application.
Choose one target machine to test the MATLAB generated standalone application.
Copy the for_redistribution_files_only folder to a file location on all target machines where
MATLAB or MATLAB Runtime is installed.
5-14
Deploy Generated MATLAB Functions from Symbolic Expressions with MATLAB Compiler
Run the MATLAB generated standalone application on all target machines by using the executable in
the for_redistribution_files_only folder.
5-15
5 Code Generation
This example shows how to use the MATLAB® Coder™ app to generate a static C library from
symbolic expressions. First, you work with symbolic expressions in Symbolic Math Toolbox™, and
convert the symbolic expressions into a deployable MATLAB function using matlabFunction. Next,
you generate C code from the MATLAB function. The generated C code accepts inputs that have a
fixed, preassigned size, but you can also specify variable-size inputs during code generation.
This example follows the steps described in “Generate C Code by Using the MATLAB Coder App”
(MATLAB Coder), but updates the steps to generate a MATLAB function from a symbolic expression.
Alternatively, you can generate C code from a MATLAB function at the MATLAB command line by
using the codegen (MATLAB Coder) command. For a tutorial on this workflow, see “Generate C Code
at the Command Line” (MATLAB Coder).
Note that the MATLAB Coder app is not supported in MATLAB Online™. To generate C/C++ code in
MATLAB Online, use the codegen (MATLAB Coder) command.
2 δ
q−1 − Ω
2
H= ,
δ 2
Ω + q+1
2
Create the symbolic variables q, Omega, and delta to represent the parameters of the Hamiltonian.
Create a symbolic matrix for the Hamiltonian.
H =
2 δ
q−1 − Ω
2
δ 2
Ω + q+1
2
5-16
Generate C Code from Symbolic Expressions Using the MATLAB Coder App
E = eig(H)
E =
2 2
4 Ω + δ + 8 δ q + 16 q2
q2 − +1
2
2 2
4 Ω + δ + 8 δ q + 16 q2
q2 + +1
2
Next, convert the two eigenvalues E(1) and E(2) to a MATLAB function file by using
matlabFunction. Write the resulting function, which returns two elements E1 and E2, to the file
myEigenvalues.m. Specify the order of input arguments as [q Omega delta].
matlabFunction(E(1),E(2),'File','myEigenvalues', ...
'Vars',[q Omega delta],'Outputs',{'E1','E2'});
The converted function in the file myEigenvalues.m can be used without Symbolic Math Toolbox.
The MATLAB file myEigenvalues.m contains the function myEigenvalues that implements the
core algorithm in this example. The function takes q, Omega, and delta as inputs, all of which must
be either the same size or a scalar. It then calculates the two eigenvalues as a function of these
inputs.
type myEigenvalues
% This function was generated by the Symbolic Math Toolbox version 23.2.
% 19-Aug-2023 18:58:33
t2 = Omega.^2;
t3 = delta.^2;
t4 = q.^2;
t6 = delta.*q.*8.0;
t5 = t2.*4.0;
t7 = t4.*1.6e+1;
t8 = t3+t5+t6+t7;
t9 = sqrt(t8);
t10 = t9./2.0;
E1 = t4-t10+1.0;
if nargout > 1
E2 = t4+t10+1.0;
end
end
To calculate the eigenvalues for a set of inputs, create and run the test script myTest.m in MATLAB.
The test script specifies the inputs with the following sizes:
• qGrid is a 128-by-256 matrix that represents points in the two-dimensional (q,Ω) space.
• OmegaGrid is a 128-by-256 matrix that represents points in the two-dimensional (q,Ω) space.
• delta is a scalar.
The script then calls the function myEigenvalues.m to compute the eigenvalues. The output
displays a plot of the eigenvalues for these input values. Below is the content of the script myTest.m.
5-17
5 Code Generation
q = linspace(-2,2,256);
Omega = linspace(0,2,128);
delta = 1;
[qGrid,OmegaGrid] = meshgrid(q,Omega);
[E1,E2] = myEigenvalues(qGrid,OmegaGrid,delta);
surf(q,Omega,E1)
hold on;
surf(q,Omega,E2)
shading interp
To make your MATLAB code suitable for code generation, use the Code Analyzer and the Code
Generation Readiness Tool. The Code Analyzer in the MATLAB Editor continuously checks your code
as you enter it. It reports issues and recommends modifications to improve performance and
maintainability. The Code Generation Readiness Tool screens the MATLAB code for features and
functions that are not supported for code generation.
• Open myEigenvalues.m in the MATLAB Editor. After the function declaration, add the
%#codegen directive:
5-18
Generate C Code from Symbolic Expressions Using the MATLAB Coder App
• The Code Analyzer message indicator in the top right corner of the MATLAB Editor is green. The
analyzer did not detect errors, warnings, or opportunities for improvement in the code. For more
information about using the Code Analyzer, see “Check Code for Errors and Warnings Using the
Code Analyzer”.
• Save the file. You are now ready to compile your code by using the MATLAB Coder app. Here,
compilation refers to the generation of C/C++ code from your MATLAB code.
• On the MATLAB toolstrip Apps tab, under Code Generation, click the MATLAB Coder app icon.
The app opens the Select Source Files page.
• In the Select Source Files page, enter or select the name of the entry-point function
myEigenvalues. An entry-point function is a top-level MATLAB function from which you generate
code. The app creates a project with the default name myEigenvalues.prj in the current folder.
5-19
5 Code Generation
• Click Next to go to the Define Input Types step. The app runs the Code Analyzer, which you
already ran in the previous step, and the Code Generation Readiness Tool on the entry-point
function. If the app identifies issues, it opens the Review Code Generation Readiness page
where you can review and fix issues. In this example, because the app does not detect issues, it
opens the Define Input Types page. For more information, see “Code Generation Readiness Tool”
(MATLAB Coder).
Note that the Code Analyzer and the Code Generation Readiness Tool might not detect all code
generation issues. After eliminating the errors or warnings that these two tools detect, generate code
with MATLAB Coder to determine if your MATLAB code has other compliance issues.
Certain MATLAB built-in functions and toolbox functions, classes, and System objects that are
supported for C/C++ code generation have specific code generation limitations. These limitations and
related usage notes are listed in the Extended Capabilities sections of their corresponding
reference pages. For more information, see “Functions and Objects Supported for C/C++ Code
Generation” (MATLAB Coder).
5-20
Generate C Code from Symbolic Expressions Using the MATLAB Coder App
Because C uses static typing, the code generator must determine the class, size, and complexity of all
variables in the MATLAB files at code generation time, also known as compile time. Therefore, you
must specify the properties of all entry-point function inputs. To specify input properties, you can:
• Instruct the app to automatically determine input properties by providing a script that calls the
entry-point functions with sample inputs.
• Specify properties directly.
In this example, to define the properties of the inputs q, delta, and Omega, specify the test file
myTest.m for the code generator to use to define types automatically:
5-21
5 Code Generation
The Check for Run-Time Issues step generates a MEX function from your entry-point functions,
runs the MEX function, and reports issues. A MEX function is generated code that can be called from
inside MATLAB. Performing this step is a best practice because you can detect and fix run-time errors
that are harder to diagnose in the generated C code. By default, the MEX function includes memory
integrity checks. These checks perform array bounds and dimension checking. The checks detect
violations of memory integrity in code generated for MATLAB functions. For more information, see
“Control Run-Time Checks” (MATLAB Coder).
To convert MATLAB code to efficient C/C++ source code, the code generator introduces
optimizations that, in certain situations, cause the generated code to behave differently than the
original source code. See “Differences Between Generated Code and MATLAB Code” (MATLAB
Coder).
• To open the Check for Run-Time Issues dialog box (if the dialog box does not automatically
appear), click the Check for Issues arrow .
• In the Check for Run-Time Issues dialog box, specify a test file or enter code that calls the
entry-point function with example inputs. For this example, use the test file myTest that you used
to define the input types.
• Click Check for Issues. The app generates a MEX function that can be run inside MATLAB. This
step runs the test script myTest replacing calls to myEigenvalues with calls to the generated
MEX function, that is [E1,E2] = myEigenvalues_mex(qGrid,OmegaGrid,delta). The
generated MEX file myEigenvalues_mex is located in the folder work\codegen\lib
\myEigenvalues (on Microsoft® Windows® platforms) or work/codegen/lib/
myEigenvalues (on Linux® or Mac platforms), where work is the location of myEigenvalues.m
and myTest.m. If the app detects issues during the MEX function generation or execution, it
provides warning and error messages. Click these messages to navigate to the problematic code
and fix the issue. In this example, the app does not detect issues.
5-22
Generate C Code from Symbolic Expressions Using the MATLAB Coder App
• By default, the app collects line execution counts. These counts help you see how well the test file
myTest.m exercised the myEigenvalues function. To view line execution counts, click View
MATLAB line execution counts. The app editor displays a color-coded bar to the left of the
code. To extend the color highlighting over the code and to see line execution counts, place your
cursor over the bar. A particular shade of green indicates that the code only executes one call to
compute the eigenvalues.
5-23
5 Code Generation
Generate C Code
• To open the Generate dialog box (if the dialog box does not automatically appear), click the
Generate arrow .
• In the Generate dialog box, set Build type to Static Library(.lib) and Language to C. Use
the default values for the other project build configuration settings. Instead of generating a C
static library, you can choose to generate a MEX function or other C/C++ build types. Different
project settings are available for the MEX and C/C++ build types. When you switch between MEX
and C/C++ code generation, verify the settings that you choose.
5-24
Generate C Code from Symbolic Expressions Using the MATLAB Coder App
• Click Generate. MATLAB Coder generates a standalone C static library, myEigenvalues, in the
folder work\codegen\lib\myEigenvalues. The folder work is the location of
myEigenvalues.m and myTest.m. The MATLAB Coder app indicates when code generation has
succeeded. It displays the source MATLAB files and generated output files on the left side of the
page. On the Variables tab, it displays information about the MATLAB source variables. On the
Target Build Log tab, it displays the build log, including C/C++ compiler warnings and errors.
By default, the code window displays the C source code file, myEigenvalues.c. To view a
different file, click the desired file name in the Source Code or Output Files pane.
5-25
5 Code Generation
• Click View Report to view the report in the Report Viewer. If the code generator detects errors or
warnings during code generation, the report describes the issues and provides links to the
problematic MATLAB code. For more information, see “Code Generation Reports” (MATLAB
Coder).
• Click Next to open the Finish Workflow page.
The Finish Workflow page indicates that code generation has succeeded. It provides a project
summary and links to generated output.
5-26
Generate C Code from Symbolic Expressions Using the MATLAB Coder App
To compare your generated C code to the original MATLAB code, open the C file, myEigenvalues.c,
and the myEigenvalues.m file in the MATLAB Editor.
• const double q[32768] and const double Omega[32768] corresponds to the input q and
Omega in your MATLAB code. The size of q is 32768, which corresponds to the total size (128 x
256) of the example input that you used when you generated C/C++ code from your MATLAB
code. The same applies to the input Omega. In this case, the generated code uses one-dimensional
arrays to represent two-dimensional arrays in the MATLAB code.
• The code generator preserves your function name and comments. When possible, the code
generator preserves your variable names. Note that if a variable in your MATLAB code is set to a
constant value, it does not appear as a variable in the generated C code. Instead, the generated C
code contains the value of the variable as a literal.
5-27
5 Code Generation
The C function that you generated for myEigenvalues.m can accept only inputs that have the same
size as the sample inputs that you specified during code generation. However, the input arrays to the
corresponding MATLAB function can be of any size. In this part of the example, you generate C code
from myEigenvalues.m that accepts variable-size inputs.
Suppose that you want the dimensions of q, Omega, and delta in the generated C code to have these
properties:
• The first dimension of both q and delta can vary in size up to 100.
• The second dimension of q and delta can vary in size up to 400.
• Omega is a scalar of size 1-by-1.
To specify these input properties using MATLAB Coder, follow these steps:
• In the Define Input Types step, specify the test file myTest.m and click Autodefine Input Types
as before. The test file calls the entry-point function, myEigenvalues.m, with the expected input
types. The app determines that the input q is double(128 x 256), the input Omega is
double(128 x 256), and the input delta is double(1 x 1). These types specify fixed-size
inputs.
• Click the input type specifications to edit them. You can specify variable size, up to a specified
limit, by using the : prefix. For example, :100 specifies that the corresponding dimension can
vary in size up to 100. Change the type for q to double(:100 x :400), for Omega to double(1
x 1), and for delta to double(:100 x :400).
5-28
Generate C Code from Symbolic Expressions Using the MATLAB Coder App
You can now generate code by following the same steps as before. The function signature for the
generated C code in myEigenvalues.c now reads:
The arguments in the generated code correspond to these arguments in the original MATLAB
function:
The C code now consists of a data structure called an emxArray_real_T to represent an array
whose size is unknown and unbounded at compile time. For more details, see “Use C Arrays in the
Generated Function Interfaces” (MATLAB Coder).
5-29
5 Code Generation
This example shows how to derive a continuous-time nonlinear model of a quadrotor using Symbolic
Math Toolbox™. Specifically, this example discusses the getQuadrotorDynamicsAndJacobian
script, which generates both the quadrotor state function and its Jacobian function. These functions
are used in the “Control of Quadrotor Using Nonlinear Model Predictive Control” (Model Predictive
Control Toolbox) example.
A quadrotor, also known as a quadcopter, is a helicopter with four rotors. From the center of mass of
the quadrotor, rotors are placed in a square formation at equal distances. The quadrotor motion is
controlled by adjusting the angular velocities of the four rotors, which are spun by electric motors.
The mathematical model for the quadrotor dynamics can be derived from both the Newton–Euler and
the Euler–Lagrange equations [1].
The quadrotor has six degrees of freedom (three linear coordinates and three angular coordinates)
with four control inputs as shown in this figure.
T
x, y, z, ϕ , θ, ψ, ẋ, ẏ, ż, ϕ̇, θ̇, ψ̇ ,
where:
• ξ = x, y, z T
represents the linear positions.
• η = ϕ , θ, ψ T
represents the roll, pitch, and yaw angles, respectively.
5-30
Derive Quadrotor Dynamics for Nonlinear Model Predictive Control
• T
ẋ, ẏ, ż, ϕ̇, θ̇, ψ̇ represents the linear and angular velocities or the time-derivative of the linear and
angular positions.
• u1, u2, u3, u4 = ω12, ω22, ω32, ω42 represents the squared angular velocities of the four rotors.
• Ixx, Iyy, Izz represents the diagonal elements of the rotational inertia matrix in the body frame.
• k, l, m, b, g represents the lift constant, rotor distance from center of mass, quadrotor mass, drag
constant, and gravity.
The first four parameters u1, u2, u3, u4 are control inputs or manipulated variables that control the
quadrotor trajectory. The rest of the parameters are fixed with given values.
Define the matrices to transform between the inertial frame and the body frame. These
transformation matrices are needed to describe the quadrotor motion in both frames. The 12 states of
the quadrotor are defined in the inertial frame and the rotational inertia matrix is defined in the body
frame.
Create symbolic functions to represent the time-dependent angles. This explicit time dependence is
needed to evaluate the time derivatives in the mathematical derivation following [1]. Define the
matrix W η to transform the angular velocities from the inertial frame to the body frame. Define the
rotation matrix R to transform the linear forces from the body frame to the inertial frame by using
the rotationMatrixEulerZYX function defined in the Local Functions section. Create symbolic
matrices to represent these transformation matrices.
% Create symbolic functions for time-dependent angles
% phi: roll angle
% theta: pitch angle
% psi: yaw angle
syms phi(t) theta(t) psi(t)
Find the Jacobian matrix J = W ηT IW η that is used to express the rotational energy in the inertial
frame.
% Create symbolic variables for diagonal elements of inertia matrix
syms Ixx Iyy Izz
d 1 ∂ T
Next, find the Coriolis matrix C η, η̇ = dt
J− 2 ∂η
η̇ J that contains the gyroscopic and centripetal
terms in the angular Euler–Lagrange equations. Use the symbolic diff and jacobian functions to
5-31
5 Code Generation
perform the differential operations. To simplify the notation for the Coriolis matrix after
differentiations, substitute the explicit time-dependent terms in C η, η̇ with symbolic variables (that
represent some values at a specific time). This simplified notation makes it easier to compare the
result here with the derivation in [1].
% Coriolis matrix
dJ_dt = diff(J);
h_dot_J = [diff(phi,t), diff(theta,t), diff(psi,t)]*J;
grad_temp_h = transpose(jacobian(h_dot_J,[phi theta psi]));
C = dJ_dt - 1/2*grad_temp_h;
C = subsStateVars(C,t);
The Coriolis matrix C η, η̇ is easily derived using the symbolic workflow in the previous section.
However, the definition of C η, η̇ here is different than in [1], which uses the Christoffel symbols to
derive the Coriolis matrix. There can be multiple ways of defining C η, η̇ because it is nonunique.
But, the term C η, η̇ η̇ that is used in the Euler–Lagrange equations must be unique. This section
proves that the symbolic definition of C η, η̇ is consistent with the definition in [1] by showing that
the term C η, η̇ η̇ is mathematically equal in both definitions.
Evaluate the term C η, η̇ η̇ using the symbolic definition of C η, η̇ derived in the previous section.
% Evaluate C times etadot using symbolic definition
phidot = subsStateVars(diff(phi,t),t);
thetadot = subsStateVars(diff(theta,t),t);
psidot = subsStateVars(diff(psi,t),t);
Csym_etadot = C*[phidot; thetadot; psidot];
Show that both definitions give the same result for the term C η, η̇ η̇ .
tf_Cdefinition = isAlways(Cpaper_etadot == Csym_etadot)
5-32
Derive Quadrotor Dynamics for Nonlinear Model Predictive Control
1
1
1
Following [1], find the torques τB in the roll, pitch, and yaw angular directions:
• The roll movement is set by decreasing the 2nd rotor velocity and increasing the 4th rotor velocity.
• The pitch movement is set by decreasing the 1st rotor velocity and increasing the 3rd rotor
velocity.
• The yaw movement is set by increasing the velocities of two opposite rotors and decreasing the
velocities of the other two.
Find the total thrust of the rotors T in the direction of the body z-axis.
% Define fixed parameters and control input
% k: lift constant
% l: distance between rotor and center of mass
% m: quadrotor mass
% b: drag constant
% g: gravity
% ui: squared angular velocity of rotor i as control input
syms k l m b g u1 u2 u3 u4
% Total thrust
T = k*(u1+u2+u3+u4);
Next, create symbolic functions to represent the time-dependent positions. Define the 12 states
ξ; η; ξ̇; η̇ for the linear positions, angles, and their time derivatives. Once the states are defined,
substitute the explicit time-dependent terms to simplify the notation.
% Create symbolic functions for time-dependent positions
syms x(t) y(t) z(t)
Create the 12 equations of motion that describe the time-derivative of the 12 states f = ξ̇; η̇ ; ξ̈ ; η̈ .
T T
The differential equations for the linear accelerations are ξ̈ = − 0, 0, g + R 0, 0, T /m. The
differential equations for the angular accelerations are η̈ = J −1 τB − C η, η̇ η̇ . Substitute the
explicit time-dependent terms to simplify the notation.
f = [ % Set time-derivative of the positions and angles
state(7:12);
5-33
5 Code Generation
f = subsStateVars(f,t);
In previous steps, the fixed parameters are defined as symbolic variables to closely follow the
derivation in [1]. Next, replace the fixed parameters with their given values. These values are used to
design a trajectory tracking controller for a specific configuration of the quadrotor. After substituting
the fixed parameters, perform algebraic simplification on the equations of motion by using
simplify.
% Replace fixed parameters with given values here
IxxVal = 1.2;
IyyVal = 1.2;
IzzVal = 2.3;
kVal = 1;
lVal = 0.25;
mVal = 2;
bVal = 0.2;
gVal = 9.81;
Find Jacobians and Generate Files for Nonlinear Model Predictive Control
Finally, find the analytical Jacobians of the nonlinear model functions and generate MATLAB® files
using Symbolic Math Toolbox. This step is important to improve the computational efficiency when
solving the nonlinear model for trajectory tracking using Model Predictive Control Toolbox™. For
more information, see nlmpc (Model Predictive Control Toolbox) and “Specify Prediction Model for
Nonlinear MPC” (Model Predictive Control Toolbox).
Find the Jacobians of the state function with respect to the state variables and control inputs.
% Calculate Jacobians for nonlinear prediction model
A = jacobian(f,state);
control = [u1; u2; u3; u4];
B = jacobian(f,control);
Generate MATLAB files for the state function and the Jacobians of the state function. These files can
be used to design a trajectory tracking controller, as discussed in “Control of Quadrotor Using
Nonlinear Model Predictive Control” (Model Predictive Control Toolbox).
% Create QuadrotorStateFcn.m with current state and control
% vectors as inputs and the state time-derivative as outputs
matlabFunction(f,'File','QuadrotorStateFcn', ...
'Vars',{state,control});
5-34
Derive Quadrotor Dynamics for Nonlinear Model Predictive Control
You can access the code in this script in the file getQuadrotorDynamicsAndJacobian.m.
Local Functions
5-35
5 Code Generation
References
[1] Raffo, Guilherme V., Manuel G. Ortega, and Francisco R. Rubio. "An integral predictive/nonlinear
ℋ ∞ control structure for a quadrotor helicopter". Automatica 46, no. 1 (January 2010): 29–39. https://
doi.org/10.1016/j.automatica.2009.10.018.
[2] Tzorakoleftherakis, Emmanouil, and Todd D. Murphey. "Iterative sequential action control for
stable, model-based control of nonlinear systems." IEEE Transactions on Automatic Control 64, no. 8
(August 2019): 3170–83. https://doi.org/10.1109/TAC.2018.2885477.
[3] Luukkonen, Teppo. "Modelling and control of quadcopter". Independent research project in
applied mathematics, Aalto University, 2011.
See Also
diff | jacobian | matlabFunction
Related Examples
• “Control of Quadrotor Using Nonlinear Model Predictive Control” (Model Predictive Control
Toolbox)
• “Specify Prediction Model for Nonlinear MPC” (Model Predictive Control Toolbox)
5-36
Using Symbolic Mathematics with Optimization Toolbox Solvers
This example shows how to use the Symbolic Math Toolbox™ functions jacobian and
matlabFunction to provide analytical derivatives to optimization solvers. Optimization Toolbox™
solvers are usually more accurate and efficient when you supply gradients and Hessians of the
objective and constraint functions.
Problem-based optimization can calculate and use gradients automatically; see “Automatic
Differentiation in Optimization Toolbox” (Optimization Toolbox). For a problem-based example using
automatic differentiation, see “Constrained Electrostatic Nonlinear Optimization Using Optimization
Variables” (Optimization Toolbox).
There are several considerations in using symbolic calculations with optimization functions:
1 Optimization objective and constraint functions should be defined in terms of a vector, say x.
However, symbolic variables are scalar or complex-valued, not vector-valued. This requires you to
translate between vectors and scalars.
2 Optimization gradients, and sometimes Hessians, are supposed to be calculated within the body
of the objective or constraint functions. This means that a symbolic gradient or Hessian has to be
placed in the appropriate place in the objective or constraint function file or function handle.
3 Calculating gradients and Hessians symbolically can be time-consuming. Therefore you should
perform this calculation only once, and generate code, via matlabFunction, to call during
execution of the solver.
4 Evaluating symbolic expressions with the subs function is time-consuming. It is much more
efficient to use matlabFunction.
5 matlabFunction generates code that depends on the orientation of input vectors. Since
fmincon calls the objective function with column vectors, you must be careful to call
matlabFunction with column vectors of symbolic variables.
2 2
f (x1, x2) = log 1 + 3 x2 − (x13 − x1) + (x1 − 4/3) .
This function is positive, with a unique minimum value of zero attained at x1 = 4/3, x2 =(4/3)^3 - 4/3
= 1.0370...
We write the independent variables as x1 and x2 because in this form they can be used as symbolic
variables. As components of a vector x they would be written x(1) and x(2). The function has a
twisty valley as depicted in the plot below.
syms x1 x2 real
x = [x1;x2]; % column vector of symbolic variables
f = log(1 + 3*(x2 - (x1^3 - x1))^2 + (x1 - 4/3)^2)
f =
4 2 2
log x1 − + 3 −x13 + x1 + x2 + 1
3
5-37
5 Code Generation
fsurf(f,[-2 2],'ShowContours','on')
view(127,38)
gradf =
8
6 3 x12 − 1 −x13 + x1 + x2 − 2 x1 + 3
−
σ1
−6 x13 + 6 x1 + 6 x2
σ1
where
4 2 2
σ1 = x1 − + 3 −x13 + x1 + x2 + 1
3
hessf = jacobian(gradf,x)
hessf =
5-38
Using Symbolic Mathematics with Optimization Toolbox Solvers
2
6 3 x12 − 1 − 36 x1 −x13 + x1 + x2 + 2 σ32
− 2 σ1
σ2 σ2
2
6 −6 x13 + 6 x1 + 6 x2
σ1 −
σ2 σ 2 2
where
−6 x13 + 6 x1 + 6 x2 σ3 18 x12 − 6
σ1 = −
σ22 σ2
4 2 2
σ2 = x1 − + 3 −x13 + x1 + x2 + 1
3
8
σ3 = 6 3 x12 − 1 −x13 + x1 + x2 − 2 x1 +
3
The fminunc solver expects to pass in a vector x, and, with the SpecifyObjectiveGradient
option set to true and HessianFcn option set to 'objective', expects a list of three outputs:
[f(x),gradf(x),hessf(x)].
matlabFunction generates exactly this list of three outputs from a list of three inputs. Furthermore,
using the vars option, matlabFunction accepts vector inputs.
fh = matlabFunction(f,gradf,hessf,'vars',{x});
xfinal = 2×1
1.3333
1.0370
fval = 7.6623e-12
exitflag = 3
5-39
5 Code Generation
constrviolation: []
Compare this with the number of iterations using no gradient or Hessian information. This requires
the 'quasi-newton' algorithm.
options = optimoptions('fminunc','Display','final','Algorithm','quasi-newton');
fh2 = matlabFunction(f,'vars',{x});
% fh2 = objective with no gradient or Hessian
[xfinal,fval,exitflag,output2] = fminunc(fh2,[-1;2],options)
xfinal = 2×1
1.3333
1.0371
fval = 2.1985e-11
exitflag = 1
The number of iterations is lower when using gradients and Hessians, and there are dramatically
fewer function evaluations:
ans =
'There were 14 iterations using gradient and Hessian, but 18 without them.'
ans =
'There were 15 function evaluations using gradient and Hessian, but 81 without them.'
We consider the same objective function and starting point, but now have two nonlinear constraints:
5-40
Using Symbolic Mathematics with Optimization Toolbox Solvers
The constraints keep the optimization away from the global minimum point [1.333,1.037]. Visualize
the two constraints:
[X,Y] = meshgrid(-2:.01:3);
Z = (5*sinh(Y./5) >= X.^4);
% Z=1 where the first constraint is satisfied, Z=0 otherwise
Z = Z+ 2*(5*tanh(X./5) >= Y.^2 - 1);
% Z=2 where the second is satisfied, Z=3 where both are
surf(X,Y,Z,'LineStyle','none');
fig = gcf;
fig.Color = 'w'; % white background
view(0,90)
hold on
plot3(.4396, .0373, 4,'o','MarkerEdgeColor','r','MarkerSize',8);
% best point
xlabel('x')
ylabel('y')
hold off
Here is a plot of the objective function over the feasible region, the region that satisfies both
constraints, pictured above in dark red, along with a small red circle around the optimal point:
W = log(1 + 3*(Y - (X.^3 - X)).^2 + (X - 4/3).^2);
% W = the objective function
5-41
5 Code Generation
W(Z < 3) = nan; % plot only where the constraints are satisfied
surf(X,Y,W,'LineStyle','none');
view(68,20)
hold on
plot3(.4396, .0373, .8152,'o','MarkerEdgeColor','r', ...
'MarkerSize',8); % best point
xlabel('x')
ylabel('y')
zlabel('z')
hold off
The nonlinear constraints must be written in the form c(x) <= 0. We compute all the symbolic
constraints and their derivatives, and place them in a function handle using matlabFunction.
The gradients of the constraints should be column vectors; they must be placed in the objective
function as a matrix, with each column of the matrix representing the gradient of one constraint
function. This is the transpose of the form generated by jacobian, so we take the transpose below.
We place the nonlinear constraints into a function handle. fmincon expects the nonlinear constraints
and gradients to be output in the order [c ceq gradc gradceq]. Since there are no nonlinear
equality constraints, we output [] for ceq and gradceq.
c1 = x1^4 - 5*sinh(x2/5);
c2 = x2^2 - 5*tanh(x1/5) - 1;
c = [c1 c2];
gradc = jacobian(c,x).'; % transpose to put in correct form
constraint = matlabFunction(c,[],gradc,[],'vars',{x});
5-42
Using Symbolic Mathematics with Optimization Toolbox Solvers
The interior-point algorithm requires its Hessian function to be written as a separate function,
instead of being part of the objective function. This is because a nonlinearly constrained function
needs to include those constraints in its Hessian. Its Hessian is the Hessian of the Lagrangian; see
the User's Guide for more information.
The Hessian function takes two input arguments: the position vector x, and the Lagrange multiplier
structure lambda. The parts of the lambda structure that you use for nonlinear constraints are
lambda.ineqnonlin and lambda.eqnonlin. For the current constraint, there are no linear
equalities, so we use the two multipliers lambda.ineqnonlin(1) and lambda.ineqnonlin(2).
We calculated the Hessian of the objective function in the first example. Now we calculate the
Hessians of the two constraint functions, and make function handle versions with matlabFunction.
hessc1 = jacobian(gradc(:,1),x); % constraint = first c column
hessc2 = jacobian(gradc(:,2),x);
hessfh = matlabFunction(hessf,'vars',{x});
hessc1h = matlabFunction(hessc1,'vars',{x});
hessc2h = matlabFunction(hessc2,'vars',{x});
To make the final Hessian, we put the three Hessians together, adding the appropriate Lagrange
multipliers to the constraint functions.
myhess = @(x,lambda)(hessfh(x) + ...
lambda.ineqnonlin(1)*hessc1h(x) + ...
lambda.ineqnonlin(2)*hessc2h(x));
Set the options to use the interior-point algorithm, the gradient, and the Hessian, have the objective
function return both the objective and the gradient, and run the solver:
options = optimoptions('fmincon', ...
'Algorithm','interior-point', ...
'SpecifyObjectiveGradient',true, ...
'SpecifyConstraintGradient',true, ...
'HessianFcn',myhess, ...
'Display','final');
% fh2 = objective without Hessian
fh2 = matlabFunction(f,gradf,'vars',{x});
[xfinal,fval,exitflag,output] = fmincon(fh2,[-1;2],...
[],[],[],[],[],[],constraint,options)
xfinal = 2×1
0.4396
0.0373
fval = 0.8152
exitflag = 1
5-43
5 Code Generation
funcCount: 13
constrviolation: 0
stepsize: 1.9160e-06
algorithm: 'interior-point'
firstorderopt: 1.9217e-08
cgiterations: 0
message: 'Local minimum found that satisfies the constraints....'
bestfeasible: [1x1 struct]
Again, the solver makes many fewer iterations and function evaluations with gradient and Hessian
supplied than when they are not:
options = optimoptions('fmincon','Algorithm','interior-point',...
'Display','final');
% fh3 = objective without gradient or Hessian
fh3 = matlabFunction(f,'vars',{x});
% constraint without gradient:
constraint = matlabFunction(c,[],'vars',{x});
[xfinal,fval,exitflag,output2] = fmincon(fh3,[-1;2],...
[],[],[],[],[],[],constraint,options)
xfinal = 2×1
0.4396
0.0373
fval = 0.8152
exitflag = 1
ans =
'There were 10 iterations using gradient and Hessian, but 17 without them.'
5-44
Using Symbolic Mathematics with Optimization Toolbox Solvers
ans =
'There were 13 function evaluations using gradient and Hessian, but 54 without them.'
The symbolic variables used in this example were assumed to be real. To clear this assumption from
the symbolic engine workspace, it is not sufficient to delete the variables. You must clear the
assumptions of variables using the syntax
assume([x1,x2],'clear')
All assumptions are cleared when the output of the following command is empty
assumptions([x1,x2])
ans =
See Also
Functions
jacobian | matlabFunction | fsurf
5-45
5 Code Generation
This example demonstrates that the Symbolic Math Toolbox™ helps minimize errors when solving a
nonlinear system of equations.
The goal is to find the minimum of the Rosenbrock function, or the so-called "banana" function.
n/2
2 2
f (x) = ∑ 100(x2i − x2
2i − 1) + (1 − x2i − 1)
i=1
syms x y
a=1; b=100;
f(x,y)=(a-x)^2+b*(y-x^2)^2
2 2
f(x, y) = x − 1 + 100 y − x2
fsurf(f,[-2 2 -1 3])
view([-45 50])
colormap jet
colorbar
5-46
Improving Accuracy and Performance in Optimization
Motivation
The “Solve Nonlinear System Without and Including Jacobian” (Optimization Toolbox) example in
Optimization Toolbox™ solves the same problem by using the fsolve (Optimization Toolbox)
function. The workflow shown in that example has two potential sources of errors. You would need to
1 Translate the equations for the Rosenbrock function and Jacobian from the math form in the text
to numeric code.
2 Explicitly calculate the Jacobian. For complicated equations, this task is prone to errors.
This example shows that using symbolic math to describe the problem statement and subsequent
steps minimizes or even eliminates such errors.
First, convert the Rosenbrock function f to a system of nonlinear equations F, where F is a gradient
of f.
clear
n = 64;
x = sym('x',[n,1]);
f = sum(100*(x(2:2:n)-x(1:2:n).^2).^2 + (1-x(1:2:n)).^2);
F = gradient(f,x);
5-47
5 Code Generation
ans =
2 x1 − 400 x1 x2 − x12 − 2
2 x3 − 400 x3 x4 − x32 − 2
2 x5 − 400 x5 x6 − x52 − 2
2 x7 − 400 x7 x8 − x72 − 2
To match the intermediate results shown in the “Solve Nonlinear System Without and Including
Jacobian” (Optimization Toolbox), use the same form of F.
F(1:2:n) = simplify(F(1:2:n) + 2*x(1:2:n).*F(2:2:n));
F(1:2:n) = -F(1:2:n)/2;
F(2:2:n) = F(2:2:n)/20;
ans =
1 − x1
10 x2 − 10 x12
1 − x3
10 x4 − 10 x32
1 − x5
10 x6 − 10 x52
1 − x7
10 x8 − 10 x72
1 − x9
10 x10 − 10 x92
Use jacobian to calculate the Jacobian of F. This function calculates the Jacobian symbolically, thus
avoiding errors associated with numerical approximations of derivatives.
JF = jacobian(F,x);
ans =
5-48
Improving Accuracy and Performance in Optimization
−1 0 0 0 0 0 0 0 0 0
−20 x1 10 0 0 0 0 0 0 0 0
0 0 −1 0 0 0 0 0 0 0
0 0 −20 x3 10 0 0 0 0 0 0
0 0 0 0 −1 0 0 0 0 0
0 0 0 0 −20 x5 10 0 0 0 0
0 0 0 0 0 0 −1 0 0 0
0 0 0 0 0 0 −20 x7 10 0 0
0 0 0 0 0 0 0 0 −1 0
0 0 0 0 0 0 0 0 −20 x9 10
Most of the elements of the Jacobian matrix JF are zeros. Nevertheless, when you convert this matrix
to a matlabFunction, the result is a dense numeric matrix. Often, operations on sparse matrices
are more efficient than the same operations on dense matrices.
Therefore, to create efficient code, convert only the nonzero elements of JF to a symbolic vector
before invoking matlabFunction. is and js represent the sparsity pattern of JF.
[is,js] = find(JF);
JF = JF(JF~=0);
The system of equations F, representing the Rosenbrock function, is a symbolic matrix that consists
of symbolic expressions. To be able to solve it with the fsolve function, convert this system to a
matlabFunction. At this step, it is convenient to convert both F and its Jacobian, JF, to a single file-
based MATLAB function, FJFfun. In principle, this allows F and JF to reuse variables. Alternatively,
you can convert them to individual MATLAB functions.
matlabFunction([F;JF],'var',x,'file','FJFfun');
FJFfun accepts variables as a list, but fsolve expects a vector of variables. The function
genericObj converts the vector to a list. Anonymous function bananaObj is defined to fix argument
values for genericObj. Note the use of the sparsity pattern in the function genericObj. Further
note that this approach of using FJFfun and genericObj together is not tied to the particular
expression represented by F and can be used as is for any F.
Use fsolve for the system of equations, converted to MATLAB function. Use the starting point x(i) =
–1.9 for the odd indices, and x(i) = 2 for the even indices. Set 'Display' to'iter' to see the
solver's progress. Set 'Jacobian' to 'on' to use the Jacobian defined in bananaobj.
x0(1:n,1) = -1.9;
x0(2:2:n,1) = 2;
options = optimoptions(@fsolve,'Display','iter','Jacobian','on');
[sol1,Fsol,exitflag,output,JAC] = fsolve(bananaobj,x0,options);
5-49
5 Code Generation
Equation solved.
The system of nonlinear equations, F, can be alternatively solved with the vpasolve function, which
is a numeric solver available in Symbolic Math Toolbox. A key difference between vpasolve and
fsolve is that fsolve uses double-precision arithmetic to solve the equations, whereas vpasolve
uses variable-precision arithmetic and therefore, lets you control the accuracy of computations.
sol2 = vpasolve(F);
If you assign the solution of a system of equations to one variable, sol2, then vpasolve returns the
solutions in form of a structure array. You can access each solution (each field of the structure array):
sol2.x1
ans = 1.0
You also can convert sol2 to a symbolic vector, and then access a range of the solutions. For
example, display the 10th to 20th solutions:
for k=(1:64)
sol2_array(k) = sol2.(char(x(k)));
end
sol2_array(10:20)
ans = 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0
Helper Functions
function [F,J] = genericObj(x,FJFfun,is,js)
% genericObj takes as input, vector x, Function and Jacobian evaluation
5-50
Improving Accuracy and Performance in Optimization
% function handle FJFfun, and sparsity pattern is,js and returns as output,
% the numeric values of the Function and Jacobian: F and Jfunction
% FJs(1:length(x)) is the numeric vector for the Function
% FJs(length(x)+1:end) is the numeric vector for the non-zero entries of the Jacobian
xcell = num2cell(x);
FJs = FJFfun(xcell{:});
F = FJs(1:length(x));
J = sparse(is,js,FJs(length(x)+1:end));
end
5-51
5 Code Generation
This example shows how to find parameterized analytical expressions for the displacement of a joint
of a trivial cantilever truss structure in both the static and frequency domains. The analytical
expression for the static case is exact. The expression for the frequency response function is an
approximate reduced-order version of the actual frequency response.
The goal of this example is to analytically relate the displacement d to the uniform cross-section area
parameter A for a particular bar in the cantilever truss structure. The governing equation is
2
d x
represented by M + Kx = F. Here, d results from a load at the upper-right joint of the cantilever.
dt2
The truss is attached to the wall at the leftmost joints.
The truss bars are made of a linear elastic material with uniform density. The cross-section area A of
the bar highlighted in blue (see figure) can vary. All other parameters, including the uniform cross-
section areas of the other bars, are fixed. Obtain the displacement of the tip by using small and linear
displacement assumptions.
Specify the length and height of the truss and the number of top horizontal truss bars.
L = 1.5;
H = 0.25;
N = 3;
Specify the density and modulus of elasticity of the truss bar material.
5-52
Analytical Model of Cantilever Truss Structure for Simscape
rhoval = 1e2;
Eval = 1e7;
AFixed = 1;
Next, define the local stiffness matrix of the specific truss element.
Compute the local stiffness matrix k and express it as a symbolic function. The forces and
displacements of the truss element are related through the local stiffness matrix. Each node of the
truss element has two degrees of freedom, horizontal and vertical displacement. The displacement of
each truss element is a column matrix that corresponds to [x_node1,y_node1,x_node2,y_node2]. The
resulting stiffness matrix is a 4-by-4 matrix.
syms A E l t real
G = [cos(t) sin(t) 0 0; 0 0 cos(t) sin(t)];
kk = A*E/l*[1 -1;-1 1];
k = simplify(G'*kk*G);
localStiffnessFn = symfun(k,[t,l,E])
localStiffnessFn(t, l, E) =
σ2 σ1 −σ2 −σ1
σ1 σ3 −σ1 −σ3
−σ2 −σ1 σ2 σ1
−σ1 −σ3 σ1 σ3
where
A E sin 2 t
σ1 =
2l
2
A E cos t
σ2 =
l
2
A E sin t
σ3 =
l
syms rho
mm = A*rho*l/6*[2 1;1 2];
m = simplify(G'*mm*G);
localMassFn = symfun(m,[t,l,rho]);
5-53
5 Code Generation
Now, define the bars of truss as a matrix bars. The indices for the bars, starting joints, and end joints
are shown in the following figure.
The number of rows of the matrix bars is the number of bars of the truss. The columns of bars have
four elements, which represent the following parameters:
• Length (l)
• Angle with respect to the horizontal axis (t)
• Index of starting joint
• Index of ending joint
bars = zeros(2*N+2*(N-1),4);
Define the upper and diagonal bars. Note that the bar of interest is the (N+1)th bar or bar number 4
which is the first diagonal bar from the left.
for n = 1:N
lelem = L/N;
bars(n,:) = [lelem,0,n,n+1];
lelem = sqrt((L/N)^2+H^2);
bars(N+n,:) = [lelem,atan2(H,L/N),N+1+n,n+1];
end
The truss structure has seven nodes. Each node has two degrees of freedom (horizontal and vertical
displacements). The total number of degrees of freedom in this system is 14.
numDofs = 2*2*(N+1)-2
numDofs = 14
The system mass matrix M and system stiffness matrix K are symbolic matrices. Assemble local
element matrices from each bar into the corresponding global matrix.
5-54
Analytical Model of Cantilever Truss Structure for Simscape
K = sym(zeros(numDofs,numDofs));
M = sym(zeros(numDofs,numDofs));
for j = 1:size(bars,1)
% Construct stiffness and mass matrices for bar j.
lelem = bars(j,1); telem = bars(j,2);
kelem = localStiffnessFn(telem,lelem,Eval);
melem = localMassFn(telem,lelem,rhoval);
n1 = bars(j,3); n2 = bars(j,4);
% For bars that are not within the parameterized area A, set the stiffness
% and mass matrices to numeric values. Note that although the values
% kelem and melem do not have symbolic parameters, they are still
% symbolic objects (symbolic numbers).
if j ~= N+1
kelem = subs(kelem,A,AFixed);
melem = subs(melem,A,AFixed);
end
% Arrange the indices.
ix = [n1*2-1,n1*2,n2*2-1,n2*2];
% Embed local elements in system global matrices.
K(ix,ix) = K(ix,ix) + kelem;
M(ix,ix) = M(ix,ix) + melem;
end
F is the load vector with a load specified in the negative Y direction at the upper rightmost joint.
F = zeros(size(K,1),1);
F(2*N) = -1;
To extract the Y displacement at the upper rightmost joint, create a selection vector.
c = zeros(1,size(K,1));
c(2*N) = 1;
Create Simscape Equations from Exact Symbolic Solution for Static Case
Find and plot the analytical solution for the displacement d as a function of A. Here, K\F represents
the displacements at all joints and c selects the particular displacements. First, show the symbolic
solution representing numeric values using 16 digits for compactness.
d_Static = simplify(c*(K\F));
vpa(d_Static,16)
ans =
0.00000001118033988749895 504.7737197247586 A2 + 384.7213595499958 A + 22.3606797749979
−
A 1.28 A + 0.8944271909999158
fplot(d_Static,[AFixed/10,10*AFixed]);
hold on;
xlabel('Cross-Section, A');
5-55
5 Code Generation
ylabel('Displacement, d');
title('')
Convert the result to a Simscape equation ssEq to use inside a Simscape block. To display the
resulting Simscape equation, remove the semicolon.
syms d
ssEq = simscapeEquation(d,d_Static);
strcat(ssEq(1:120),'...')
ans =
'd == (sqrt(5.0)*(A*2.2e+2+A*cos(9.272952180016122e-1)*2.0e+2+sqrt(5.0)*A^2*1.16e+2+sqrt(5.0)*1.0
Compare the exact analytical solution and numeric solution over a range of A parameter values. The
values form a sequence from AFixed to 5*AFixed in increments of 1.
AParamValues = AFixed*(1:5)';
d_NumericArray = zeros(size(AParamValues));
for k=1:numel(AParamValues)
beginDim = (k-1)*size(K,1)+1;
endDim = k*size(K,1);
% Create a numeric stiffness matrix and extract the numeric solution.
KNumeric = double(subs(K,A,AParamValues(k)));
5-56
Analytical Model of Cantilever Truss Structure for Simscape
d_NumericArray(k) = c*(KNumeric\F);
end
Compute the symbolic values over AParamValues. To do so, call the subs function, and then convert
the result to double-precision numbers using double.
d_SymArray = double(subs(d_Static,A,AParamValues));
T = table(AParamValues,d_SymArray,d_NumericArray)
T=5×3 table
AParamValues d_SymArray d_NumericArray
____________ ___________ ______________
1 -4.6885e-06 -4.6885e-06
2 -4.5488e-06 -4.5488e-06
3 -4.5022e-06 -4.5022e-06
4 -4.4789e-06 -4.4789e-06
5 -4.4649e-06 -4.4649e-06
A parametric representation for the frequency response H(s,A) can be efficient for quickly
examining the effects of parameter A without resorting to potentially expensive numeric calculations
for each new value of A. However, finding an exact closed-form solution for a large system with
additional parameters is often impossible. Therefore, you typically approximate a solution for such
systems. This example approximates the parametric frequency response near the zero frequency as
follows:
digits(32);
K = vpa(K);
M = vpa(M);
[LK,UK] = lu(K);
5-57
5 Code Generation
iK = @(x) UK\(LK\x);
iK_M = @(x) -iK(M*x);
momentPre = iK(F);
Define a frequency series corresponding to the first three moments. Here, s is the frequency.
syms s
sPowers = [1 s^2 s^4];
Set the first moment, which is the same as d_Static in the previous computation.
moments = d_Static;
Combine the moment terms to create the approximate analytical frequency response Happrox.
HApprox = sPowers*moments;
Display the first three moments. Because the expressions are large, you can display them only
partially.
momentString = arrayfun(@char,moments,'UniformOutput',false);
freqString = arrayfun(@char,sPowers.','UniformOutput',false);
table(freqString,momentString,'VariableNames',{'FreqPowers','Moments'})
ans=3×2 table
FreqPowers
__________ _______________________________________________________________________________
Convert the frequency response to a MATLAB function containing numeric values for A and s. You
can use the resulting MATLAB function without Symbolic Math Toolbox.
HApproxFun = matlabFunction(HApprox,'vars',[A,s]);
Vary the frequency from 0 to 1 in logspace, and then convert the range to radians.
freq = 2*pi*logspace(0,1);
Compute the numeric values of the frequency response for A = AFixed*perturbFactor, that is,
for a small perturbation around A.
perturbFactor = 1 + 0.25;
KFixed = double(subs(K,A,AFixed*perturbFactor));
5-58
Analytical Model of Cantilever Truss Structure for Simscape
MFixed = double(subs(M,A,AFixed*perturbFactor));
H_Numeric = zeros(size(freq));
for k=1:numel(freq)
sVal = 1i*freq(k);
H_Numeric(k) = c*((sVal^2*MFixed + KFixed)\F);
end
Compute the symbolic values of the frequency response over the frequency range and A =
perturbFactor*AFixed.
H_Symbolic = HApproxFun(AFixed*perturbFactor,freq*1i);
figure
loglog(freq/(2*pi),abs(H_Symbolic),freq/(2*pi),abs(H_Numeric),'k*');
xlabel('Frequency');
ylabel('Frequency Response');
legend('Symbolic','Numeric');
The analytical and numeric curves are close in the chosen interval, but, in general, the curves diverge
for frequencies outside the neighborhood of s = 0. Also, for values of A far from AFixed, the Taylor
approximation introduces larger errors.
5-59
5 Code Generation
Create custom-equation-based components for the Simscape™ library using the Symbolic Math
Toolbox™.
Introduction
The Symbolic Math Toolbox provides a flexible way to develop models from first engineering
principles in any spatial dimension. You can develop mathematical models for steady state or
transient physics.
You can develop and solve the equations required to represent the physics necessary for your
component; and perform your own reduced-order model mapping between the inputs x and a quantity
of interest f(x).
Here f is the custom component which can represent governing equations in the form of:
• Mathematical formulas
• Numerical simulations of ODEs and PDEs
5-60
Customize and Extend Simscape Libraries for a Custom DC Motor
To run this example, you must have licenses for Simscape and Symbolic Math Toolbox.
DC Motor Model
A DC motor is a device for converting electrical energy into mechanical energy and vice versa. A
schematic of a DC motor is shown below (left figure). Blocks that simulate DC motors are provided in
“Simscape Electrical”™ (right figure), which is an optional product for Simscape.
In this example, we will derive a reduced-order model representation of a DC Motor using the
governing Ordinary Differential Equations (ODEs). For a DC motor, the electrical voltage and current
is derived from Kirchhoff’s laws and the formula of the mechanical torque is derived from Newton’s
laws. Using these equations we can implement a custom and parametric Simscape component.
5-61
5 Code Generation
∂
J w t = Ki I t − Dr w t
∂t
∂
L I t + R I t = V t − Kb w t
∂t
Suppose you have a Simscape component MyMotorTemplate.ssc in your current folder or on the
default MATLAB path. This component has no equations yet. The template records the parameters
and variables which will be used to develop our motor. You can use type to provide a preview of that
template.
type MyMotorTemplate.ssc
component MyMotorTemplate
% Custom DC Motor
% This block implements a custom DC motor
nodes
p = foundation.electrical.electrical; % +:left
n = foundation.electrical.electrical; % -:left
r = foundation.mechanical.rotational.rotational; % R:right
c = foundation.mechanical.rotational.rotational; % C:right
end
parameters
R = {3.9, 'Ohm'}; %Armature resistance
L = {0.000012, 'H'}; %Armature inductance
J = {0.000001, 'kg*m^2'}; %Inertia
Dr = {0.000003, '(N*m*s)/rad'}; %Rotor damping
Ki = {0.000072, '(N*m)/A'}; %Torque constant
Kb = {0.000072, '(V*s)/rad'}; %Back-emf constant
end
variables
torque = {0, 'N*m'}; %Total Torque
tau = {0, 'N*m'}; %Electric Torque
w = {0, 'rad/s'}; %Angular Velocity
I = {0, 'A'}; %Current
V = {0, 'V'}; %Applied voltage
Vb = {0, 'V'}; %Counter electromotive force
end
function setup
if(R<=0)
error('Winding resistance must be greater than 0.');
end
end
branches
torque : r.t -> c.t; % Through variable tau from r to c
I : p.i -> n.i; % Through variable i from p to n
end
equations
w == r.w -c.w; % Across variable w from r to c
V == p.v -n.v; % Across variable v from p to n
end
end
Read the names, values, and units of the parameters from the template component.
5-62
Customize and Extend Simscape Libraries for a Custom DC Motor
Display the parameters, their values, and the corresponding units as vectors.
ans =
Dr J Kb Ki L R
0.000003 0.000001 0.000072 0.000072 0.000012 3.9
Nms Vs Nm
kg m2 H Ω
rad rad A
Add the parameter names to the MATLAB Workspace by using the syms function. Parameters appear
as symbolic variables in the workspace. You can use who to list variables in the workspace.
syms(parNames)
syms
Dr J Kb Ki L R ans
Read and display the names of the component variables. Use ReturnFunction to simultaneously
convert these variables to functions of the variable t.
ans =
I t V t Vb t τ t torque t w t
0 0 0 0 0 0
rad
A V V Nm Nm
s
Add the variable names to the MATLAB Workspace by using the syms function. Variables appear as
symbolic functions in the workspace. Verify that you have declared all required symbolic variables
and functions using syms.
syms(varFuns)
syms
Dr I J Kb Ki L R V Vb ans t tau t
The differential equations for the mechanical torque are defined as eq1 and eq2. I(t) represents the
current and w(t) the angular velocity.
eq1(t) =
∂
J w t + torque t = τ t − Dr w t
∂t
eq2 = τ t = Ki I t
5-63
5 Code Generation
The equations for the electrical voltage and current are eq3 and eq4. V(t) and Vb(t) represent the
applied voltage and counter electromotive force respectively.
eq3 =
∂
L I t + R I t = V t − Vb t
∂t
eq4 = Vb t = Kb w t
We can list them together. Here, the motor’s torque is assumed to be proportional to the current.
eqs =
∂
J w t + torque t = τ t − Dr w t
∂t
τ t = Ki I t
∂
L I t + R I t = V t − Vb t
∂t
Vb t = Kb w t
operands = children(eqs);
operList = [ operands{:} ];
lhs = operList(1:2:end)
rhs = operList(2:2:end)
The second and fourth equations define the values tau(t) and Vb(t). To simplify the system of four
equations to a system of two equations, substitute these values into the first and third equation.
equations =
∂
J w t + torque t = Ki I t − Dr w t
∂t
equations =
∂ ∂
J w t + torque t = Ki I t − Dr w t L I t + R I t = V t − Kb w t
∂t ∂t
equations.'
ans =
5-64
Customize and Extend Simscape Libraries for a Custom DC Motor
∂
J w t + torque t = Ki I t − Dr w t
∂t
∂
L I t + R I t = V t − Kb w t
∂t
Before solving the equations, substitute parameters with their numeric values. Also, use V(t) = 1.
ans =
∂
0.000001 w t = 0.000072 I t − 0.000003 w t
∂t
∂
0.000012 I t + 3.9 I t = 1.0 − 0.000072 w t
∂t
For this, remove the time dependency for the functions w(t) and I(t). For example, substitute them
with symbolic variables ww and ii.
syms ww ii
equations_steady = subs(equations, [w(t),I(t)], [ww,ii]);
result = solve(equations_steady,ww,ii);
steadyStateW = vpa(result.ww,10)
steadyStateW = 6.151120734
steadyStateI = vpa(result.ii,10)
steadyStateI = 0.2562966973
Create a valid input for ode45 from the symbolic equations. Use odeToVectorField to create the
dY
MATLAB procedure which represents the dynamical system dt
= f t, Y with the initial condition
Y t0 = Y 0.
vfEquations =
147573952589676412928 2877692075498690052096 Y 1
− 6 Y2 −
1770887431076117 8854437155380585
83010348331692984375 Y 1 27670116110564328125 Y 2
−
1152921504606846976 9223372036854775808
tVals =
I
w
M = matlabFunction(vfEquations,'Vars', {'t','Y'})
5-65
5 Code Generation
Solve the differential equation using the initial conditions w(0) = 0 and I(0) = 0.
Evaluate the solution at the following points in time t=[0.5,0.75,1]. The first value is the current I(t)
and the second value is the angular velocity w(t). We see that the solution for the angular velocity is
starting to approach a steady state steadyStateW.
ans = 2×1
0.2563
4.7795
ans = 2×1
0.2563
5.5034
ans = 2×1
0.2563
5.8453
steadyStateW
steadyStateW = 6.151120734
time = linspace(0,2.5);
iValues = deval(solution, time, 1);
wValues = deval(solution, time, 2);
steadyStateValuesI = vpa(steadyStateI*ones(1,100),10);
steadyStateValuesW = vpa(steadyStateW*ones(1,100),10);
figure;
plot1 = subplot(2,1,1);
plot2 = subplot(2,1,2);
5-66
Customize and Extend Simscape Libraries for a Custom DC Motor
type MyMotor.ssc
component MyMotor
% Custom DC Motor
% This block implements a custom DC motor
nodes
p = foundation.electrical.electrical; % +:left
n = foundation.electrical.electrical; % -:left
r = foundation.mechanical.rotational.rotational; % R:right
c = foundation.mechanical.rotational.rotational; % C:right
end
parameters
5-67
5 Code Generation
if ~isdir('+MyLib')
mkdir +MyLib;
end
copyfile MyMotor.ssc +MyLib;
ssc_build MyLib;
See Also
Functions
diff | subs | solve | matlabFunction | ode45 | symReadSSCParameters |
symReadSSCVariables | symWriteSSC
5-68
Estimate Model Parameters of a Symbolically Derived Plant Model in Simulink
This example uses Simulink Design Optimization™ to estimate the unknown capacitance and initial
voltage of a symbolically derived algebraic model of a simple resistor-capacitor (RC) circuit. The
example solves the same problem and uses the same experimental data as “Estimate Model
Parameters and Initial States (Code)” (Simulink Design Optimization), but uses the closed-form
solution for the RC circuit instead of the differential form.
You perform design optimization to estimate the capacitance and initial voltage values of the
analytical RC circuit. In particular, you match the experimental output voltage values with the
simulated values.
Define and solve the following differential equation for the RC circuit.
Here, v2(t) is the output voltage across capacitor C1, v1 is the constant voltage across resistor R1,
and v20 is the initial voltage across the capacitor. Use dsolve to solve the equation.
v2sol =
5-69
5 Code Generation
t
−
v1 − e C1 R1 v1 − v20
Use subs to evaluate the solution for an R1 value of 10 kOhm and v1 value of 5 V.
v2sol = vpa(subs(v2sol,[R1,v1],[10e3,5]))
v2sol =
0.0001 t
−
e C1 v20 − 5.0 + 5.0
myModel = 'rcSymbolic';
new_system(myModel);
load_system(myModel);
Use matlabFunctionBlock to convert the symbolic result for the output voltage to a Simulink block
representing the RC plant model. matlabFunctionBlock adds this new block to the model.
blockName = 'closedFormRC_block';
rcBlock = strcat(myModel,'/',blockName);
myVars = [C1,v20,t];
matlabFunctionBlock(rcBlock,v2sol,...
'vars',myVars,...
'functionName','myRC',...
'outputs',{'v2'});
Add and arrange other blocks with positions and sizes relative to the RC block.
rcBlockPosition = get_param(rcBlock,'position');
rcBlockWidth = rcBlockPosition(3)-rcBlockPosition(1);
rcBlockHeight = rcBlockPosition(4)-rcBlockPosition(2);
constantBlock = 'built-in/Constant';
timeBlock = 'simulink/Sources/Ramp';
outputBlock = 'built-in/Outport';
C1 and v20 are the parameters to estimate. First, introduce and initialize these parameters in the
MATLAB® workspace, using the initial values of 460 μF and 1 V, respectively. Then create constant
blocks for both parameters.
C1val = 460e-6;
v20val = 1.0;
posX = rcBlockPosition(1)-rcBlockWidth*2;
posY = rcBlockPosition(2)-rcBlockHeight*3/4;
pos = [posX,posY,posX+rcBlockWidth/2,posY+rcBlockHeight/2];
add_block(constantBlock,strcat(myModel,'/C1'),'Value','C1val',...
'Position',pos);
pos = pos + [0 rcBlockHeight 0 rcBlockHeight];
add_block(constantBlock,strcat(myModel,'/v20'),'Value','v20val',...
'Position',pos);
5-70
Estimate Model Parameters of a Symbolically Derived Plant Model in Simulink
Now, wire blocks in the model. The model is ready for Simulink Design Optimization.
myAddLine = @(k) add_line(myModel,...
strcat(char(myVars(k)),'/1'),...
strcat(blockName,'/',num2str(k)),...
'autorouting','on');
arrayfun(myAddLine,(1:numel(myVars)));
add_line(myModel,strcat(blockName,'/1'),'v2/1','autorouting','on');
open_system(myModel);
Estimate Parameters
The variables time and data are loaded into the workspace. data is the measured capacitor voltage
for times time.
5-71
5 Code Generation
Voltage = Simulink.SimulationData.Signal;
Voltage.Name = 'Voltage';
Voltage.BlockPath = rcBlock;
Voltage.PortType = 'outport';
Voltage.PortIndex = 1;
Voltage.Values = timeseries(data,time);
Add the measured capacitor data to the experiment as the expected output data.
Exp.OutputData = Voltage;
Get the parameters. Set a minimum value for C1. Note that you already specified the initial guesses.
c1param = sdo.getParameterFromModel(myModel,'C1val');
c1param.Minimum = 0;
v20param = sdo.getParameterFromModel(myModel,'v20val');
Define the objective function for estimation. The code for sdoRCSymbolic_Objective used in this
example is given in the Helper Functions section at the end of the example.
v = [c1param;v20param];
Because the model is entirely algebraic, turn off warning messages that instruct you to select a
discrete solver.
set_param(myModel,'SolverPrmCheckMsg','none');
opt = sdo.OptimizeOptions;
opt.Method = 'lsqnonlin';
vOpt = sdo.optimize(estFcn,v,opt);
First-order
Iter F-count f(x) Step-size optimality
0 5 27.7093 1
1 10 2.86889 1.919 2.94
2 15 1.53851 0.3832 0.523
3 20 1.35137 0.3347 0.505
4 25 1.34473 0.01374 0.00842
5 30 1.34472 0.002686 0.00141
Local minimum possible.
lsqnonlin stopped because the final change in the sum of squares relative to
its initial value is less than the value of the function tolerance.
5-72
Estimate Model Parameters of a Symbolically Derived Plant Model in Simulink
Update the experiment with the estimated capacitance and capacitor initial voltage values.
Exp = setEstimatedValues(Exp,vOpt);
Simulate the model with the estimated parameter values and compare the simulated output with the
experimental data.
Simulator = createSimulator(Exp);
Simulator = sim(Simulator);
SimLog = find(Simulator.LoggedData,get_param(myModel,'SignalLoggingName'));
Voltage = find(SimLog,'Voltage');
plot(time,data,'ro',Voltage.Values.Time,Voltage.Values.Data,'b')
title('Simulated and Measured Responses')
legend('Measured Voltage','Simulated Voltage','Location','Best')
close_system(myModel,0);
Helper Functions
5-73
5 Code Generation
Simulator = sim(Simulator);
SimLog = find(Simulator.LoggedData,get_param(myModel,'SignalLoggingName'));
Voltage = find(SimLog,'Voltage');
VoltageError = evalRequirement(r,Voltage.Values,Exp.OutputData(1).Values);
vals.F = VoltageError(:);
end
5-74
6
Note MuPAD notebook has been removed. Use MATLAB Live Editor instead.
To convert a MuPAD notebook file to a MATLAB live script file, see convertMuPADNotebook.
MATLAB live scripts support most MuPAD functionality, although there are some differences. For
more information, see “Convert MuPAD Notebooks to MATLAB Live Scripts” on page 6-3.
A MuPAD engine is a separate process that runs on your computer in addition to a MATLAB process.
A MuPAD engine starts when you first call a function that needs a symbolic engine, such as syms.
Symbolic Math Toolbox functions that use the symbolic engine use standard MATLAB syntax, such as
y = int(x^2).
Conceptually, each MuPAD notebook has its own symbolic engine, with an associated workspace. You
can have any number of MuPAD notebooks open simultaneously.
The engine workspace associated with the MATLAB workspace is generally empty, except for
assumptions you make about variables. For details, see “Clear Assumptions and Reset the Symbolic
Engine” on page 3-314.
6-2
Convert MuPAD Notebooks to MATLAB Live Scripts
Note convertMuPADNotebook will be removed in a future release. Convert your MuPAD notebooks
to MATLAB live scripts now, and use the MATLAB Live Editor instead.
Migrate MuPAD notebooks to MATLAB live scripts that use MATLAB code. Live scripts are an
interactive way to run MATLAB code. For details, see “What Is a Live Script or Function?”. MuPAD
notebooks are converted to live scripts by using Symbolic Math Toolbox. For more information, see
“Get Started with Symbolic Math Toolbox”.
convertMuPADNotebook('myNotebook.mn','myScript.mlx')
Alternatively, right-click the notebook in the Current Folder browser and select Open as Live
Script.
3 Check for errors or warnings: Check the output of convertMuPADNotebook for errors or
warnings. If there are none, go to step 7. For example, this output means that the converted live
script myScript.mlx has 4 errors and 1 warning.
A translation error means that the translated code will not run correctly while a translation
warning indicates that the code requires inspection. If the code only contains warnings, it will
likely run without issues.
4 Fix translation errors: Open the converted live script by clicking the link in the output. Find
errors by searching for ERROR. The error explains which MuPAD command did not translate
correctly. For details and fixes, click ERROR. After fixing the error, delete the error message. For
the list of translation errors, see “Troubleshoot MuPAD to MATLAB Translation Errors” on page
6-8. If you cannot fix your error, and the “Known Issues” on page 6-4 do not help, please
contact MathWorks Technical Support.
5 Fix translation warnings: Find warnings by searching for WARNING. The warning text explains
the issue. For details and fixes, click WARNING. Decide to either adapt the code or ignore the
warning. Then delete the warning message. For the list of translation warnings, see
“Troubleshoot MuPAD to MATLAB Translation Warnings” on page 6-15.
6 Verify the live script: Open the live script and check for unexpected commands, comments,
formatting, and so on. For readability, the converted code may require manual cleanup, such as
eliminating auxiliary variables.
7 Execute the live script: Ensure that the code runs properly and returns expected results. If the
results are not expected, check your MuPAD code for the “Known Issues” on page 6-4 listed
below.
6-3
6 MuPAD to MATLAB Migration
Known Issues
These are the known issues when converting MuPAD notebooks to MATLAB live scripts with the
convertMuPADNotebook function. If your issue is not described, please contact MathWorks
Technical Support.
Expand the list to view MuPAD objects that are not converted. To avoid conversion errors and
warnings, remove these objects or commands from your notebook before conversion.
• Reading code from files. Replace commands such as read("filename.mu") by the content of
filename.mu.
• Function calls with expression sequences as input arguments.
• Function calls where the function is generated by the preceding code instead of being specified
explicitly.
• Domains, and commands that create domains and their elements.
• Assignments to slots of domains and function environments.
• Commands using the history mechanism, such as last(2) or HISTORY := 30.
• MuPAD environment variables, such as ORDER, HISTORY, and LEVEL.
In MATLAB, when symbolic variables are assigned values, then expressions containing those values
are not automatically updated.
6-4
Convert MuPAD Notebooks to MATLAB Live Scripts
When values are assigned to variables, update any expressions that contain those variables by calling
subs on those expressions.
syms a b
f = a + b;
a = 1;
b = 2;
f % f is still a + b
subs(f) % f is updated
f =
a + b
ans =
3
In MuPAD, last(1) always returns the last result. In MATLAB, ans returns the result of the last
unassigned command. For example, in MATLAB if you run x = 1, then calling ans does not return 1.
Instead of using ans, assign the result to a variable and use that variable.
When results of MuPAD solve are accessed, convertMuPADNotebook assumes that the result is a
finite set. However, if the result is a non-finite set then the code is wrongly translated.
There is no general solution. Further, non-finite solution sets are not translatable.
If you are accessing parameters or conditions, use the parameters or conditions output
arguments of MATLAB solve.
syms x
S = solve(sin(x) == 1, x, 'ReturnConditions', true);
S.x % solution
S.parameters % parameters in solution
S.conditions % conditions on solution
ans =
pi/2 + 2*pi*k
ans =
k
ans =
in(k, 'integer')
In MuPAD, a break ends a case in a switch case. However, MATLAB does not require a break to end
a case. Thus, a MuPAD break introduces an unnecessary break in MATLAB. Also, if a MuPAD case
omits a break, then the MATLAB case will not fall-through.
6-5
6 MuPAD to MATLAB Migration
In the live script, delete break statements that end cases in a switch-case statement.
For fall-through in MATLAB, specify all values with their conditions in one case.
While the most commonly used MuPAD graphics options are translated, there are some options that
are not translated.
Find the corresponding option in MATLAB by using the properties of the figure handle gcf or axis
handle gca. For example, the MuPAD command plot(sin(x), Width = 80*unit::mm, Height
= 4*unit::cm) sets height and width. Translate it to MATLAB code.
syms x
fplot(sin(x));
g = gcf;
g.Units = 'centimeters';
g.Position(3:4) = [8 4];
Operations on matrices are not always translated correctly. For example, if M is a matrix, then exp(M)
in MuPAD is wrongly translated to exp(M) instead of the matrix exponential expm(M).
When performing operations on matrices, search for the matrix operation and use it instead. For
example, in MATLAB:
indets is translated to MATLAB symvar. However, symvar does not find bound variables or
constant identifiers like PI in MuPAD.
6-6
Convert MuPAD Notebooks to MATLAB Live Scripts
The return type of MuPAD factor has no equivalent in MATLAB. Subsequent operations on the
results of factor in MATLAB might return incorrect results.
Check and modify the output of factor in MATLAB as required such that subsequent commands run
correctly.
Layout Issues
For the syntax differences between MATLAB and MuPAD, see “Differences Between MATLAB and
MuPAD Syntax” on page 6-20.
6-7
6 MuPAD to MATLAB Migration
Note convertMuPADNotebook will be removed in a future release. Convert your MuPAD notebooks
to MATLAB live scripts now, and use the MATLAB Live Editor instead.
This page helps troubleshoot errors generated by the convertMuPADNotebook function when
converting MuPAD notebooks to MATLAB live scripts. For the conversion steps, see “Convert MuPAD
Notebooks to MATLAB Live Scripts” on page 6-3. To troubleshoot warnings, see “Troubleshoot
MuPAD to MATLAB Translation Warnings” on page 6-15.
6-8
Troubleshoot MuPAD to MATLAB Translation Errors
Domains, function
environments, and their slots
are not available in MATLAB.
Unable to translate explicitly MuPAD lets you use special Adjust the code so that it does
given coefficient ring. coefficient rings that cannot be not use polynomials over special
represented by arithmetical rings.
expressions. Specifying
coefficient rings of polynomials
is not available in MATLAB.
Unable to translate MuPAD uses the value Adjust the code so that it does
complexInfinity. complexInfinity. This value not use complexInfinity.
is not available in MATLAB.
6-9
6 MuPAD to MATLAB Migration
convertMuPADNotebook
cannot translate MuPAD
environment variables because
they are not available in
MATLAB.
Unable to translate function calls In MuPAD, a function call f(x), Adjust the code so that it does
with expression sequences as where x is a sequence of n not contain function calls with
input arguments. operands, resolves to a call with expression sequences as input
n arguments. arguments.
6-10
Troubleshoot MuPAD to MATLAB Translation Errors
6-11
6 MuPAD to MATLAB Migration
convertMuPADNotebook can
translate simple procedures to
anonymous functions. Simple
procedures do not contain loops,
assignments, multiple
statements, or nested functions
where the inner function
accesses variables of the outer
function.
6-12
Troubleshoot MuPAD to MATLAB Translation Errors
6-13
6 MuPAD to MATLAB Migration
6-14
Troubleshoot MuPAD to MATLAB Translation Warnings
Note convertMuPADNotebook will be removed in a future release. Convert your MuPAD notebooks
to MATLAB live scripts now, and use the MATLAB Live Editor instead.
This page helps troubleshoot warnings generated by the convertMuPADNotebook function when
converting MuPAD notebooks to MATLAB live scripts. For the conversion steps, see “Convert MuPAD
Notebooks to MATLAB Live Scripts” on page 6-3. To troubleshoot errors, see “Troubleshoot MuPAD to
MATLAB Translation Errors” on page 6-8.
convertMuPADNotebook
corrected it.
6-15
6 MuPAD to MATLAB Migration
6-16
Troubleshoot MuPAD to MATLAB Translation Warnings
6-17
6 MuPAD to MATLAB Migration
6-18
Troubleshoot MuPAD to MATLAB Translation Warnings
6-19
6 MuPAD to MATLAB Migration
Note MuPAD notebook has been removed. Use MATLAB Live Editor instead.
To convert a MuPAD notebook file to a MATLAB live script file, see convertMuPADNotebook.
MATLAB live scripts support most MuPAD functionality, although there are some differences. For
more information, see “Convert MuPAD Notebooks to MATLAB Live Scripts” on page 6-3.
There are several differences between MATLAB and MuPAD syntax. Be aware of which interface you
are using in order to use the correct syntax:
• Use MATLAB syntax in the MATLAB workspace, except for the functions
evalin(symengine,...) and feval(symengine,...), which use MuPAD syntax.
• Use MuPAD syntax only in MuPAD notebooks.
You must define MATLAB variables before using them. However, every expression entered in a
MuPAD notebook is assumed to be a combination of symbolic variables unless otherwise defined. This
means that you must be especially careful when working in MuPAD notebooks, since fewer of your
typos cause syntax errors.
This table lists common tasks, meaning commands or functions, and how they differ in MATLAB and
MuPAD syntax.
The next table lists differences between MATLAB expressions and MuPAD expressions.
6-20
Differences Between MATLAB and MuPAD Syntax
The MuPAD definition of exponential integral differs from the Symbolic Math Toolbox counterpart.
x
t
ei x = ∫ et dt .
−∞
6-21
6 MuPAD to MATLAB Migration
Note MuPAD notebook has been removed. Use MATLAB Live Editor instead.
To convert a MuPAD notebook file to a MATLAB live script file, see convertMuPADNotebook.
MATLAB live scripts support most MuPAD functionality, although there are some differences. For
more information, see “Convert MuPAD Notebooks to MATLAB Live Scripts” on page 6-3.
To access built-in MuPAD functions at the MATLAB command line, use evalin(symengine,...) or
feval(symengine,...). These functions are designed to work like the existing MATLAB evalin
and feval functions.
evalin and feval do not open a MuPAD notebook, and therefore, you cannot use these functions to
access MuPAD graphics capabilities.
evalin
For evalin, the syntax is
y = evalin(symengine,'MuPAD_Expression');
Use evalin when you want to perform computations in the MuPAD language, while working in the
MATLAB workspace. For example, to make a three-element symbolic vector of the sin(kx) function,
k = 1 to 3, enter:
y = evalin(symengine,'[sin(k*x) $ k = 1..3]')
y =
[ sin(x), sin(2*x), sin(3*x)]
feval
For evaluating a MuPAD function, you can also use the feval function. feval has a different syntax
than evalin, so it can be simpler to use. The syntax is:
y = feval(symengine,'MuPAD_Function',x1,...,xn);
MuPAD_Function represents the name of a MuPAD function. The arguments x1,...,xn must be
symbolic variables, numbers, or character vectors. For example, to find the tenth element in the
Fibonacci sequence, enter:
z = feval(symengine,'numlib::fibonacci',10)
z =
55
The next example compares the use of a symbolic solution of an equation to the solution returned by
the MuPAD numeric fsolve function near the point x = 3. The symbolic solver returns these
results:
syms x
f = sin(x^2);
solve(f)
6-22
Call Built-In MuPAD Functions from MATLAB
ans =
0
feval(symengine, 'numeric::fsolve',f,'x=3')
ans =
x == 3.0699801238394654654386548746678
As you might expect, the answer is the numerical value of 3π. The setting of MATLAB format does
not affect the display; it is the full returned value from the MuPAD 'numeric::fsolve' function.
syms x
y = x^2;
evalin(symengine, 'cos(y)')
ans =
cos(y)
In contrast, feval(symengine,...) can pass symbolic variables that exist in the MATLAB
workspace, and these variables are evaluated before being processed in the MuPAD engine. For
example:
syms x
y = x^2;
feval(symengine,'cos',y)
ans =
cos(x^2)
y =
igamma(1/10, 5/2)
To approximate the result numerically with double precision, use the double function:
format long
double(y)
6-23
6 MuPAD to MATLAB Migration
ans =
0.028005841168289
Alternatively, use quotes to prevent the conversion of floating-point arguments to rational numbers.
(The toolbox treats arguments enclosed in quotes as character vectors.) When MuPAD performs
arithmetic operations on numbers involving at least one floating-point number, it automatically
switches to numeric computations and returns a floating-point result:
ans =
0.028005841168289177028337498391181
For further computations, set the format for displaying outputs back to short:
format short
6-24
7
Functions
7 Functions
abs
Symbolic absolute value (complex modulus or magnitude)
Syntax
abs(z)
Description
abs(z) returns the absolute value (or complex modulus) of z. Because symbolic variables are
assumed to be complex by default, abs returns the complex modulus (magnitude) by default. If z is
an array, abs acts element-wise on each element of z.
Examples
ans =
[ 1/2, 0, 4 - pi]
Compute abs(x)^2 and simplify the result. Because symbolic variables are assumed to be complex
by default, the result does not simplify to x^2.
syms x
simplify(abs(x)^2)
ans =
abs(x)^2
Assume x is real, and repeat the calculation. Now, the result is simplified to x^2.
assume(x,'real')
simplify(abs(x)^2)
ans =
x^2
Remove assumptions on x for further calculations. For details, see “Use Assumptions on Symbolic
Variables” on page 1-41.
assume(x,'clear')
7-2
abs
A = sym([1/2+i -25;
i pi/2]);
abs(A)
ans =
[ 5^(1/2)/2, 25]
[ 1, pi/2]
Compute the absolute value of this expression assuming that the value of x is negative.
syms x
assume(x < 0)
abs(5*x^3)
ans =
-5*x^3
syms x
Input Arguments
z — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, vector, matrix, or array,
variable, function, or expression.
More About
Complex Modulus
The absolute value of a complex number z = x + y*i is the value z = x2 + y2. Here, x and y are real
numbers. The absolute value of a complex number is also called a complex modulus.
Tips
• Calling abs for a number that is not a symbolic object invokes the MATLAB abs function.
Version History
Introduced before R2006a
7-3
7 Functions
See Also
angle | imag | real | sign | signIm
7-4
acos
acos
Symbolic inverse cosine function
Syntax
acos(X)
Description
acos(X) returns the inverse cosine function (arccosine function) of X. All angles are in radians.
• For real values of X in the interval [-1,1], acos(x) returns the values in the interval [0,pi].
• For real values of X outside the interval [-1,1] and for complex values of X, acos(X) returns
complex values with the real parts in the interval [0,pi].
Examples
Inverse Cosine Function for Numeric and Symbolic Arguments
Compute the inverse cosine function for these numbers. Because these numbers are not symbolic
objects, acos returns floating-point results.
A =
3.1416 1.9106 2.0944 1.3181 1.0472 0.5236 0
Compute the inverse cosine function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, acos returns unresolved symbolic calls.
symA =
[ pi, pi - acos(1/3), (2*pi)/3, acos(1/4), pi/3, pi/6, 0]
vpa(symA)
ans =
[ 3.1415926535897932384626433832795,...
1.9106332362490185563277142050315,...
2.0943951023931954923084289221863,...
1.318116071652817965745664254646,...
1.0471975511965977461542144610932,...
0.52359877559829887307710723054658,...
0]
7-5
7 Functions
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing acos.
Find the first and second derivatives of the inverse cosine function:
syms x
diff(acos(x), x)
diff(acos(x), x, x)
ans =
-1/(1 - x^2)^(1/2)
ans =
-x/(1 - x^2)^(3/2)
ans =
x*acos(x) - (1 - x^2)^(1/2)
7-6
acos
taylor(acos(x), x)
ans =
- (3*x^5)/40 - x^3/6 - x + pi/2
rewrite(acos(x), 'log')
ans =
-log(x + (1 - x^2)^(1/2)*1i)*1i
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Version History
Introduced before R2006a
See Also
asin | atan | acsc | asec | acot | sin | cos | tan | csc | sec | cot
7-7
7 Functions
acosh
Symbolic inverse hyperbolic cosine function
Syntax
acosh(X)
Description
acosh(X) returns the inverse hyperbolic cosine function of X.
Examples
Inverse Hyperbolic Cosine Function for Numeric and Symbolic Arguments
Compute the inverse hyperbolic cosine function for these numbers. Because these numbers are not
symbolic objects, acosh returns floating-point results.
A =
0.0000 + 3.1416i 0.0000 + 1.5708i 0.0000 + 1.4033i...
0.0000 + 1.0472i 0.0000 + 0.0000i 1.3170 + 0.0000i
Compute the inverse hyperbolic cosine function for the numbers converted to symbolic objects. For
many symbolic (exact) numbers, acosh returns unresolved symbolic calls.
symA =
[ pi*1i, (pi*1i)/2, acosh(1/6), (pi*1i)/3, 0, acosh(2)]
vpa(symA)
ans =
[ 3.1415926535897932384626433832795i,...
1.5707963267948966192313216916398i,...
1.4033482475752072886780470855961i,...
1.0471975511965977461542144610932i,...
0,...
1.316957896924816708625046347308]
Plot the inverse hyperbolic cosine function on the interval from 1 to 10.
7-8
acosh
syms x
fplot(acosh(x),[1 10])
grid on
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing
acosh.
Find the first and second derivatives of the inverse hyperbolic cosine function. Simplify the second
derivative by using simplify.
syms x
diff(acosh(x), x)
simplify(diff(acosh(x), x, x))
ans =
1/((x - 1)^(1/2)*(x + 1)^(1/2))
ans =
-x/((x - 1)^(3/2)*(x + 1)^(3/2))
Find the indefinite integral of the inverse hyperbolic cosine function. Simplify the result by using
simplify.
int(acosh(x), x)
7-9
7 Functions
ans =
x*acosh(x) - (x - 1)^(1/2)*(x + 1)^(1/2)
assume(x > 1)
taylor(acosh(x), x)
ans =
(x^5*3i)/40 + (x^3*1i)/6 + x*1i - (pi*1i)/2
syms x
Rewrite the inverse hyperbolic cosine function in terms of the natural logarithm:
rewrite(acosh(x), 'log')
ans =
log(x + (x - 1)^(1/2)*(x + 1)^(1/2))
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Version History
Introduced before R2006a
See Also
asinh | atanh | acsch | asech | acoth | sinh | cosh | tanh | csch | sech | coth
7-10
acot
acot
Symbolic inverse cotangent function
Syntax
acot(X)
Description
acot(X) returns the inverse cotangent function (arccotangent function) of X. All angles are in
radians.
Examples
Inverse Cotangent Function for Numeric and Symbolic Arguments
Compute the inverse cotangent function for these numbers. Because these numbers are not symbolic
objects, acot returns floating-point results.
A =
-0.7854 -1.2490 -1.0472 1.1071 0.7854 0.5236
Compute the inverse cotangent function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, acot returns unresolved symbolic calls.
symA =
[ -pi/4, -acot(1/3), -pi/3, acot(1/2), pi/4, pi/6]
vpa(symA)
ans =
[ -0.78539816339744830961566084581988,...
-1.2490457723982544258299170772811,...
-1.0471975511965977461542144610932,...
1.1071487177940905030170654601785,...
0.78539816339744830961566084581988,...
0.52359877559829887307710723054658]
7-11
7 Functions
Plot the inverse cotangent function on the interval from -10 to 10.
syms x
fplot(acot(x),[-10 10])
grid on
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing acot.
Find the first and second derivatives of the inverse cotangent function:
syms x
diff(acot(x), x)
diff(acot(x), x, x)
ans =
-1/(x^2 + 1)
ans =
(2*x)/(x^2 + 1)^2
ans =
log(x^2 + 1)/2 + x*acot(x)
7-12
acot
assume(x > 0)
taylor(acot(x), x)
ans =
- x^5/5 + x^3/3 - x + pi/2
syms x
rewrite(acot(x), 'log')
ans =
(log(1 - 1i/x)*1i)/2 - (log(1i/x + 1)*1i)/2
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Version History
Introduced before R2006a
See Also
acos | asin | atan | acsc | asec | sin | cos | tan | csc | sec | cot
7-13
7 Functions
acoth
Symbolic inverse hyperbolic cotangent function
Syntax
acoth(X)
Description
acoth(X) returns the inverse hyperbolic cotangent function of X.
Examples
Inverse Hyperbolic Cotangent Function for Numeric and Symbolic Arguments
Compute the inverse hyperbolic cotangent function for these numbers. Because these numbers are
not symbolic objects, acoth returns floating-point results.
A =
-0.7525 + 0.0000i -Inf + 0.0000i 0.0000 + 1.5708i...
0.5493 + 1.5708i Inf + 0.0000i 0.7525 + 0.0000i
Compute the inverse hyperbolic cotangent function for the numbers converted to symbolic objects.
For many symbolic (exact) numbers, acoth returns unresolved symbolic calls.
symA =
[ -acoth(pi/2), Inf, -(pi*1i)/2, acoth(1/2), Inf, acoth(pi/2)]
vpa(symA)
ans =
[ -0.75246926714192715916204347800251,...
Inf,...
-1.5707963267948966192313216916398i,...
0.54930614433405484569762261846126...
- 1.5707963267948966192313216916398i,...
Inf,...
0.75246926714192715916204347800251]
Plot the inverse hyperbolic cotangent function on the interval from -10 to 10.
7-14
acoth
syms x
fplot(acoth(x),[-10 10])
grid on
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing
acoth.
Find the first and second derivatives of the inverse hyperbolic cotangent function:
syms x
diff(acoth(x), x)
diff(acoth(x), x, x)
ans =
-1/(x^2 - 1)
ans =
(2*x)/(x^2 - 1)^2
int(acoth(x), x)
ans =
log(x^2 - 1)/2 + x*acoth(x)
7-15
7 Functions
assume(x > 0)
taylor(acoth(x), x)
ans =
x^5/5 + x^3/3 + x - (pi*1i)/2
syms x
Rewrite the inverse hyperbolic cotangent function in terms of the natural logarithm:
rewrite(acoth(x), 'log')
ans =
log(1/x + 1)/2 - log(1 - 1/x)/2
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Version History
Introduced before R2006a
See Also
asinh | acosh | atanh | acsch | asech | sinh | cosh | tanh | csch | sech | coth
7-16
acsc
acsc
Symbolic inverse cosecant function
Syntax
acsc(X)
Description
acsc(X) returns the inverse cosecant function (arccosecant function) of X. All angles are in radians.
• For real values of X in intervals [-Inf,-1] and [1,Inf], acsc returns real values in the interval
[-pi/2,pi/2].
• For real values of X in the interval [-1,1] and for complex values of X, acsc returns complex
values with the real parts in the interval [-pi/2,pi/2].
Examples
Inverse Cosecant Function for Numeric and Symbolic Arguments
Compute the inverse cosecant function for these numbers. Because these numbers are not symbolic
objects, acsc returns floating-point results.
A =
-0.5236 + 0.0000i 1.5708 - Infi 1.0472 + 0.0000i 1.5708...
- 1.3170i 1.5708 + 0.0000i 0.2014 + 0.0000i
Compute the inverse cosecant function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, acsc returns unresolved symbolic calls.
symA =
[ -pi/6, Inf, pi/3, asin(2), pi/2, asin(1/5)]
vpa(symA)
ans =
[ -0.52359877559829887307710723054658,...
Inf,...
1.0471975511965977461542144610932,...
1.5707963267948966192313216916398...
- 1.3169578969248165734029498707969i,...
1.5707963267948966192313216916398,...
0.20135792079033079660099758712022]
7-17
7 Functions
Plot the inverse cosecant function on the interval from -10 to 10.
syms x
fplot(acsc(x),[-10 10])
grid on
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing acsc.
Find the first and second derivatives of the inverse cosecant function:
syms x
diff(acsc(x), x)
diff(acsc(x), x, x)
ans =
-1/(x^2*(1 - 1/x^2)^(1/2))
ans =
2/(x^3*(1 - 1/x^2)^(1/2)) + 1/(x^5*(1 - 1/x^2)^(3/2))
7-18
acsc
int(acsc(x), x)
ans =
x*asin(1/x) + log(x + (x^2 - 1)^(1/2))*sign(x)
taylor(acsc(x), x, Inf)
ans =
1/x + 1/(6*x^3) + 3/(40*x^5)
rewrite(acsc(x), 'log')
ans =
-log(1i/x + (1 - 1/x^2)^(1/2))*1i
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Version History
Introduced before R2006a
See Also
acos | asin | atan | asec | acot | sin | cos | tan | csc | sec | cot
7-19
7 Functions
acsch
Symbolic inverse hyperbolic cosecant function
Syntax
acsch(X)
Description
acsch(X) returns the inverse hyperbolic cosecant function of X.
Examples
Inverse Hyperbolic Cosecant Function for Numeric and Symbolic Arguments
Compute the inverse hyperbolic cosecant function for these numbers. Because these numbers are not
symbolic objects, acsch returns floating-point results.
A =
0.0000 + 0.5236i Inf + 0.0000i 0.0000 - 1.0472i...
1.4436 + 0.0000i 0.0000 - 1.5708i 0.3275 + 0.0000i
Compute the inverse hyperbolic cosecant function for the numbers converted to symbolic objects. For
many symbolic (exact) numbers, acsch returns unresolved symbolic calls.
symA =
[ (pi*1i)/6, Inf, -(pi*1i)/3, asinh(2), -(pi*1i)/2, asinh(1/3)]
vpa(symA)
ans =
[ 0.52359877559829887307710723054658i,...
Inf,...
-1.0471975511965977461542144610932i,...
1.4436354751788103424932767402731,...
-1.5707963267948966192313216916398i,...
0.32745015023725844332253525998826]
Plot the inverse hyperbolic cosecant function on the interval from -10 to 10.
7-20
acsch
syms x
fplot(acsch(x),[-10 10])
grid on
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing
acsch.
Find the first and second derivatives of the inverse hyperbolic cosecant function:
syms x
diff(acsch(x), x)
diff(acsch(x), x, x)
ans =
-1/(x^2*(1/x^2 + 1)^(1/2))
ans =
2/(x^3*(1/x^2 + 1)^(1/2)) - 1/(x^5*(1/x^2 + 1)^(3/2))
int(acsch(x), x)
ans =
x*asinh(1/x) + asinh(x)*sign(x)
7-21
7 Functions
taylor(acsch(x), x, Inf)
ans =
1/x - 1/(6*x^3) + 3/(40*x^5)
Rewrite the inverse hyperbolic cosecant function in terms of the natural logarithm:
rewrite(acsch(x), 'log')
ans =
log((1/x^2 + 1)^(1/2) + 1/x)
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Version History
Introduced before R2006a
See Also
asinh | acosh | atanh | asech | acoth | sinh | cosh | tanh | csch | sech | coth
7-22
adjoint
adjoint
Classical adjoint (adjugate) of square matrix
Syntax
X = adjoint(A)
Description
X = adjoint(A) returns the “Classical Adjoint (Adjugate) Matrix” on page 7-24 X of A, such that
A*X = det(A)*eye(n) = X*A, where n is the number of rows in A.
Examples
A = magic(3);
X = adjoint(A)
X =
-53.0000 52.0000 -23.0000
22.0000 -8.0000 -38.0000
7.0000 -68.0000 37.0000
syms x y z
A = sym([x y z; 2 1 0; 1 0 2]);
X = adjoint(A)
X =
[ 2, -2*y, -z]
[ -4, 2*x - z, 2*z]
[ -1, y, x - 2*y]
ans =
3×3 logical array
1 1 1
1 1 1
1 1 1
7-23
7 Functions
Compute the inverse of this matrix by computing its classical adjoint and determinant.
syms a b c d
A = [a b; c d];
invA = adjoint(A)/det(A)
invA =
[ d/(a*d - b*c), -b/(a*d - b*c)]
[ -c/(a*d - b*c), a/(a*d - b*c)]
ans =
2×2 logical array
1 1
1 1
Input Arguments
A — Square matrix
matrix of symbolic scalar variables | symbolic matrix variable | symbolic function | symbolic matrix
function | symbolic expression
Square matrix, specified as a matrix of symbolic scalar variables, symbolic matrix variable, symbolic
function, symbolic matrix function, or symbolic expression.
More About
Classical Adjoint (Adjugate) Matrix
The classical adjoint, or adjugate, of a square matrix A is the square matrix X, such that the (i,j)-th
entry of X is the (j,i)-th cofactor of A.
Aij is the submatrix of A obtained from A by removing the i-th row and j-th column.
The classical adjoint matrix should not be confused with the adjoint matrix. The adjoint is the
conjugate transpose of a matrix while the classical adjoint is another name for the adjugate matrix or
cofactor transpose of a matrix.
Version History
Introduced in R2013a
7-24
adjoint
See Also
ctranspose | det | inv | rank
7-25
7 Functions
airy
Airy function
Syntax
airy(x)
airy(0,x)
airy(1,x)
airy(2,x)
airy(3,x)
airy(n,x)
Description
airy(x) returns the Airy function on page 7-31 of the first kind, Ai(x), for each element of x.
airy(2,x) returns the Airy function on page 7-31 of the second kind, Bi(x).
airy(n,x) uses the values in vector n to return the corresponding Airy functions of elements of
vector x. Both n and x must have the same size.
airy( ___ ,1) returns the “Scaled Airy Functions” on page 7-31 following the syntax for the
MATLAB airy function.
Examples
Find the Airy Function of the First Kind
Find the Airy function of the first kind, Ai(x), for numeric or symbolic inputs using airy. Approximate
exact symbolic outputs using vpa.
Find the Airy function of the first kind, Ai(x), at 1.5. Because the input is double and not symbolic,
you get a double result.
airy(1.5)
ans =
0.0717
Find the Airy function of the values of vector v symbolically, by converting v to symbolic form using
sym. Because the input is symbolic, airy returns exact symbolic results. The exact symbolic results
for most symbolic inputs are unresolved function calls.
7-26
airy
vAiry =
[ airy(0, -1), 3^(1/3)/(3*gamma(2/3)), airy(0, 251/10), airy(0, 1 + 1i)]
vpa(vAiry)
ans =
[ 0.53556088329235211879951656563887, 0.35502805388781723926006318600418,...
4.9152763177499054787371976959487e-38,...
0.060458308371838149196532978116646 - 0.15188956587718140235494791259223i]
Find the Airy function, Ai(x), of the symbolic input x^2. For symbolic expressions, airy returns an
unresolved call.
syms x
airy(x^2)
ans =
airy(0, x^2)
Find the Airy function of the second kind, Bi(x), of the symbolic input [-3 4 1+1i x^2] by
specifying the first argument as 2. Because the input is symbolic, airy returns exact symbolic
results. The exact symbolic results for most symbolic inputs are unresolved function calls.
vAiry =
[ airy(2, -3), airy(2, 4), airy(2, 1 + 1i), airy(2, x^2)]
Use the syntax airy(2,x) like airy(x), as described in the example “Find the Airy Function of the
First Kind” on page 7-26.
Plot the Airy Functions, Ai(x) and Bi(x), over the interval [-10 2] using fplot.
syms x
fplot(airy(x), [-10 2])
hold on
fplot(airy(2,x), [-10 2])
legend('Ai(x)','Bi(x)','Location','Best')
title('Airy functions Ai(x) and Bi(x)')
grid on
hold off
7-27
7 Functions
syms y
z = x + 1i*y;
fsurf(abs(airy(z)),[-3 3 -3 3])
title('|Ai(z)|')
7-28
airy
Find the derivative of the Airy function of the first kind, Ai′(x), at 0 by specifying the first argument of
airy as 1. Then, numerically approximate the derivative using vpa.
dAi =
-(3^(1/6)*gamma(2/3))/(2*pi)
dAi_vpa =
-0.2588194037928067984051835601892
Find the derivative of the Airy function of the second kind, Bi′(x), at x by specifying the first argument
as 3. Then, find the derivative at x = 5 by substituting for x using subs and calling vpa.
syms x
dBi = airy(3, x)
dBi_vpa = vpa(subs(dBi, x, 5))
dBi =
airy(3, x)
dBi_vpa =
1435.8190802179825186717212380046
7-29
7 Functions
Show that the Airy functions Ai(x) and Bi(x) are the solutions of the differential equation
∂2 y
− xy = 0.
∂x2
syms y(x)
dsolve(diff(y, 2) - x*y == 0)
ans =
C1*airy(0, x) + C2*airy(2, x)
syms x y
diff(airy(x^2))
diff(diff(airy(3, x^2 + x*y -y^2), x), y)
ans =
2*x*airy(1, x^2)
ans =
airy(2, x^2 + x*y - y^2)*(x^2 + x*y - y^2) +...
airy(2, x^2 + x*y - y^2)*(x - 2*y)*(2*x + y) +...
airy(3, x^2 + x*y - y^2)*(x - 2*y)*(2*x + y)*(x^2 + x*y - y^2)
Find the Taylor series expansion of the Airy functions, Ai(x) and Bi(x), using taylor.
aiTaylor = taylor(airy(x))
biTaylor = taylor(airy(2, x))
aiTaylor =
- (3^(1/6)*gamma(2/3)*x^4)/(24*pi) + (3^(1/3)*x^3)/(18*gamma(2/3))...
- (3^(1/6)*gamma(2/3)*x)/(2*pi) + 3^(1/3)/(3*gamma(2/3))
biTaylor =
(3^(2/3)*gamma(2/3)*x^4)/(24*pi) + (3^(5/6)*x^3)/(18*gamma(2/3))...
+ (3^(2/3)*gamma(2/3)*x)/(2*pi) + 3^(5/6)/(3*gamma(2/3))
Find the Fourier transform of the Airy function Ai(x) using fourier.
syms x
aiFourier = fourier(airy(x))
aiFourier =
exp((w^3*1i)/3)
7-30
airy
syms x
vpasolve(airy(x) == 0, x)
ans =
-226.99630507523600716771890962744
ans =
-4.0879494441309706166369887014574
Input Arguments
x — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
Type of Airy function, specified as a number, vector, matrix, or multidimensional array, or a symbolic
number, variable, vector, matrix, or multidimensional array. The values of the input must be 0, 1, 2, or
3, which specify the Airy function as follows.
n Returns
0 (default) Airy function, Ai(x), which is the same as airy(x).
1 Derivative of Airy function, Ai’(x).
2 Airy function of the second kind, Bi(x).
3 Derivative of Airy function of the second kind, Bi’(x).
More About
Airy Functions
The Airy functions Ai(x) and Bi(x) are the two linearly independent solutions of the differential
equation
∂2 y
− xy = 0.
∂x2
Ai(x) is called the Airy function of the first kind. Bi(x) is called the Airy function of the second kind.
7-31
7 Functions
Tips
• When you call airy for inputs that are not symbolic objects, you call the MATLAB airy function.
• When you call airy(n, x), at least one argument must be a scalar or both arguments must be
vectors or matrices of the same size. If one argument is a scalar and the other is a vector or
matrix, airy(n,x) expands the scalar into a vector or matrix of the same size as the other
argument with all elements equal to the scalar.
• airy returns special exact values at 0.
Version History
Introduced in R2012a
See Also
besseli | besselj | besselk | bessely
7-32
all
all
Test whether all equations and inequalities represented as elements of symbolic array are valid
Syntax
all(A)
all(A,dim)
Description
all(A) tests whether all elements of A return logical 1 (true). If A is a matrix, all tests all elements
of each column. If A is a multidimensional array, all tests all elements along one dimension.
Examples
Test All Elements of Symbolic Vector
Create vector V that contains the symbolic equation and inequalities as its elements:
syms x
V = [x ~= x + 1, abs(x) >= 0, x == x];
Use all to test whether all of them are valid for all values of x:
all(V)
ans =
logical
1
M =
[ x == x, x == abs(x)]
[ 0 <= abs(x), x ~= 2*x]
Use all to test equations and inequalities of this matrix. By default, all tests whether all elements
of each column are valid for all possible values of variables. If all equations and inequalities in the
column are valid (return logical 1), then all returns logical 1 for that column. Otherwise, it returns
logical 0 for the column. Thus, it returns 1 for the first column and 0 for the second column:
all(M)
ans =
1×2 logical array
1 0
7-33
7 Functions
syms x
M = [x == x, x == abs(x); abs(x) >= 0, x ~= 2*x]
M =
[ x == x, x == abs(x)]
[ 0 <= abs(x), x ~= 2*x]
For matrices and multidimensional arrays, all can test all elements along the specified dimension. To
specify the dimension, use the second argument of all. For example, to test all elements of each
column of a matrix, use the value 1 as the second argument:
all(M, 1)
ans =
1×2 logical array
1 0
To test all elements of each row, use the value 2 as the second argument:
all(M, 2)
ans =
2×1 logical array
0
1
Test whether all elements of this vector return logical 1s. Note that all also converts all numeric
values outside equations and inequalities to logical 1s and 0s. The numeric value 0 becomes logical 0:
syms x
all([0, x == x])
ans =
logical
0
All nonzero numeric values, including negative and complex values, become logical 1s:
ans =
logical
1
Input Arguments
A — Input
symbolic array
Input, specified as a symbolic array. For example, it can be an array of symbolic equations,
inequalities, or logical expressions with symbolic subexpressions.
7-34
all
dim — Dimension
first non-singleton dimension (default) | integer
Dimension, specified as an integer. For example, if A is a matrix, any(A,1) tests elements of each
column and returns a row vector of logical 1s and 0s. any(A,2) tests elements of each row and
returns a column vector of logical 1s and 0s.
Tips
• If A is an empty symbolic array, all(A) returns logical 1.
• If some elements of A are just numeric values (not equations or inequalities), all converts these
values as follows. All numeric values except 0 become logical 1. The value 0 becomes logical 0.
• If A is a vector and all its elements return logical 1, all(A) returns logical 1. If one or more
elements are zero, all(A) returns logical 0.
• If A is a multidimensional array, all(A) treats the values along the first dimension that is not
equal to 1 (nonsingleton dimension) as vectors, returning logical 1 or 0 for each vector.
Version History
Introduced in R2012a
See Also
and | any | isAlways | not | or | xor
7-35
7 Functions
and
Logical AND for symbolic expressions
Syntax
A & B
and(A,B)
Description
A & B represents the logical AND. A & B is true only when both A and B are true.
Examples
syms x y
cond = x>=0 & y>=0;
assume(cond)
assumptions
ans =
[ 0 <= x, 0 <= y]
Define a range for a variable by combining two inequalities into a logical condition using &.
syms x
range = 0 < x & x < 1;
Return the condition at 1/2 and 10 by substituting for x using subs. The subs function does not
evaluate the conditions automatically.
x1 = subs(range,x,1/2)
x2 = subs(range,x,10)
x1 =
0 < 1/2 & 1/2 < 1
7-36
and
x2 =
0 < 10 & 10 < 1
isAlways(x1)
isAlways(x2)
ans =
logical
1
ans =
logical
0
Input Arguments
A, B — Operands
symbolic equations | symbolic inequalities | symbolic expressions | symbolic arrays
Operands, specified as symbolic equations, inequalities, expressions, or arrays. Inputs A and B must
either be the same size or have sizes that are compatible (for example, A is an M-by-N matrix and B is
a scalar or 1-by-N row vector). For more information, see “Compatible Array Sizes for Basic
Operations”.
Tips
• If you call simplify for a logical expression containing symbolic subexpressions, you can get the
symbolic constants symtrue and symfalse. These two constants are not the same as logical 1
(true) and logical 0 (false). To convert symbolic symtrue and symfalse to logical values, use
logical.
Version History
Introduced in R2012a
Starting in R2016b with the addition of implicit expansion, some combinations of arguments for basic
operations that previously returned errors now produce results. For example, you previously could
not add a row and a column vector, but those operands are now valid for addition. In other words, an
expression like [1 2] + [1; 2] previously returned a size mismatch error, but now it executes.
If your code uses element-wise operators and relies on the errors that MATLAB previously returned
for mismatched sizes, particularly within a try/catch block, then your code might no longer catch
those errors.
For more information on the required input sizes for basic array operations, see “Compatible Array
Sizes for Basic Operations”.
7-37
7 Functions
See Also
all | any | isAlways | not | or | piecewise | xor
7-38
angle
angle
Symbolic polar angle
Syntax
angle(Z)
Description
angle(Z) computes the polar angle of the complex value Z.
Examples
Compute Polar Angle of Numeric Inputs
Compute the polar angles of these complex numbers. Because these numbers are not symbolic
objects, you get floating-point results.
ans =
0.7854 0.6658 0.7854
Compute the polar angles of these complex numbers which are converted to symbolic objects:
ans =
[ pi/4, atan(pi/4), pi/4]
syms x
limit(angle(x + x^2*i/(1 + x)), x, -Inf)
limit(angle(x + x^2*i/(1 + x)), x, Inf)
ans =
-(3*pi)/4
ans =
pi/4
7-39
7 Functions
ans =
[ pi/3, pi/6]
[ pi/4, pi/2]
Input Arguments
Z — Input
number | vector | matrix | array | symbolic number | symbolic array | symbolic function | symbolic
expression
Input, specified as a number, vector, matrix, array, or a symbolic number, variable, expression,
function.
Tips
• Calling angle for numbers (or vectors or matrices of numbers) that are not symbolic objects
invokes the MATLAB angle function.
• If Z = 0, then angle(Z) returns 0.
Alternatives
For real X and Y such that Z = X + Y*i, the call angle(Z) is equivalent to atan2(Y,X).
Version History
Introduced in R2013a
See Also
atan2 | conj | imag | real | sign | signIm
7-40
animationToFrame
animationToFrame
Return structure of frames from animation objects
Syntax
frames = animationToFrame
frames = animationToFrame(fig)
frames = animationToFrame( ___ ,Name,Value)
Description
frames = animationToFrame returns a structure array of frames from animation objects. The
animation objects must be created using the fanimator function.
Examples
Create an animation of a moving circle, and return specific frames of the animation.
First, create two symbolic variables, t and x. The variable t defines the time parameter of the
animation. Use t to set the center of the circle at (t,1) and x to parameterize the perimeter of the
circle within the range [-pi pi]. Create the circle animation object using fanimator. Set the x-
axis and y-axis to be equal length.
syms t x
fanimator(@fplot,cos(x)+t,sin(x)+1,[-pi pi])
axis equal
By default, fanimator generates an animation object with 10 frames per unit time within the range
of t from 0 to 10. The default animation object contains a total of 101 frames. Use the command
playAnimation to play the animation.
Next, return a structure array of frames from the animation object by using animationToFrame.
frames = animationToFrame
7-41
7 Functions
The structure frames contains two fields. The cdata field stores the image data as an array of
uint8 values.
Reconstruct the animation frames by using the imshow function. For example, display the 50th frame
and the last frame of the animation.
imshow(frames(50).cdata)
7-42
animationToFrame
imshow(frames(101).cdata)
7-43
7 Functions
Create a moving circle animation object and a timer animation object. Return the generated
animation frames in reverse order.
First, create two symbolic variables, t and x. The variable t defines the time parameter of the
animation. Create a figure window for the animation.
syms t x
fig1 = figure;
Create a circle animation object using fanimator. Use t to set the center of the circle at (t,1) and
x to parameterize the perimeter of the circle within the range [-pi pi]. Set the x-axis and y-axis to
be equal length.
fanimator(@fplot,cos(x)+t,sin(x)+1,[-pi pi])
axis equal
Next, use the text function to add a piece of text to count the elapsed time. Use num2str to convert
the time parameter to a string.
7-44
animationToFrame
hold on
fanimator(@(t) text(8,3,"Timer: "+num2str(t,2)))
hold off
By default, fanimator creates stop-motion frames with 10 frames per unit time within the range of t
from 0 to 10. The default animation object contains a total of 101 frames. Use the command
playAnimation to play the animation.
Next, return a structure array of frames from the animation in figure fig by using
animationToFrame. Return the animation frames in reverse order by setting the 'Backwards'
option to true. Set the frame rate per unit time to 2 to return a total of 21 frames.
frames = animationToFrame(fig1,'Backwards',true,'FrameRate',2)
The structure frames contains two fields. The cdata field stores the image data as an array of
uint8 values.
Reconstruct the animation frames by using the imshow function. For example, display the first frame
and the 11th frame of the animation in a new figure window.
fig2 = figure;
imshow(frames(1).cdata)
7-45
7 Functions
imshow(frames(11).cdata)
7-46
animationToFrame
Input Arguments
fig — Target figure
Figure object
Target figure, specified as a Figure object. For more information about Figure objects, see figure.
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: 'Backwards',true,'AnimationRange',[-2 5]
Range of the animation time parameter, specified as a two-element row vector. The two elements
must be real values that are increasing.
7-47
7 Functions
Frame rate, specified as a positive value. The frame rate defines the number of frames per unit time
when you returning animation frames as a structure array.
Example: 20
Backward option, specified as a logical value (boolean). If you specify true, then the function returns
the animation frames backwards or in reverse order.
Example: true
Output Arguments
frames — Animation frames
structure array
• cdata — The image data stored as an array of uint8 values. The size of the image data array
depends on your screen resolution.
• colormap — The colormap. On true color systems, this field is empty.
The animationToFrame function returns a structure of animation frames in the same format as the
output returned by the getframe function.
Version History
Introduced in R2019a
See Also
playAnimation | fanimator | writeAnimation | rewindAnimation | getframe
7-48
Animator Properties
Animator Properties
Animator appearance and behavior
Note UIContextMenu property is not recommended. Use ContextMenu instead. For more
information, see “Compatibility Considerations”.
Description
Animator properties control the appearance and behavior of an Animator object. By changing
property values, you can modify certain aspects of the Animator object. You can use dot notation to
refer to a particular object and property:
fp = fanimator(@(x) plot(x,sin(x),'bo'))
ls = fp.Visible
fp.Visible = 'off'
Properties
Frames
Range of the animation time parameter, specified as a two-element row vector. The two elements
must be real values that are increasing.
Frame rate, specified as a positive value. The frame rate defines the number of frames per unit time
interval of an animation object.
Interactivity
State of visibility, specified as 'on' or 'off', or as numeric or logical 1 (true) or 0 (false). A value
of 'on' is equivalent to true, and 'off' is equivalent to false. Thus, you can use the value of this
property as a logical value. The value is stored as an on/off logical value of type
matlab.lang.OnOffSwitchState.
7-49
7 Functions
Context menu, specified as a ContextMenu object. Use this property to display a context menu when
you right-click the object. Create the context menu using the uicontextmenu function.
Callbacks
• Function handle.
• Cell array containing a function handle and additional arguments.
• Character vector that is a valid MATLAB command or function, which is evaluated in the base
workspace (not recommended).
Use this property to execute code when you click the object. If you specify this property using a
function handle, then MATLAB passes two arguments to the callback function when executing the
callback:
• Clicked object — Access properties of the clicked object from within the callback function.
• Event data — Empty argument. Replace it with the tilde character (~) in the function definition to
indicate that this argument is not used.
For more information on how to use function handles to define callback functions, see “Create
Callbacks for Graphics Objects”.
• Function handle.
• Cell array in which the first element is a function handle. Subsequent elements in the cell array
are the arguments to pass to the callback function.
• Character vector containing a valid MATLAB expression (not recommended). MATLAB evaluates
this expression in the base workspace.
For more information about specifying a callback as a function handle, cell array, or character vector,
see “Create Callbacks for Graphics Objects”.
This property specifies a callback function to execute when MATLAB creates the object. MATLAB
initializes all property values before executing the CreateFcn callback. If you do not specify the
CreateFcn property, then MATLAB executes a default creation function.
If you specify this property as a function handle or cell array, you can access the object that is being
created using the first argument of the callback function. Otherwise, use the gcbo function to access
the object.
7-50
Animator Properties
• Function handle.
• Cell array in which the first element is a function handle. Subsequent elements in the cell array
are the arguments to pass to the callback function.
• Character vector containing a valid MATLAB expression (not recommended). MATLAB evaluates
this expression in the base workspace.
For more information about specifying a callback as a function handle, cell array, or character vector,
see “Create Callbacks for Graphics Objects”.
This property specifies a callback function to execute when MATLAB deletes the object. MATLAB
executes the DeleteFcn callback before destroying the properties of the object. If you do not specify
the DeleteFcn property, then MATLAB executes a default deletion function.
If you specify this property as a function handle or cell array, you can access the object that is being
deleted using the first argument of the callback function. Otherwise, use the gcbo function to access
the object.
This property determines if a running callback can be interrupted. There are two callback states to
consider:
MATLAB determines callback interruption behavior whenever it executes a command that processes
the callback queue. These commands include drawnow, figure, uifigure, getframe, waitfor,
and pause.
If the running callback does not contain one of these commands, then no interruption occurs.
MATLAB first finishes executing the running callback, and later executes the interrupting callback.
If the running callback does contain one of these commands, then the Interruptible property of
the object that owns the running callback determines if the interruption occurs:
• If the value of Interruptible is 'off', then no interruption occurs. Instead, the BusyAction
property of the object that owns the interrupting callback determines if the interrupting callback
is discarded or added to the callback queue.
• If the value of Interruptible is 'on', then the interruption occurs. The next time MATLAB
processes the callback queue, it stops the execution of the running callback and executes the
7-51
7 Functions
interrupting callback. After the interrupting callback completes, MATLAB then resumes executing
the running callback.
Note When an interruption occurs, MATLAB does not save the state of properties or the display. For
example, the object returned by the gca or gcf command might change when another callback
executes.
Callback queuing, specified as 'queue' or 'cancel'. The BusyAction property determines how
MATLAB handles the execution of interrupting callbacks. There are two callback states to consider:
The BusyAction property determines callback queuing behavior only when both of these conditions
are met:
• The running callback contains a command that processes the callback queue, such as drawnow,
figure, uifigure, getframe, waitfor, or pause.
• The value of the Interruptible property of the object that owns the running callback is 'off'.
Under these conditions, the BusyAction property of the object that owns the interrupting callback
determines how MATLAB handles the interrupting callback. These are possible values of the
BusyAction property:
• 'queue' — Puts the interrupting callback in a queue to be processed after the running callback
finishes execution.
• 'cancel' — Does not execute the interrupting callback.
MATLAB sets the BeingDeleted property to 'on' when the DeleteFcn callback begins execution.
The BeingDeleted property remains set to 'on' until the component object no longer exists.
7-52
Animator Properties
Check the value of the BeingDeleted property to verify that the object is not about to be deleted
before querying or modifying it.
Parent/Child
Parent — Parent
Axes object
Children — Children
graphics object
Children, returned as a graphics object. Use this property to view the property values of the graphics
object.
You cannot add or remove children using the Children property. You can only set Children to a
permutation of itself.
Visibility of the object handle in the Children property of the parent, specified as one of these
values:
If the object is not listed in the Children property of the parent, then functions that obtain object
handles by searching the object hierarchy or querying handle properties cannot return it. Examples
of such functions include the get, findobj, gca, gcf, gco, newplot, cla, clf, and close
functions.
Hidden object handles are still valid. Set the root ShowHiddenHandles property to 'on' to list all
object handles regardless of their HandleVisibility property setting.
Identifier
Type of graphics object, returned as 'animator'. Use this property to find all objects of a given type
within a plotting hierarchy. For example, you can use the findobj function to find graphics objects of
type 'animator'.
7-53
7 Functions
Object identifier, specified as a character vector or string scalar. You can specify a unique Tag value
to serve as an identifier for an object. When you need access to the object elsewhere in your code,
you can use the findobj function to search for the object based on the Tag value.
User data, specified as any MATLAB array. For example, you can specify a scalar, vector, matrix, cell
array, character array, table, or structure. Use this property to store arbitrary data on an object.
If you are working in App Designer, create public or private properties in the app to share data
instead of using the UserData property. For more information, see “Share Data Within App Designer
Apps”.
Version History
Introduced in R2019a
Starting in R2020a, using the UIContextMenu property to assign a context menu to a graphics
object or UI component is not recommended. Use the ContextMenu property instead. The property
values are the same.
There are no plans to remove support for the UIContextMenu property at this time. However, the
UIContextMenu property no longer appears in the list returned by calling the get function on a
graphics object or UI component.
7-54
any
any
Test whether at least one of equations and inequalities represented as elements of symbolic array is
valid
Syntax
any(A)
any(A,dim)
Description
any(A) tests whether at least one element of A returns logical 1 (true). If A is a matrix, any tests
elements of each column. If A is a multidimensional array, any tests elements along one dimension.
Examples
Test Vector of Symbolic Conditions
Create vector V that contains the symbolic equation and inequalities as its elements:
syms x real
V = [x ~= x + 1, abs(x) >= 0, x == x];
Use any to test whether at least one of them is valid for all values of x:
any(V)
ans =
logical
1
syms x real
M = [x == 2*x, x == abs(x); abs(x) >= 0, x == 2*x]
M =
[ x == 2*x, x == abs(x)]
[ 0 <= abs(x), x == 2*x]
Use any to test equations and inequalities of this matrix. By default, any tests whether any element
of each column is valid for all possible values of variables. If at least one equation or inequality in the
column is valid (returns logical 1), then any returns logical 1 for that column. Otherwise, it returns
logical 0 for the column. Thus, it returns 1 for the first column and 0 for the second column:
any(M)
7-55
7 Functions
ans =
1×2 logical array
1 0
syms x real
M = [x == 2*x, x == abs(x); abs(x) >= 0, x == 2*x]
M =
[ x == 2*x, x == abs(x)]
[ 0 <= abs(x), x == 2*x]
For matrices and multidimensional arrays, any can test elements along the specified dimension. To
specify the dimension, use the second argument of any. For example, to test elements of each column
of a matrix, use the value 1 as the second argument:
any(M, 1)
ans =
1×2 logical array
1 0
To test elements of each row, use the value 2 as the second argument:
any(M, 2)
ans =
2×1 logical array
0
1
Test whether any element of this vector returns logical 1. Note that any also converts all numeric
values outside equations and inequalities to logical 1s and 0s. The numeric value 0 becomes logical 0:
syms x
any([0, x == x + 1])
ans =
logical
0
All nonzero numeric values, including negative and complex values, become logical 1s:
any([-4 + i, x == x + 1])
ans =
logical
1
Input Arguments
A — Input
symbolic array
7-56
any
Input, specified as a symbolic array. For example, it can be an array of symbolic equations,
inequalities, or logical expressions with symbolic subexpressions.
dim — Dimension
first non-singleton dimension (default) | integer
Dimension, specified as an integer. For example, if A is a matrix, any(A,1) tests elements of each
column and returns a row vector of logical 1s and 0s. any(A,2) tests elements of each row and
returns a column vector of logical 1s and 0s.
Tips
• If A is an empty symbolic array, any(A) returns logical 0.
• If some elements of A are just numeric values (not equations or inequalities), any converts these
values as follows. All nonzero numeric values become logical 1. The value 0 becomes logical 0.
• If A is a vector and any of its elements returns logical 1, any(A) returns logical 1. If all elements
are zero, any(A) returns logical 0.
• If A is a multidimensional array, any(A) treats the values along the first dimension that is not
equal to 1 (non-singleton dimension) as vectors, returning logical 1 or 0 for each vector.
Version History
Introduced in R2012a
See Also
all | and | isAlways | not | or | xor
7-57
7 Functions
argnames
Input variables of symbolic function or matrix function
Syntax
args = argnames(f)
Description
args = argnames(f) returns the input variables of the symbolic function or matrix function f.
Examples
syms f(x,y)
f(x,y) = x + y;
args = argnames(f)
args = x y
syms f(a,b,x,y)
f(x,b,y,a) = a*x + b*y;
Find the input variables of f. When returning variables, argnames uses the same order as you used
when you defined the function.
args = argnames(f)
args = x b y a
syms A B 2 matrix
syms f(A,B) 2 matrix keepargs
f(A,B) = A*B - 3*A + 2*eye(2);
Find the input variables of f by using argnames. The result is a cell array containing symbolic matrix
variables.
7-58
argnames
args = argnames(f)
arg1 = args{1}
arg1 = A
arg2 = args{2}
arg2 = B
Input Arguments
f — Input function
symbolic function | symbolic matrix function
Output Arguments
args — Input variables of symbolic function or matrix function
symbolic variable | vector of symbolic variables | cell array of symbolic matrix variables
Version History
Introduced in R2012a
The argnames function accepts an input argument of type symfunmatrix. For an example, see
“Find Input Variables of Symbolic Matrix Function” on page 7-58.
See Also
formula | syms | symvar | symfun | symfunmatrix
7-59
7 Functions
asec
Symbolic inverse secant function
Syntax
asec(X)
Description
asec(X) returns the inverse secant function (arcsecant function) of X. All angles are in radians.
• For real elements of X in the interval [-Inf,-1] and [1,Inf], asec returns values in the
interval [0,pi].
• For real values of X in the interval [-1,1] and for complex values of X, asec returns complex
values with the real parts in the interval [0,pi].
Examples
Inverse Secant Function for Numeric and Symbolic Arguments
Compute the inverse secant function for these numbers. Because these numbers are not symbolic
objects, asec returns floating-point results.
A = asec([-2, 0, 2/sqrt(3), 1/2, 1, 5])
A =
2.0944 + 0.0000i 0.0000 + Infi 0.5236 + 0.0000i...
0.0000 + 1.3170i 0.0000 + 0.0000i 1.3694 + 0.0000i
Compute the inverse secant function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, asec returns unresolved symbolic calls.
symA = asec(sym([-2, 0, 2/sqrt(3), 1/2, 1, 5]))
symA =
[ (2*pi)/3, Inf, pi/6, acos(2), 0, acos(1/5)]
ans =
[ 2.0943951023931954923084289221863,...
Inf,...
0.52359877559829887307710723054658,...
1.3169578969248165734029498707969i,...
0,...
1.3694384060045659001758622252964]
7-60
asec
Plot the inverse secant function on the interval from -10 to 10.
syms x
fplot(asec(x),[-10 10])
grid on
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing asec.
Find the first and second derivatives of the inverse secant function:
syms x
diff(asec(x), x)
diff(asec(x), x, x)
ans =
1/(x^2*(1 - 1/x^2)^(1/2))
ans =
- 2/(x^3*(1 - 1/x^2)^(1/2)) - 1/(x^5*(1 - 1/x^2)^(3/2))
ans =
x*acos(1/x) - log(x + (x^2 - 1)^(1/2))*sign(x)
7-61
7 Functions
taylor(asec(x), x, Inf)
ans =
pi/2 - 1/x - 1/(6*x^3) - 3/(40*x^5)
rewrite(asec(x), 'log')
ans =
-log(1/x + (1 - 1/x^2)^(1/2)*1i)*1i
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Version History
Introduced before R2006a
See Also
acos | asin | atan | acsc | acot | sin | cos | tan | csc | sec | cot
7-62
asech
asech
Symbolic inverse hyperbolic secant function
Syntax
asech(X)
Description
asech(X) returns the inverse hyperbolic secant function of X.
Examples
Inverse Hyperbolic Secant Function for Numeric and Symbolic Arguments
Compute the inverse hyperbolic secant function for these numbers. Because these numbers are not
symbolic objects, asech returns floating-point results.
A =
0.0000 + 2.0944i Inf + 0.0000i 0.0000 + 0.5236i...
1.3170 + 0.0000i 0.0000 + 0.0000i 0.0000 + 1.2310i
Compute the inverse hyperbolic secant function for the numbers converted to symbolic objects. For
many symbolic (exact) numbers, asech returns unresolved symbolic calls.
symA =
[ (pi*2i)/3, Inf, (pi*1i)/6, acosh(2), 0, acosh(1/3)]
vpa(symA)
ans =
[ 2.0943951023931954923084289221863i,...
Inf,...
0.52359877559829887307710723054658i,...
1.316957896924816708625046347308,...
0,...
1.230959417340774682134929178248i]
7-63
7 Functions
syms x
fplot(asech(x),[0 1])
grid on
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing
asech.
Find the first and second derivatives of the inverse hyperbolic secant function. Simplify the second
derivative by using simplify.
syms x
diff(asech(x), x)
simplify(diff(asech(x), x, x))
ans =
-1/(x^2*(1/x - 1)^(1/2)*(1/x + 1)^(1/2))
ans =
-(2*x^2 - 1)/(x^5*(1/x - 1)^(3/2)*(1/x + 1)^(3/2))
ans =
atan(1/((1/x - 1)^(1/2)*(1/x + 1)^(1/2))) + x*acosh(1/x)
7-64
asech
taylor(asech(x), x, Inf)
ans =
(pi*1i)/2 - 1i/x - 1i/(6*x^3) - 3i/(40*x^5)
Rewrite the inverse hyperbolic secant function in terms of the natural logarithm:
rewrite(asech(x), 'log')
ans =
log((1/x - 1)^(1/2)*(1/x + 1)^(1/2) + 1/x)
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Version History
Introduced before R2006a
See Also
asinh | acosh | atanh | acsch | acoth | sinh | cosh | tanh | csch | sech | coth
7-65
7 Functions
asin
Symbolic inverse sine function
Syntax
asin(X)
Description
asin(X) returns the inverse sine function (arcsine function) of X. All angles are in radians.
• For real values of X in the interval [-1,1], asin(X) returns the values in the interval [-pi/
2,pi/2].
• For real values of X outside the interval [-1,1] and for complex values of X, asin(X) returns
complex values with the real parts in the interval [-pi/2,pi/2].
Examples
Inverse Sine Function for Numeric and Symbolic Arguments
Compute the inverse sine function for these numbers. Because these numbers are not symbolic
objects, asin returns floating-point results.
A = asin([-1, -1/3, -1/2, 1/4, 1/2, sqrt(3)/2, 1])
A =
-1.5708 -0.3398 -0.5236 0.2527 0.5236 1.0472 1.5708
Compute the inverse sine function for the numbers converted to symbolic objects. For many symbolic
(exact) numbers, asin returns unresolved symbolic calls.
symA = asin(sym([-1, -1/3, -1/2, 1/4, 1/2, sqrt(3)/2, 1]))
symA =
[ -pi/2, -asin(1/3), -pi/6, asin(1/4), pi/6, pi/3, pi/2]
ans =
[ -1.5707963267948966192313216916398,...
-0.33983690945412193709639251339176,...
-0.52359877559829887307710723054658,...
0.25268025514207865348565743699371,...
0.52359877559829887307710723054658,...
1.0471975511965977461542144610932,...
1.5707963267948966192313216916398]
7-66
asin
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing asin.
Find the first and second derivatives of the inverse sine function:
syms x
diff(asin(x), x)
diff(asin(x), x, x)
ans =
1/(1 - x^2)^(1/2)
ans =
x/(1 - x^2)^(3/2)
ans =
x*asin(x) + (1 - x^2)^(1/2)
7-67
7 Functions
taylor(asin(x), x)
ans =
(3*x^5)/40 + x^3/6 + x
rewrite(asin(x), 'log')
ans =
-log((1 - x^2)^(1/2) + x*1i)*1i
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Version History
Introduced before R2006a
See Also
acos | atan | acsc | asec | acot | sin | cos | tan | csc | sec | cot
7-68
asinh
asinh
Symbolic inverse hyperbolic sine function
Syntax
asinh(X)
Description
asinh(X) returns the inverse hyperbolic sine function of X.
Examples
Inverse Hyperbolic Sine Function for Numeric and Symbolic Arguments
Compute the inverse hyperbolic sine function for these numbers. Because these numbers are not
symbolic objects, asinh returns floating-point results.
A =
0.0000 - 1.5708i 0.0000 + 0.0000i 0.1659 + 0.0000i...
0.0000 + 0.5236i 0.0000 + 1.5708i 1.4436 + 0.0000i
Compute the inverse hyperbolic sine function for the numbers converted to symbolic objects. For
many symbolic (exact) numbers, asinh returns unresolved symbolic calls.
symA =
[ -(pi*1i)/2, 0, asinh(1/6), (pi*1i)/6, (pi*1i)/2, asinh(2)]
vpa(symA)
ans =
[ -1.5707963267948966192313216916398i,...
0,...
0.16590455026930117643502171631553,...
0.52359877559829887307710723054658i,...
1.5707963267948966192313216916398i,...
1.4436354751788103012444253181457]
Plot the inverse hyperbolic sine function on the interval from -10 to 10.
7-69
7 Functions
syms x
fplot(asinh(x),[-10 10])
grid on
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing
asinh.
Find the first and second derivatives of the inverse hyperbolic sine function:
syms x
diff(asinh(x), x)
diff(asinh(x), x, x)
ans =
1/(x^2 + 1)^(1/2)
ans =
-x/(x^2 + 1)^(3/2)
int(asinh(x), x)
ans =
x*asinh(x) - (x^2 + 1)^(1/2)
7-70
asinh
taylor(asinh(x), x)
ans =
(3*x^5)/40 - x^3/6 + x
Rewrite the inverse hyperbolic sine function in terms of the natural logarithm:
rewrite(asinh(x), 'log')
ans =
log(x + (x^2 + 1)^(1/2))
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Version History
Introduced before R2006a
See Also
acosh | atanh | acsch | asech | acoth | sinh | cosh | tanh | csch | sech | coth
7-71
7 Functions
assume
Set assumption on symbolic object
Syntax
assume(condition)
assume(expr,set)
assume(expr,"clear")
Description
assume(condition) sets mathematical assumptions or conditions on symbolic variables as defined
by condition. assume is not additive. Instead, it automatically deletes all previous assumptions on
the variables in condition.
assume(expr,set) states that expr belongs to set. assume deletes previous assumptions on the
variables in expr.
Examples
Common Assumptions
Assume x is even by assuming that x/2 is an integer. Assume x is odd by assuming that (x-1)/2 is
an integer.
7-72
assume
Assume x is even.
syms x
assume(x/2,"integer")
ans =
2
4
6
8
Assume x is odd. assume is not additive, but instead automatically deletes the previous assumption
in(x/2, "integer").
assume((x-1)/2,"integer")
solve(x>0,x<10,x)
ans =
1
3
5
7
9
Multiple Assumptions
Successive assume commands do not set multiple assumptions. Instead, each assume command
deletes previous assumptions and sets new assumptions. Set multiple assumptions by using
assumeAlso or the & operator.
Assume x > 5 and then x < 10 by using assume. Use assumptions to check that only the second
assumption exists because assume deleted the first assumption when setting the second.
syms x
assume(x > 5)
assume(x < 10)
assumptions
ans =
x < 10
Assume the first assumption in addition to the second by using assumeAlso. Check that both
assumptions exist.
assumeAlso(x > 5)
assumptions
ans =
[ 5 < x, x < 10]
7-73
7 Functions
assume(x,"clear")
Assume both conditions using the & operator. Check that both assumptions exist.
ans =
[ 5 < x, x < 10]
assume(x,"clear")
Assumptions on Integrand
Compute an indefinite integral with and without the assumption on the symbolic parameter a.
syms x a
assume(a ~= -1)
int(x^a,x)
ans =
x^(a + 1)/(a + 1)
Now, clear the assumption and compute the same integral. Without assumptions, int returns this
piecewise result.
assume(a,"clear")
int(x^a, x)
ans =
piecewise(a == -1, log(x), a ~= -1, x^(a + 1)/(a + 1))
ans =
-5
-1
-1/3
1/2
100
7-74
assume
ans =
-1
-1/3
1/2
Set several assumptions simultaneously by using the logical operators and, or, xor, not, or their
shortcuts. For example, all negative solutions less than -1 and all positive solutions greater than 1.
ans =
-5
100
assume(x,"clear")
Try to simplify the expression sin(2*pi*n) using simplify. The simplify function cannot
simplify the input and returns the input as it is.
syms n
simplify(sin(2*n*pi))
ans =
sin(2*pi*n)
assume(n,"integer")
simplify(sin(2*n*pi))
ans =
0
assume(n,"clear")
Assumptions on Expressions
You can set assumptions not only on variables, but also on expressions. For example, compute this
integral.
syms x
f = 1/abs(x^2 - 1);
int(f,x)
ans =
-atanh(x)/sign(x^2 - 1)
7-75
7 Functions
assume(x^2 - 1 > 0)
int(f,x)
ans =
-atanh(x)
Prove relations that hold under certain conditions by first assuming the conditions and then using
isAlways.
Prove that sin(pi*x) is never equal to 0 when x is not an integer. The isAlways function returns
logical 1 (true), which means the condition holds for all values of x under the set assumptions.
syms x
assume(~in(x,"integer"))
isAlways(sin(pi*x) ~= 0)
ans =
logical
1
Create the 2-by-2 symbolic matrix A with autogenerated elements. Specify set as rational.
A = sym("A",[2 2],"rational")
A =
[ A1_1, A1_2]
[ A2_1, A2_2]
ans =
[ in(A1_1, 'rational'), in(A1_2, 'rational'),...
in(A2_1, 'rational'), in(A2_2, 'rational')]
You can also use assume to set assumptions on all elements of a matrix. Now, assume all elements of
A have positive rational values. Set the assumptions as a cell array of character vectors
{'positive','rational'}.
assume(A,{'positive','rational'})
ans =
[ 0 < A1_1, 0 < A1_2, 0 < A2_1, 0 < A2_2,...
in(A1_1, 'rational'), in(A1_2, 'rational'),...
in(A2_1, 'rational'), in(A2_2, 'rational')]
7-76
assume
Input Arguments
condition — Assumption statement
symbolic expression | symbolic equation | symbolic relation | vector or matrix of symbolic expressions,
equations, or relations
Expression to set assumption on, specified as a symbolic variable, expression, vector, or matrix. If
expr is a vector or matrix, then assume(expr,set) sets an assumption that each element of expr
belongs to set.
Set of assumptions, specified as a character vector, string scalar, string array, or cell array. The
available assumptions are "integer", "rational", "real", or "positive".
You can combine multiple assumptions by specifying a string array or cell array of character vectors.
For example, assume a positive rational value by specifying set as ["positive" "rational"] or
{'positive','rational'}.
Tips
• assume removes any assumptions previously set on the symbolic variables. To retain previous
assumptions while adding an assumption, use assumeAlso.
• When you delete a symbolic variable from the MATLAB workspace using clear, all assumptions
that you set on that variable remain in the symbolic engine. If you later declare a new symbolic
variable with the same name, it inherits these assumptions.
• To clear all assumptions set on a symbolic variable var, use this command.
assume(var,"clear")
• To delete all objects in the MATLAB workspace and close the Symbolic Math Toolbox engine
associated with the MATLAB workspace clearing all assumptions, use this command:
clear all
• MATLAB projects complex numbers in inequalities to the real axis. If condition is an inequality,
then both sides of the inequality must represent real values. Inequalities with complex numbers
are invalid because the field of complex numbers is not an ordered field. (It is impossible to tell
whether 5 + i is greater or less than 2 + 3*i.) For example, x > i becomes x > 0, and x <=
3 + 2*i becomes x <= 3.
• The toolbox does not support assumptions on symbolic functions. Set assumptions on symbolic
variables and expressions instead.
7-77
7 Functions
• When you create a new symbolic variable using sym and syms, you also can set an assumption
that the variable is real, positive, integer, or rational.
a = sym("a","real");
b = sym("b","rational");
c = sym("c","positive");
d = sym("d","positive");
e = sym("e",{'positive','integer'});
Alternatively, you can use these commands, which are more efficient.
syms a real
syms b rational
syms c d positive
syms e positive integer
Version History
Introduced in R2012a
See Also
Functions
and | assumeAlso | assumptions | isAlways | in | not | or | piecewise | sym | syms
Topics
“Use Assumptions on Symbolic Variables” on page 1-41
7-78
assumeAlso
assumeAlso
Add assumption on symbolic object
Syntax
assumeAlso(condition)
assumeAlso(expr,set)
Description
assumeAlso(condition) states that condition is valid for all symbolic variables in condition.
It retains all assumptions previously set on these symbolic variables.
assumeAlso(expr,set) states that expr belongs to set, in addition to all previously made
assumptions.
Examples
Assumptions Specified as Relations
Set assumptions using assume. Then add more assumptions using assumeAlso.
The solver warns that both solutions hold only under certain conditions.
Add the assumption that x < 1. To add a new assumption without removing the previous one, use
assumeAlso.
assumeAlso(x < 1)
s =
(1 - x)^(1/2)*(x + 1)^(1/2)
7-79
7 Functions
assume([x y],'clear')
Set assumptions using syms. Then add more assumptions using assumeAlso.
syms n positive
Using assumeAlso, add more assumptions on the same variable n. For example, assume also that n
is an integer.
assumeAlso(n,'integer')
Return all assumptions affecting variable n using assumptions. In this case, n is a positive integer.
assumptions(n)
ans =
[ 0 < n, in(n, 'integer')]
assume(n,'clear')
Use the assumption on a matrix as a shortcut for setting the same assumption on each matrix
element.
Create the 3-by-3 symbolic matrix A with auto-generated elements. To assume every element of A is
rational, specify set as 'rational'.
A = sym('A',[3 3],'rational')
A =
[ A1_1, A1_2, A1_3]
[ A2_1, A2_2, A2_3]
[ A3_1, A3_2, A3_3]
assumeAlso(A > 1)
assumptions(A)
ans =
[ 1 < A1_1, 1 < A1_2, 1 < A1_3, 1 < A2_1, 1 < A2_2, 1 < A2_3,...
1 < A3_1, 1 < A3_2, 1 < A3_3,...
in(A1_1, 'rational'), in(A1_2, 'rational'), in(A1_3, 'rational'),...
in(A2_1, 'rational'), in(A2_2, 'rational'), in(A2_3, 'rational'),...
in(A3_1, 'rational'), in(A3_2, 'rational'), in(A3_3, 'rational')]
7-80
assumeAlso
assume(A,'clear')
Contradicting Assumptions
When you add assumptions, ensure that the new assumptions do not contradict the previous
assumptions. Contradicting assumptions can lead to inconsistent and unpredictable results. In some
cases, assumeAlso detects conflicting assumptions and issues an error.
assumeAlso does not guarantee to detect contradicting assumptions. For example, assume that y is
nonzero, and both y and y*i are real values.
syms y
assume(y ~= 0)
assumeAlso(y,'real')
assumeAlso(y*i,'real')
ans =
[ in(y, 'real'), in(y*1i, 'real'), y ~= 0]
Input Arguments
condition — Assumption statement
symbolic expression | symbolic equation | relation | vector or matrix of symbolic expressions,
equations, or relations
Expression to set assumption on, specified as a symbolic variable, expression, or a vector or matrix of
symbolic variables or expressions. If expr is a vector or matrix, then assumeAlso(expr,set) sets
an assumption that each element of expr belongs to set.
7-81
7 Functions
Set of assumptions, specified as a character vector, string array, or cell array. The available
assumptions are 'integer', 'rational', 'real', or 'positive'.
You can combine multiple assumptions by specifying a string array or cell array of character vectors.
For example, assume a positive rational value by specifying set as ["positive" "rational"] or
{'positive','rational'}.
Tips
• assumeAlso keeps all assumptions previously set on the symbolic variables. To replace previous
assumptions with the new one, use assume.
• When adding assumptions, always check that a new assumption does not contradict the existing
assumptions. To see existing assumptions, use assumptions. Symbolic Math Toolbox does not
guarantee to detect conflicting assumptions. Conflicting assumptions can lead to unpredictable
and inconsistent results.
• When you delete a symbolic variable from the MATLAB workspace using clear, all assumptions
that you set on that variable remain in the symbolic engine. If later you declare a new symbolic
variable with the same name, it inherits these assumptions.
• To clear all assumptions set on a symbolic variable var use this command.
assume(var,'clear')
• To clear all objects in the MATLAB workspace and close the Symbolic Math Toolbox engine
associated with the MATLAB workspace resetting all its assumptions, use this command.
clear all
• MATLAB projects complex numbers in inequalities to the real axis. If condition is an inequality,
then both sides of the inequality must represent real values. Inequalities with complex numbers
are invalid because the field of complex numbers is not an ordered field. (It is impossible to tell
whether 5 + i is greater or less than 2 + 3*i.) For example, x > i becomes x > 0, and x <=
3 + 2*i becomes x <= 3.
• The toolbox does not support assumptions on symbolic functions. Make assumptions on symbolic
variables and expressions instead.
• Instead of adding assumptions one by one, you can set several assumptions in one function call. To
set several assumptions, use assume and combine these assumptions by using the logical
operators and, or, xor, not, all, any, or their shortcuts.
Version History
Introduced in R2012a
See Also
and | assume | assumptions | in | isAlways | not | or | piecewise | sym | syms
Topics
“Use Assumptions on Symbolic Variables” on page 1-41
7-82
assumptions
assumptions
Show assumptions affecting symbolic variable, expression, or function
Syntax
assumptions(var)
assumptions
Description
assumptions(var) returns all assumptions that affect variable var. If var is an expression or
function, assumptions returns all assumptions that affect all variables in var.
assumptions returns all assumptions that affect all variables in MATLAB Workspace.
Examples
Assumptions on Variables
In Symbolic Math Toolbox™, you can set mathematical assumptions or conditions when creating
symbolic variables. For example, create a symbolic variable n and assume that the variable is an
integer. Return the assumption using assumptions.
syms n integer
assumptions
ans = n ∈ ℤ
You can also use the assume function to set assumptions. For example, assume that n is less than x
and that x < 42. The assume function replaces old assumptions on input with the new assumptions.
Return all assumptions that affect n.
syms x
assume(n < x & x < 42)
assumptions(n)
assumptions returns the assumption x < 42 because it affects n through the assumption n < x.
Thus, assumptions returns the transitive closure of assumptions, which is all assumptions that
mathematically affect the input.
Set the assumption on variable m that 1 < m < 3. Return all assumptions on m and x using
assumptions.
syms m
assume(1 < m < 3)
assumptions([m x])
7-83
7 Functions
To see the assumptions that affect all variables, use assumptions without any arguments.
assumptions
assume([m n x],"clear")
You cannot set an additional assumption on a variable using assume because assume clears all
previous assumptions on that variable. To set an additional assumption on a variable, using
assumeAlso.
Set an assumption on x using assume. Set an additional assumption on x use assumeAlso. Use
assumptions to return the multiple assumptions on x.
syms x
assume(x,"real")
assumeAlso(x < 0)
assumptions(x)
ans = x ∈ ℝ x < 0
assume(x,"clear")
assumptions accepts symbolic expressions and functions as input and returns all assumptions that
affect all variables in the symbolic expressions or functions.
Set assumptions on variables in a symbolic expression and function. Find all assumptions that affect
all variables in the symbolic expression using assumptions.
syms a b c f(a,b,c)
expr = a*exp(b)*sin(c);
assume(a+b > 3 & in(a,"integer") & in(c,"real"))
assumptions(expr)
ans = a ∈ ℤ c ∈ ℝ 3 < a + b
Find all assumptions that affect all variables that are inputs to a symbolic function.
assumptions(f)
ans = a ∈ ℤ c ∈ ℝ 3 < a + b
7-84
assumptions
Note that if you use syms to create another symbolic function after setting assumptions on the
function input arguments, syms clears all previously set assumptions on the symbolic variables.
Instead, create the symbolic function first, and then set the assumptions on the symbolic variables.
syms g(a,b,c)
assumptions(g)
ans =
ans = a ∈ ℤ c ∈ ℝ 3 < a + b
assume([a b c],"clear")
To restore old assumptions, first store the assumptions returned by assumptions. Then you can
restore these assumptions at any point by calling assume or assumeAlso.
Solve the equation for a spring system using dsolve under the assumptions that the mass and spring
constant are positive.
syms m k positive
syms x(t)
xsol = dsolve(m*diff(x,t,t) == -k*x, x(0) == 0)
xsol =
kt
−C1 sin
m
Suppose you want to explore solutions unconstrained by assumptions, but want to restore the
assumptions afterwards. First store the assumptions using assumptions, then clear the assumptions
and solve the equation. dsolve returns unconstrained solutions.
tmp = assumptions;
assume([m k],"clear")
xsol = dsolve(m*diff(x,t,t) == -k*x, x(0) == 0)
xsol =
t −k m 2 t −k m
−C1 e− m e m −1
assume(tmp)
7-85
7 Functions
assume([m k],"clear")
Input Arguments
var — Symbolic input to check for assumptions
symbolic variable | symbolic expression | symbolic function | symbolic vector | symbolic matrix |
symbolic multidimensional array
Symbolic input for which to show assumptions, specified as a symbolic variable, expression, or
function, or a vector, matrix, or multidimensional array of symbolic variables, expressions, or
functions.
Tips
• When you delete a symbolic object from the MATLAB workspace by using clear, all assumptions
that you set on that object remain in the symbolic engine. If you declare a new symbolic variable
with the same name, it inherits these assumptions.
• To clear all assumptions set on a symbolic variable var use this command.
assume(var,"clear")
• To clear all objects in the MATLAB workspace and close the Symbolic Math Toolbox engine
associated with the MATLAB workspace resetting all its assumptions, use this command.
clear all
Version History
Introduced in R2012a
See Also
and | assume | assumeAlso | clear | in | isAlways | not | or | piecewise | sym | syms
Topics
“Use Assumptions on Symbolic Variables” on page 1-41
7-86
atan
atan
Symbolic inverse tangent
Syntax
P = atan(Z)
P = atan(Y,X)
Description
P = atan(Z) returns the inverse tangent on page 7-90 (arctangent) of the elements of Z. All angles
are in radians.
P = atan(Y,X) returns the four-quadrant inverse tangent on page 7-90 of the elements of Y and X.
This syntax with two input arguments is the same as atan2(Y,X).
Symbolic arguments X and Y are assumed to be real, and atan(Y,X) returns values in the interval
[-pi,pi].
Examples
Compute the inverse tangent function for these numbers. Because these numbers are not symbolic
objects, atan returns floating-point results.
P = atan([-1, -1/3, -1/sqrt(3), 1/2, 1, sqrt(3)])
P = 1×6
Compute the inverse tangent function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, atan returns unresolved symbolic calls.
symP = atan(sym([-1, -1/3, -1/sqrt(3), 1/2, 1, sqrt(3)]))
symP =
π 1 π 1 π π
− −atan − atan
4 3 6 2 4 3
7-87
7 Functions
Plot the inverse tangent function on the interval from -10 to 10.
syms x
fplot(atan(x),[-10 10])
grid on
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing atan.
Find the first and second derivatives of the inverse tangent function.
syms z
D1 = diff(atan(z),z)
D1 =
1
z2 + 1
7-88
atan
D2 = diff(atan(z),z,z)
D2 =
2z
− 2
z2 + 1
I = int(atan(z),z)
I =
log z2 + 1
z atan z −
2
T = taylor(atan(z),z)
T =
z5 z3
− +z
5 3
R = rewrite(atan(z),'log')
R =
log 1 − z i i log 1 + z i i
−
2 2
Input Arguments
Z — Tangent of angle
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix | symbolic array
Y — y-coordinates
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix | symbolic array
Inputs Y and X must either be the same size or have sizes that are compatible (for example, Y is an M-
by-N matrix and X is a scalar or 1-by-N row vector). For more information, see “Compatible Array
Sizes for Basic Operations”.
X — x-coordinates
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix | symbolic array
7-89
7 Functions
Inputs Y and X must either be the same size or have sizes that are compatible (for example, Y is an M-
by-N matrix and X is a scalar or 1-by-N row vector). For more information, see “Compatible Array
Sizes for Basic Operations”.
More About
Inverse Tangent
i 1 − iZ
atan(Z) = log .
2 1 + iZ
If X ≠ 0 and Y ≠ 0, then
Y π
atan Y, X = atan( ) + sign Y 1 − sign X .
X 2
Results returned by atan(Y,X) belong to the closed interval [-pi,pi]. Meanwhile, results returned
by atan(Y/X) belong to the closed interval [-pi/2,pi/2].
Version History
Introduced before R2006a
See Also
acos | asin | acsc | asec | acot | atan2 | sin | cos | tan | csc | sec | cot
7-90
atan2
atan2
Symbolic four-quadrant inverse tangent
Syntax
P = atan2(Y,X)
Description
P = atan2(Y,X) computes the four-quadrant inverse tangent on page 7-92 (arctangent) of Y and
X.
Symbolic arguments X and Y are assumed to be real, and atan2(Y,X) returns values in the interval
[-pi,pi].
Examples
Compute the arctangents of these parameters. Because these numbers are not symbolic objects, you
get floating-point results.
P = 1×3
Compute the arctangents of these parameters which are converted to symbolic objects.
P =
π π π
atan
4 4 4
syms x
P_minusinf = limit(atan2(x^2/(1 + x),x),x,-Inf)
P_minusinf =
3π
−
4
7-91
7 Functions
P_plusinf =
π
4
P =
π π
3 6
π π
4 2
Input Arguments
Y — y-coordinates
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix | symbolic array
Inputs Y and X must either be the same size or have sizes that are compatible (for example, Y is an M-
by-N matrix and X is a scalar or 1-by-N row vector). For more information, see “Compatible Array
Sizes for Basic Operations”.
X — x-coordinates
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix | symbolic array
Inputs Y and X must either be the same size or have sizes that are compatible (for example, Y is an M-
by-N matrix and X is a scalar or 1-by-N row vector). For more information, see “Compatible Array
Sizes for Basic Operations”.
More About
Four-Quadrant Inverse Tangent
If X ≠ 0 and Y ≠ 0, then
Y π
atan2 Y, X = atan( ) + sign Y 1 − sign X
X 2
7-92
atan2
Results returned by atan2(Y,X) belong to the closed interval [-pi,pi]. Meanwhile, results
returned by atan(Y/X) belong to the closed interval [-pi/2,pi/2].
Tips
• Calling atan2 for numbers (or vectors or matrices of numbers) that are not symbolic objects
invokes the MATLAB atan2 function.
• If one of the arguments X and Y is a vector or a matrix, and another one is a scalar, then atan2
expands the scalar into a vector or a matrix of the same length with all elements equal to that
scalar.
• If X = 0 and Y > 0, then atan2(Y,X) returns pi/2.
Alternatives
For complex Z = X + Y*i, the call atan2(Y,X) is equivalent to angle(Z).
Version History
Introduced in R2013a
See Also
angle | atan | conj | imag | real
7-93
7 Functions
atanh
Symbolic inverse hyperbolic tangent function
Syntax
atanh(X)
Description
atanh(X) returns the inverse hyperbolic tangent function of X.
Examples
Inverse Hyperbolic Tangent Function for Numeric and Symbolic Arguments
Compute the inverse hyperbolic tangent function for these numbers. Because these numbers are not
symbolic objects, atanh returns floating-point results.
A =
0.0000 - 0.7854i 0.0000 + 0.0000i 0.1682 + 0.0000i...
0.0000 + 0.4636i 0.0000 + 0.7854i 0.5493 + 1.5708i
Compute the inverse hyperbolic tangent function for the numbers converted to symbolic objects. For
many symbolic (exact) numbers, atanh returns unresolved symbolic calls.
symA =
[ -(pi*1i)/4, 0, atanh(1/6), atanh(1i/2), (pi*1i)/4, atanh(2)]
vpa(symA)
ans =
[ -0.78539816339744830961566084581988i,...
0,...
0.1682361183106064652522967051085,...
0.46364760900080611621425623146121i,...
0.78539816339744830961566084581988i,...
0.54930614433405484569762261846126 - 1.5707963267948966192313216916398i]
7-94
atanh
syms x
fplot(atanh(x),[-1 1])
grid on
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing
atanh.
Find the first and second derivatives of the inverse hyperbolic tangent function:
syms x
diff(atanh(x), x)
diff(atanh(x), x, x)
ans =
-1/(x^2 - 1)
ans =
(2*x)/(x^2 - 1)^2
int(atanh(x), x)
ans =
log(x^2 - 1)/2 + x*atanh(x)
7-95
7 Functions
taylor(atanh(x), x)
ans =
x^5/5 + x^3/3 + x
Rewrite the inverse hyperbolic tangent function in terms of the natural logarithm:
rewrite(atanh(x), 'log')
ans =
log(x + 1)/2 - log(1 - x)/2
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Version History
Introduced before R2006a
See Also
acosh | asinh | acsch | asech | acoth | sinh | cosh | tanh | csch | sech | coth
7-96
baseUnits
baseUnits
Base units of unit system
Syntax
baseUnits(unitSystem)
Description
baseUnits(unitSystem) returns the base units of the unit system unitSystem as a vector of
symbolic units. You can use the returned units to create new unit systems by using newUnitSystem.
Examples
Get the base units of a unit system by using baseUnits. Then, modify the base units and create a
new unit system using the modified base units. Available unit systems include SI, CGS, and US. For all
unit systems, see “Unit Systems List” on page 2-71.
SIUnits = baseUnits('SI')
SIUnits =
[ [kg], [s], [m], [A], [cd], [mol], [K]]
Note Do not define a variable called baseUnits because the variable will prevent access to the
baseUnits function.
Define base units that use kilometer for length and hour for time by modifying SIUnits using subs.
u = symunit;
newUnits = subs(SIUnits,[u.m u.s],[u.km u.hr])
newUnits =
[ [kg], [h], [km], [A], [cd], [mol], [K]]
newUnitSystem('SI_km_hr',newUnits)
ans =
"SI_km_hr"
7-97
7 Functions
To convert units between unit systems, see “Unit Conversions and Unit Systems” on page 2-53.
Input Arguments
unitSystem — Name of unit system
string | character vector
Version History
Introduced in R2017b
See Also
derivedUnits | newUnitSystem | removeUnitSystem | rewrite | symunit
Topics
“Units of Measurement Tutorial” on page 2-47
“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)
7-98
bernoulli
bernoulli
Bernoulli numbers and polynomials
Syntax
bernoulli(n)
bernoulli(n,x)
Description
bernoulli(n) returns the nth Bernoulli number on page 7-102.
Examples
Bernoulli Numbers with Odd and Even Indices
The 0th Bernoulli number is 1. The next Bernoulli number can be -1/2 or 1/2, depending on the
definition. The bernoulli function uses -1/2. The Bernoulli numbers with even indices n > 1
alternate the signs. Any Bernoulli number with an odd index n > 2 is 0.
Compute the even-indexed Bernoulli numbers with the indices from 0 to 10. Because these indices
are not symbolic objects, bernoulli returns floating-point results.
bernoulli(0:2:10)
ans =
1.0000 0.1667 -0.0333 0.0238 -0.0333 0.0758
Compute the same Bernoulli numbers for the indices converted to symbolic objects:
bernoulli(sym(0:2:10))
ans =
[ 1, 1/6, -1/30, 1/42, -1/30, 5/66]
Compute the odd-indexed Bernoulli numbers with the indices from 1 to 11:
bernoulli(sym(1:2:11))
ans =
[ -1/2, 0, 0, 0, 0, 0]
Bernoulli Polynomials
For the Bernoulli polynomials, use bernoulli with two input arguments.
Compute the first, second, and third Bernoulli polynomials in variables x, y, and z, respectively:
syms x y z
bernoulli(1, x)
7-99
7 Functions
bernoulli(2, y)
bernoulli(3, z)
ans =
x - 1/2
ans =
y^2 - y + 1/6
ans =
z^3 - (3*z^2)/2 + z/2
If the second argument is a number, bernoulli evaluates the polynomial at that number. Here, the
result is a floating-point number because the input arguments are not symbolic numbers:
bernoulli(2, 1/3)
ans =
-0.0556
To get the exact symbolic result, convert at least one of the numbers to a symbolic object:
bernoulli(2, sym(1/3))
ans =
-1/18
syms x
fplot(bernoulli(0:5, x), [-0.8 1.8])
title('Bernoulli Polynomials')
grid on
7-100
bernoulli
Many functions, such as diff and expand, handles expressions containing bernoulli.
syms n x
diff(bernoulli(n,x^2), x)
ans =
2*n*x*bernoulli(n - 1, x^2)
diff(bernoulli(n,x^2), x, x)
ans =
2*n*bernoulli(n - 1, x^2) +...
4*n*x^2*bernoulli(n - 2, x^2)*(n - 1)
expand(bernoulli(n, x + 3))
ans =
bernoulli(n, x) + (n*(x + 1)^n)/(x + 1) +...
(n*(x + 2)^n)/(x + 2) + (n*x^n)/x
expand(bernoulli(n, 3*x))
7-101
7 Functions
ans =
(3^n*bernoulli(n, x))/3 + (3^n*bernoulli(n, x + 1/3))/3 +...
(3^n*bernoulli(n, x + 2/3))/3
Input Arguments
n — Index of the Bernoulli number or polynomial
nonnegative integer | symbolic nonnegative integer | symbolic variable | symbolic expression |
symbolic function | symbolic vector | symbolic matrix
x — Polynomial variable
symbolic variable | symbolic expression | symbolic function | symbolic vector | symbolic matrix
More About
Bernoulli Polynomials
∞
text tn
= ∑ bernoulli n, x
n!
et − 1 n=0
Bernoulli Numbers
bernoulli n = bernoulli n, 0
Version History
Introduced in R2014a
See Also
euler
7-102
bernstein
bernstein
Bernstein polynomials
Syntax
bernstein(f,n,t)
bernstein(g,n,t)
bernstein(g,var,n,t)
Description
bernstein(f,n,t) with a function handle f returns the nth-order Bernstein polynomial on page 7-
107 symsum(nchoosek(n,k)*t^k*(1-t)^(n-k)*f(k/n),k,0,n), evaluated at the point t. This
polynomial approximates the function f over the interval [0,1].
If any argument is symbolic, bernstein converts all arguments except a function handle to symbolic,
and converts a function handle’s results to symbolic.
Examples
Approximation of Sine Function Specified as Function Handle
Approximate the sine function by the 10th- and 100th-degree Bernstein polynomials.
syms t
b10 = bernstein(@(t) sin(2*pi*t), 10, t);
b100 = bernstein(@(t) sin(2*pi*t), 100, t);
fplot(sin(2*pi*t),[0,1])
hold on
fplot(b10,[0,1])
fplot(b100,[0,1])
7-103
7 Functions
Approximate the exponential function by the second-order Bernstein polynomial in the variable t:
syms x t
bernstein(exp(x), 2, t)
ans =
(t - 1)^2 + t^2*exp(1) - 2*t*exp(1/2)*(t - 1)
Approximate the multivariate exponential function. When you approximate a multivariate function,
bernstein regards it as a univariate function of the default variable determined by symvar. The
default variable for the expression y*exp(x*y) is x:
syms x y t
symvar(y*exp(x*y), 1)
ans =
x
ans =
y*(t - 1)^2 + t^2*y*exp(y) - 2*t*y*exp(y/2)*(t - 1)
7-104
bernstein
bernstein(y*exp(x*y), y, 2, t)
ans =
t^2*exp(x) - t*exp(x/2)*(t - 1)
Approximate function f representing a linear ramp by the fifth-order Bernstein polynomials in the
variable t:
syms f(t)
f(t) = triangularPulse(1/4, 3/4, Inf, t);
p = bernstein(f, 5, t)
p =
7*t^3*(t - 1)^2 - 3*t^2*(t - 1)^3 - 5*t^4*(t - 1) + t^5
simplify(p)
ans =
-t^2*(2*t - 3)
When you simplify a high-order symbolic Bernstein polynomial, the result often cannot be evaluated
in a numerically stable way.
Approximate this rectangular pulse function by the 100th-degree Bernstein polynomial, and then
simplify the result.
f = @(x)rectangularPulse(1/4,3/4,x);
b1 = bernstein(f, 100, sym('t'));
b2 = simplify(b1);
f1 = matlabFunction(b1);
f2 = matlabFunction(b2);
Compare the plot of the original rectangular pulse function, its numerically stable Bernstein
representation f1, and its simplified version f2. The simplified version is not numerically stable.
t = 0:0.001:1;
plot(t, f(t), t, f1(t), t, f2(t))
hold on
legend('original function','Bernstein polynomial',...
'simplified Bernstein polynomial')
hold off
7-105
7 Functions
Input Arguments
f — Function to be approximated by a polynomial
function handle
t — Evaluation point
number | symbolic number | symbolic variable | symbolic expression | symbolic function
7-106
bernstein
More About
Bernstein Polynomials
Here,
n k n−k
bk, n t = t 1−t , k = 0, …, n
k
n
are the Bernstein basis polynomials, and is a binomial coefficient.
k
lim Bn f t = f t
n ∞
Tips
• Symbolic polynomials returned for symbolic t are numerically stable when substituting numerical
values between 0 and 1 for t.
• If you simplify a symbolic Bernstein polynomial, the result can be unstable when substituting
numerical values for the curve parameter t.
Version History
Introduced in R2013b
See Also
bernsteinMatrix | formula | nchoosek | symvar | symsum
7-107
7 Functions
bernsteinMatrix
Bernstein matrix
Syntax
B = bernsteinMatrix(n,t)
Description
B = bernsteinMatrix(n,t), where t is a vector, returns the length(t)-by-(n+1) Bernstein
matrix B, such that B(i,k+1)= nchoosek(n,k)*t(i)^k*(1-t(i))^(n-k). Here, the index i
runs from 1 to length(t), and the index k runs from 0 to n.
Here, the n+1 rows of the matrix P specify the control points of the Bezier curve. For example, to
construct the second-order 3-D Bezier curve, specify the control points as:
Examples
Plot the fourth-order Bezier curve specified by the control points p0 = [0 1], p1 = [4 3], p2 =
[6 2], p3 = [3 0], p4 = [2 4]. Create a matrix with each row representing a control point.
P = [0 1; 4 3; 6 2; 3 0; 2 4];
syms t
B = bernsteinMatrix(4,t);
bezierCurve = simplify(B*P);
7-108
bernsteinMatrix
Construct the third-order Bezier curve specified by the 4-by-3 matrix P of control points. Each control
point corresponds to a row of the matrix P.
P = [0 0 0; 2 2 2; 2 -1 1; 6 1 3];
syms t
B = bernsteinMatrix(3,t);
bezierCurve = simplify(B*P);
7-109
7 Functions
Construct the third-order Bezier curve with the evaluation point specified by the following 1-by-101
vector t.
t = 0:1/100:1;
Compute the third-order 101-by-4 Bernstein matrix and specify the control points.
B = bernsteinMatrix(3,t);
P = [0 0 0; 2 2 2; 2 -1 1; 6 1 3];
Construct and plot the Bezier curve. Add grid lines and control points to the plot.
bezierCurve = B*P;
plot3(bezierCurve(:,1), bezierCurve(:,2), bezierCurve(:,3))
hold on
grid
scatter3(P(:,1), P(:,2), P(:,3),'filled')
hold off
7-110
bernsteinMatrix
Input Arguments
n — Approximation order
nonnegative integer
t — Evaluation point
number | vector | symbolic number | symbolic variable | symbolic expression | symbolic vector
Output Arguments
B — Bernstein matrix
matrix
Version History
Introduced in R2013b
7-111
7 Functions
See Also
bernstein | nchoosek | symvar | symsum
7-112
besselh
besselh
Bessel function of third kind (Hankel function) for symbolic expressions
Syntax
H = besselh(nu,K,z)
H = besselh(nu,z)
H = besselh(nu,K,z,1)
Description
H = besselh(nu,K,z) computes the Hankel function Hν(K)(z), where K = 1 or 2, for each element of
the complex array z. The output H has the symbolic data type if any input argument is symbolic. See
“Bessel’s Equation” on page 7-115.
H = besselh(nu,z) uses K = 1.
Examples
syms z
H = besselh(3/2,1,z)
H =
i
2 ez i 1 + z
−
z π
Hval = subs(H,z,1+2i)
Hval =
7 1
2 e−2 + i − 5 − 5 i
1+2 i π
vpa(Hval)
H2 = besselh(3/2,z)
H2 =
7-113
7 Functions
i
2 ez i 1 + z
−
z π
Hnew = besselh(3/2,1,z,1)
Hnew =
i
2 1+ z
−
z π
diffH = diff(H)
diffH =
i i
2 ez i i 2 ez i 1 + z i 2 ez i 1 + z
− +
z5/2 π z π 2 z3/2 π
Input Arguments
nu — Hankel function order
symbolic array | double array
Hankel function order, specified as a symbolic array or double array. If nu and z are arrays of the
same size, the result is also that size. If either input is a scalar, besselh expands it to the other input
size.
Example: nu = 3*sym(pi)/2
Kind of Hankel function, specified as a symbolic or double 1 or 2. K identifies the sign of the added
Bessel function Y:
Example: K = sym(2)
Hankel function argument, specified as a symbolic array or double array. If nu and z are arrays of the
same size, the result is also that size. If either input is a scalar, besselh expands it to the other input
size.
Example: z = sym(1+1i)
7-114
besselh
More About
Bessel’s Equation
where ν is a real constant, is called Bessel's equation, and its solutions are known as Bessel functions.
Jν(z) and J–ν(z) form a fundamental set of solutions of Bessel's equation for noninteger ν. Yν(z) is a
second solution of Bessel's equation—linearly independent of Jν(z)—defined by
Jν(z)cos(νπ) − J−ν(z)
Y ν(z) = .
sin(νπ)
Version History
Introduced in R2018b
References
[1] Abramowitz, M., and I. A. Stegun. Handbook of Mathematical Functions. National Bureau of
Standards, Applied Math. Series #55, Dover Publications, 1965.
See Also
besseli | besselj | besselk | bessely
7-115
7 Functions
besseli
Modified Bessel function of the first kind for symbolic expressions
Syntax
besseli(nu,z)
Description
besseli(nu,z) returns the modified Bessel function of the first kind on page 7-119, Iν(z).
Examples
Find Modified Bessel Function of First Kind
Compute the modified Bessel functions of the first kind for these numbers. Because these numbers
are not symbolic objects, you get floating-point results.
[besseli(0, 5), besseli(-1, 2), besseli(1/3, 7/4), besseli(1, 3/2 + 2*i)]
ans =
27.2399 + 0.0000i 1.5906 + 0.0000i 1.7951 + 0.0000i -0.1523 + 1.0992i
Compute the modified Bessel functions of the first kind for the numbers converted to symbolic
objects. For most symbolic (exact) numbers, besseli returns unresolved symbolic calls.
ans =
[ besseli(0, 5), besseli(1, 2), besseli(1/3, 7/4), besseli(1, 3/2 + 2i)]
For symbolic variables and expressions, besseli also returns unresolved symbolic calls:
syms x y
[besseli(x, y), besseli(1, x^2), besseli(2, x - y), besseli(x^2, x*y)]
ans =
[ besseli(x, y), besseli(1, x^2), besseli(2, x - y), besseli(x^2, x*y)]
Solve this second-order differential equation. The solutions are the modified Bessel functions of the
first and the second kind.
syms nu w(z)
dsolve(z^2*diff(w, 2) + z*diff(w) -(z^2 + nu^2)*w == 0)
ans =
C2*besseli(nu, z) + C3*besselk(nu, z)
Verify that the modified Bessel function of the first kind is a valid solution of the modified Bessel
differential equation.
7-116
besseli
syms nu z
isAlways(z^2*diff(besseli(nu, z), z, 2) + z*diff(besseli(nu, z), z)...
- (z^2 + nu^2)*besseli(nu, z) == 0)
ans =
logical
1
If the first parameter is an odd integer multiplied by 1/2, besseli rewrites the Bessel functions in
terms of elementary functions:
syms x
besseli(1/2, x)
ans =
(2^(1/2)*sinh(x))/(x^(1/2)*pi^(1/2))
besseli(-1/2, x)
ans =
(2^(1/2)*cosh(x))/(x^(1/2)*pi^(1/2))
besseli(-3/2, x)
ans =
(2^(1/2)*(sinh(x) - cosh(x)/x))/(x^(1/2)*pi^(1/2))
besseli(5/2, x)
ans =
-(2^(1/2)*((3*cosh(x))/x - sinh(x)*(3/x^2 + 1)))/(x^(1/2)*pi^(1/2))
Differentiate the expressions involving the modified Bessel functions of the first kind:
syms x y
diff(besseli(1, x))
diff(diff(besseli(0, x^2 + x*y -y^2), x), y)
ans =
besseli(0, x) - besseli(1, x)/x
ans =
besseli(1, x^2 + x*y - y^2) +...
(2*x + y)*(besseli(0, x^2 + x*y - y^2)*(x - 2*y) -...
(besseli(1, x^2 + x*y - y^2)*(x - 2*y))/(x^2 + x*y - y^2))
Call besseli for the matrix A and the value 1/2. The result is a matrix of the modified Bessel
functions besseli(1/2, A(i,j)).
syms x
A = [-1, pi; x, 0];
besseli(1/2, A)
7-117
7 Functions
ans =
[ (2^(1/2)*sinh(1)*1i)/pi^(1/2), (2^(1/2)*sinh(pi))/pi]
[ (2^(1/2)*sinh(x))/(x^(1/2)*pi^(1/2)), 0]
syms x y
fplot(besseli(0:3, x))
axis([0 4 -0.1 4])
grid on
ylabel('I_v(x)')
legend('I_0','I_1','I_2','I_3', 'Location','Best')
title('Modified Bessel functions of the first kind')
Input Arguments
nu — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic array | symbolic
function | symbolic expression
7-118
besseli
Input, specified as a number, vector, matrix, array, or a symbolic number, variable, expression,
function, or array. If nu is a vector or matrix, besseli returns the modified Bessel function of the
first kind for each element of nu.
z — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, array, or a symbolic number, variable, expression,
function, or array. If nu is a vector or matrix, besseli returns the modified Bessel function of the
first kind for each element of nu.
More About
Modified Bessel Functions of the First Kind
has two linearly independent solutions. These solutions are represented by the modified Bessel
functions of the first kind, Iν(z), and the modified Bessel functions of the second kind, Kν(z):
w z = C1Iν z + C2Kν z
This formula is the integral representation of the modified Bessel functions of the first kind:
ν π
Iν z =
z/2
πΓ ν + 1/2 ∫e
0
zcos t sin t
2ν
dt
Tips
• Calling besseli for a number that is not a symbolic object invokes the MATLAB besseli
function.
• At least one input argument must be a scalar or both arguments must be vectors or matrices of
the same size. If one input argument is a scalar and the other one is a vector or a matrix,
besseli(nu,z) expands the scalar into a vector or matrix of the same size as the other
argument with all elements equal to that scalar.
Version History
Introduced in R2014a
References
[1] Olver, F. W. J. “Bessel Functions of Integer Order.” Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New
York: Dover, 1972.
7-119
7 Functions
See Also
airy | besselh | besselj | besselk | bessely
7-120
besselj
besselj
Bessel function of the first kind for symbolic expressions
Syntax
besselj(nu,z)
Description
besselj(nu,z) returns the Bessel function of the first kind on page 7-124, Jν(z).
Examples
Find Bessel Function of First Kind
Compute the Bessel functions of the first kind for these numbers. Because these numbers are floating
point, you get floating-point results.
Compute the Bessel functions of the first kind for the numbers converted to symbolic form. For most
symbolic (exact) numbers, besselj returns unresolved symbolic calls.
[besselj(sym(0),5) besselj(sym(-1),2)...
besselj(1/3,sym(7/4)) besselj(sym(1),3/2+2*i)]
ans =
[ besselj(0, 5), -besselj(1, 2), besselj(1/3, 7/4), besselj(1, 3/2 + 2i)]
For symbolic variables and expressions, besselj also returns unresolved symbolic calls.
syms x y
[besselj(x,y) besselj(1,x^2) besselj(2,x-y) besselj(x^2,x*y)]
ans =
[ besselj(x, y), besselj(1, x^2), besselj(2, x - y), besselj(x^2, x*y)]
Solve this second-order differential equation. The solutions are the Bessel functions of the first and
the second kind.
syms nu w(z)
ode = z^2*diff(w,2) + z*diff(w) +(z^2-nu^2)*w == 0;
dsolve(ode)
ans =
C2*besselj(nu, z) + C3*bessely(nu, z)
Verify that the Bessel function of the first kind is a valid solution of the Bessel differential equation.
7-121
7 Functions
cond = subs(ode,w,besselj(nu,z));
isAlways(cond)
ans =
logical
1
Show that if the first parameter is an odd integer multiplied by 1/2, besselj rewrites the Bessel
functions in terms of elementary functions.
syms x
besselj(1/2,x)
ans =
(2^(1/2)*sin(x))/(x^(1/2)*pi^(1/2))
besselj(-1/2,x)
ans =
(2^(1/2)*cos(x))/(x^(1/2)*pi^(1/2))
besselj(-3/2,x)
ans =
-(2^(1/2)*(sin(x) + cos(x)/x))/(x^(1/2)*pi^(1/2))
besselj(5/2,x)
ans =
-(2^(1/2)*((3*cos(x))/x - sin(x)*(3/x^2 - 1)))/(x^(1/2)*pi^(1/2))
syms x y
diff(besselj(1,x))
ans =
besselj(0, x) - besselj(1, x)/x
diff(diff(besselj(0,x^2+x*y-y^2), x), y)
ans =
- besselj(1, x^2 + x*y - y^2) -...
(2*x + y)*(besselj(0, x^2 + x*y - y^2)*(x - 2*y) -...
(besselj(1, x^2 + x*y - y^2)*(x - 2*y))/(x^2 + x*y - y^2))
Call besselj for the matrix A and the value 1/2. besselj acts element-wise to return matrix of
Bessel functions.
syms x
A = [-1, pi; x, 0];
besselj(1/2, A)
7-122
besselj
ans =
[ (2^(1/2)*sin(1)*1i)/pi^(1/2), 0]
[ (2^(1/2)*sin(x))/(x^(1/2)*pi^(1/2)), 0]
ylabel('J_v(x)')
legend('J_0','J_1','J_2','J_3', 'Location','Best')
title('Bessel functions of the first kind')
Input Arguments
nu — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
7-123
7 Functions
If nu is a vector or matrix, besselj returns the modified Bessel function of the first kind for each
element of nu.
z — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
If nu is a vector or matrix, besselj returns the modified Bessel function of the first kind for each
element of nu.
More About
Bessel Functions of the First Kind
These solutions are the Bessel functions of the first kind, Jν(z), and the Bessel functions of the second
kind, Yν(z).
w z = C1 Jν z + C2Y ν z
This formula is the integral representation of the Bessel functions of the first kind.
ν π
Jν z =
z/2
πΓ ν + 1/2 ∫ cos zcos t
0
sin t
2ν
dt
Tips
• Calling besselj for a number that is not a symbolic object invokes the MATLAB besselj
function.
• At least one input argument must be a scalar or both arguments must be vectors or matrices of
the same size. If one input argument is a scalar and the other one is a vector or a matrix,
besselj(nu,z) expands the scalar into a vector or matrix of the same size as the other
argument with all elements equal to that scalar.
Version History
Introduced in R2014a
References
[1] Olver, F. W. J. “Bessel Functions of Integer Order.” Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New
York: Dover, 1972.
7-124
besselj
See Also
airy | besselh | besseli | besselk | bessely
7-125
7 Functions
besselk
Modified Bessel function of the second kind for symbolic expressions
Syntax
besselk(nu,z)
Description
besselk(nu,z) returns the modified Bessel function of the second kind on page 7-129, Kν(z).
Examples
Find Modified Bessel Function of Second Kind
Compute the modified Bessel functions of the second kind for these numbers. Because these numbers
are not symbolic objects, you get floating-point results.
Compute the modified Bessel functions of the second kind for the numbers converted to symbolic
objects. For most symbolic (exact) numbers, besselk returns unresolved symbolic calls.
ans =
[ besselk(0, 5), besselk(1, 2), besselk(1/3, 7/4), besselk(1, 3/2 + 2i)]
For symbolic variables and expressions, besselk also returns unresolved symbolic calls:
syms x y
[besselk(x, y), besselk(1, x^2), besselk(2, x - y), besselk(x^2, x*y)]
ans =
[ besselk(x, y), besselk(1, x^2), besselk(2, x - y), besselk(x^2, x*y)]
If the first parameter is an odd integer multiplied by 1/2, besselk rewrites the Bessel functions in
terms of elementary functions:
syms x
besselk(1/2, x)
ans =
(2^(1/2)*pi^(1/2)*exp(-x))/(2*x^(1/2))
besselk(-1/2, x)
7-126
besselk
ans =
(2^(1/2)*pi^(1/2)*exp(-x))/(2*x^(1/2))
besselk(-3/2, x)
ans =
(2^(1/2)*pi^(1/2)*exp(-x)*(1/x + 1))/(2*x^(1/2))
besselk(5/2, x)
ans =
(2^(1/2)*pi^(1/2)*exp(-x)*(3/x + 3/x^2 + 1))/(2*x^(1/2))
Solve this second-order differential equation. The solutions are the modified Bessel functions of the
first and the second kind.
syms nu w(z)
dsolve(z^2*diff(w, 2) + z*diff(w) -(z^2 + nu^2)*w == 0)
ans =
C2*besseli(nu, z) + C3*besselk(nu, z)
Verify that the modified Bessel function of the second kind is a valid solution of the modified Bessel
differential equation:
syms nu z
isAlways(z^2*diff(besselk(nu, z), z, 2) + z*diff(besselk(nu, z), z)...
- (z^2 + nu^2)*besselk(nu, z) == 0)
ans =
logical
1
Differentiate the expressions involving the modified Bessel functions of the second kind:
syms x y
diff(besselk(1, x))
diff(diff(besselk(0, x^2 + x*y -y^2), x), y)
ans =
- besselk(1, x)/x - besselk(0, x)
ans =
(2*x + y)*(besselk(0, x^2 + x*y - y^2)*(x - 2*y) +...
(besselk(1, x^2 + x*y - y^2)*(x - 2*y))/(x^2 + x*y - y^2)) -...
besselk(1, x^2 + x*y - y^2)
Call besselk for the matrix A and the value 1/2. The result is a matrix of the modified Bessel
functions besselk(1/2, A(i,j)).
syms x
A = [-1, pi; x, 0];
besselk(1/2, A)
7-127
7 Functions
ans =
[ -(2^(1/2)*pi^(1/2)*exp(1)*1i)/2, (2^(1/2)*exp(-pi))/2]
[ (2^(1/2)*pi^(1/2)*exp(-x))/(2*x^(1/2)), Inf]
syms x y
fplot(besselk(0:3, x))
axis([0 4 0 4])
grid on
ylabel('K_v(x)')
legend('K_0','K_1','K_2','K_3', 'Location','Best')
title('Modified Bessel functions of the second kind')
Input Arguments
nu — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic array | symbolic
function | symbolic expression
7-128
besselk
Input, specified as a number, vector, matrix, array, or a symbolic number, variable, expression,
function, or array. If nu is a vector or matrix, besseli returns the modified Bessel function of the
first kind for each element of nu.
z — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, array, or a symbolic number, variable, expression,
function, or array. If nu is a vector or matrix, besseli returns the modified Bessel function of the
first kind for each element of nu.
More About
Modified Bessel Functions of the Second Kind
2
d w dw
z2 +z − z2 + ν2 w = 0
dz 2 dz
has two linearly independent solutions. These solutions are represented by the modified Bessel
functions of the first kind, Iν(z), and the modified Bessel functions of the second kind, Kν(z):
w z = C1Iν z + C2Kν z
The modified Bessel functions of the second kind are defined via the modified Bessel functions of the
first kind:
π/2
Kν z = I z − Iν z
sin νπ −ν
Here Iν(z) are the modified Bessel functions of the first kind:
ν π
Iν z =
z/2
πΓ ν + 1/2 ∫e
0
zcos t sin t
2ν
dt
Tips
• Calling besselk for a number that is not a symbolic object invokes the MATLAB besselk
function.
• At least one input argument must be a scalar or both arguments must be vectors or matrices of
the same size. If one input argument is a scalar and the other one is a vector or a matrix,
besselk(nu,z) expands the scalar into a vector or matrix of the same size as the other
argument with all elements equal to that scalar.
Version History
Introduced in R2014a
7-129
7 Functions
References
[1] Olver, F. W. J. “Bessel Functions of Integer Order.” Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New
York: Dover, 1972.
See Also
airy | besselh | besseli | besselj | bessely
7-130
bessely
bessely
Bessel function of the second kind for symbolic expressions
Syntax
bessely(nu,z)
Description
bessely(nu,z) returns the Bessel function of the second kind on page 7-134, Yν(z).
Examples
Find Bessel Function of Second Kind
Compute the Bessel functions of the second kind for these numbers. Because these numbers are not
symbolic objects, you get floating-point results.
[bessely(0, 5), bessely(-1, 2), bessely(1/3, 7/4), bessely(1, 3/2 + 2*i)]
ans =
-0.3085 + 0.0000i 0.1070 + 0.0000i 0.2358 + 0.0000i -0.4706 + 1.5873i
Compute the Bessel functions of the second kind for the numbers converted to symbolic objects. For
most symbolic (exact) numbers, bessely returns unresolved symbolic calls.
ans =
[ bessely(0, 5), -bessely(1, 2), bessely(1/3, 7/4), bessely(1, 3/2 + 2i)]
For symbolic variables and expressions, bessely also returns unresolved symbolic calls:
syms x y
[bessely(x, y), bessely(1, x^2), bessely(2, x - y), bessely(x^2, x*y)]
ans =
[ bessely(x, y), bessely(1, x^2), bessely(2, x - y), bessely(x^2, x*y)]
Solve this second-order differential equation. The solutions are the Bessel functions of the first and
the second kind.
syms nu w(z)
dsolve(z^2*diff(w, 2) + z*diff(w) +(z^2 - nu^2)*w == 0)
ans =
C2*besselj(nu, z) + C3*bessely(nu, z)
Verify that the Bessel function of the second kind is a valid solution of the Bessel differential equation:
7-131
7 Functions
syms nu z
isAlways(z^2*diff(bessely(nu, z), z, 2) + z*diff(bessely(nu, z), z)...
+ (z^2 - nu^2)*bessely(nu, z) == 0)
ans =
logical
1
If the first parameter is an odd integer multiplied by 1/2, bessely rewrites the Bessel functions in
terms of elementary functions:
syms x
bessely(1/2, x)
ans =
-(2^(1/2)*cos(x))/(x^(1/2)*pi^(1/2))
bessely(-1/2, x)
ans =
(2^(1/2)*sin(x))/(x^(1/2)*pi^(1/2))
bessely(-3/2, x)
ans =
(2^(1/2)*(cos(x) - sin(x)/x))/(x^(1/2)*pi^(1/2))
bessely(5/2, x)
ans =
-(2^(1/2)*((3*sin(x))/x + cos(x)*(3/x^2 - 1)))/(x^(1/2)*pi^(1/2))
Differentiate the expressions involving the Bessel functions of the second kind:
syms x y
diff(bessely(1, x))
diff(diff(bessely(0, x^2 + x*y -y^2), x), y)
ans =
bessely(0, x) - bessely(1, x)/x
ans =
- bessely(1, x^2 + x*y - y^2) -...
(2*x + y)*(bessely(0, x^2 + x*y - y^2)*(x - 2*y) -...
(bessely(1, x^2 + x*y - y^2)*(x - 2*y))/(x^2 + x*y - y^2))
Call bessely for the matrix A and the value 1/2. The result is a matrix of the Bessel functions
bessely(1/2, A(i,j)).
syms x
A = [-1, pi; x, 0];
bessely(1/2, A)
7-132
bessely
ans =
[ (2^(1/2)*cos(1)*1i)/pi^(1/2), 2^(1/2)/pi]
[ -(2^(1/2)*cos(x))/(x^(1/2)*pi^(1/2)), Inf]
ylabel('Y_v(x)')
legend('Y_0','Y_1','Y_2','Y_3', 'Location','Best')
title('Bessel functions of the second kind')
Input Arguments
nu — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
7-133
7 Functions
If nu is a vector or matrix, bessely returns the Bessel function of the second kind for each element
of nu.
z — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
If z is a vector or matrix, bessely returns the Bessel function of the second kind for each element of
z.
More About
Bessel Function of the Second Kind
2
d w dw
z2 +z + z2 − ν2 w = 0
dz 2 dz
has two linearly independent solutions. These solutions are represented by the Bessel functions of the
first kind, Jν(z), and the Bessel functions of the second kind, Yν(z):
w z = C1 Jν z + C2Y ν z
The Bessel functions of the second kind are defined via the Bessel functions of the first kind:
Jν z cos νπ − J−ν z
Yν z =
sin νπ
ν π
Jν z =
z/2
πΓ ν + 1/2 ∫ cos zcos t
0
sin t
2ν
dt
Tips
• Calling bessely for a number that is not a symbolic object invokes the MATLAB bessely
function.
At least one input argument must be a scalar or both arguments must be vectors or matrices of
the same size. If one input argument is a scalar and the other one is a vector or a matrix,
bessely(nu,z) expands the scalar into a vector or matrix of the same size as the other
argument with all elements equal to that scalar.
Version History
Introduced in R2014a
7-134
bessely
References
[1] Olver, F. W. J. “Bessel Functions of Integer Order.” Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New
York: Dover, 1972.
See Also
airy | besselh | besseli | besselj | besselk
7-135
7 Functions
beta
Beta function
Syntax
beta(x,y)
Description
beta(x,y) returns the beta function on page 7-138 of x and y.
Examples
Compute Beta Function for Numeric Inputs
Compute the beta function for these numbers. Because these numbers are not symbolic objects, you
get floating-point results:
[beta(1, 5), beta(3, sqrt(2)), beta(pi, exp(1)), beta(0, 1)]
ans =
0.2000 0.1716 0.0379 Inf
Compute the beta function for the numbers converted to symbolic objects:
[beta(sym(1), 5), beta(3, sym(2)), beta(sym(4), sym(4))]
ans =
[ 1/5, 1/12, 1/140]
If one or both parameters are complex numbers, convert these numbers to symbolic objects:
[beta(sym(i), 3/2), beta(sym(i), i), beta(sym(i + 2), 1 - i)]
ans =
[ (pi^(1/2)*gamma(1i))/(2*gamma(3/2 + 1i)), gamma(1i)^2/gamma(2i),...
(pi*(1/2 + 1i/2))/sinh(pi)]
Compute the beta function for negative parameters. If one or both arguments are negative numbers,
convert these numbers to symbolic objects:
[beta(sym(-3), 2), beta(sym(-1/3), 2), beta(sym(-3), 4), beta(sym(-3), -2)]
ans =
[ 1/6, -9/2, Inf, Inf]
Call beta for the matrix A and the value 1. The result is a matrix of the beta functions
beta(A(i,j),1):
7-136
beta
A = sym([1 2; 3 4]);
beta(A,1)
ans =
[ 1, 1/2]
[ 1/3, 1/4]
Differentiate the beta function, then substitute the variable t with the value 2/3 and approximate the
result using vpa:
syms t
u = diff(beta(t^2 + 1, t))
vpa(subs(u, t, 2/3), 10)
u =
beta(t, t^2 + 1)*(psi(t) + 2*t*psi(t^2 + 1) -...
psi(t^2 + t + 1)*(2*t + 1))
ans =
-2.836889094
syms x y
expand(beta(x, y))
expand(beta(x + 1, y - 1))
ans =
(gamma(x)*gamma(y))/gamma(x + y)
ans =
-(x*gamma(x)*gamma(y))/(gamma(x + y) - y*gamma(x + y))
Input Arguments
x — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
If x is a vector or matrix, beta returns the beta function for each element of x.
y — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
If y is a vector or matrix, beta returns the beta function for each element of y.
7-137
7 Functions
More About
Beta Function
Tips
• The beta function is uniquely defined for positive numbers and complex numbers with positive real
parts. It is approximated for other numbers.
• Calling beta for numbers that are not symbolic objects invokes the MATLAB beta function. This
function accepts real arguments only. If you want to compute the beta function for complex
numbers, use sym to convert the numbers to symbolic objects, and then call beta for those
symbolic objects.
• If one or both parameters are negative numbers, convert these numbers to symbolic objects using
sym, and then call beta for those symbolic objects.
• If the beta function has a singularity, beta returns the positive infinity Inf.
• beta(sym(0),0), beta(0,sym(0)), and beta(sym(0),sym(0)) return NaN.
• beta(x,y) = beta(y,x) and beta(x,A) = beta(A,x).
• At least one input argument must be a scalar or both arguments must be vectors or matrices of
the same size. If one input argument is a scalar and the other one is a vector or a matrix,
beta(x,y) expands the scalar into a vector or matrix of the same size as the other argument with
all elements equal to that scalar.
Version History
Introduced in R2014a
References
[1] Zelen, M. and N. C. Severo. “Probability Functions.” Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New
York: Dover, 1972.
See Also
gamma | factorial | nchoosek | psi
7-138
cat
cat
Concatenate symbolic arrays along specified dimension
Syntax
cat(dim,A1,...,AN)
Description
cat(dim,A1,...,AN) concatenates the arrays A1,...,AN along dimension dim. The remaining
dimensions must be the same size.
Examples
Concatenate Two Vectors into Matrix
A =
[ a1, a2, a3, a4]
B =
[ b1, b2, b3, b4]
ans =
[ a1, a2, a3, a4]
[ b1, b2, b3, b4]
ans =
[ a1, a2, a3, a4]
[ b1, b2, b3, b4]
ans =
[ a1, a2, a3, a4, b1, b2, b3, b4]
7-139
7 Functions
[A B]
ans =
[ a1, a2, a3, a4, b1, b2, b3, b4]
A = sym('a%d%d',[2 2]);
A(:,:,2) = -A
B = sym('b%d%d', [2 2]);
B(:,:,2) = -B
A(:,:,1) =
[ a11, a12]
[ a21, a22]
A(:,:,2) =
[ -a11, -a12]
[ -a21, -a22]
B(:,:,1) =
[ b11, b12]
[ b21, b22]
B(:,:,2) =
[ -b11, -b12]
[ -b21, -b22]
cat(3,A,B)
ans(:,:,1) =
[ a11, a12]
[ a21, a22]
ans(:,:,2) =
[ -a11, -a12]
[ -a21, -a22]
ans(:,:,3) =
[ b11, b12]
[ b21, b22]
ans(:,:,4) =
[ -b11, -b12]
[ -b21, -b22]
Input Arguments
dim — Dimension to concatenate arrays along
positive integer
7-140
cat
Version History
Introduced in R2010b
See Also
horzcat | reshape | vertcat
7-141
7 Functions
catalan
Catalan constant
Syntax
catalan
Description
catalan represents the Catalan constant on page 7-142. To get a floating-point approximation with
the current precision set by digits, use vpa(catalan).
Examples
Approximate Catalan Constant
Find a floating-point approximation of the Catalan constant with the default number of digits and with
the 10-digit precision.
Use vpa to approximate the Catalan constant with the default 32-digit precision:
vpa(catalan)
ans =
0.91596559417721901505460351493238
old = digits(10);
vpa(catalan)
ans =
0.9159655942
digits(old)
More About
Catalan Constant
Version History
Introduced in R2014a
7-142
catalan
See Also
dilog | eulergamma
7-143
7 Functions
ccode
C code representation of symbolic expression
Syntax
ccode(f)
ccode(f,Name,Value)
Description
ccode(f) returns C code for the symbolic expression f.
Examples
syms x
f = log(1+x);
ccode(f)
ans =
' t0 = log(x+1.0);'
H = sym(hilb(3));
ccode(H)
ans =
' H[0][0] = 1.0;
H[0][1] = 1.0/2.0;
H[0][2] = 1.0/3.0;
H[1][0] = 1.0/2.0;
H[1][1] = 1.0/3.0;
H[1][2] = 1.0/4.0;
H[2][0] = 1.0/3.0;
H[2][1] = 1.0/4.0;
H[2][2] = 1.0/5.0;'
Because generated C code initializes only non-zero elements, you can efficiently initialize arrays by
setting all elements to 0 directly in your C code. Then, use the generated C code to initialize only
nonzero elements. This approach enables efficient initialization of matrices, especially sparse
matrices.
7-144
ccode
Initialize the 3-by-3 identity matrix. First initialize the matrix with all elements set to 0 in your C
code. Then use the generated C code to initialize the nonzero values.
I3 = sym(eye(3));
I3code = ccode(I3)
I3code =
' I3[0][0] = 1.0;
I3[1][1] = 1.0;
I3[2][2] = 1.0;'
Write C code to the file ccodetest.c by specifying the File option. When writing to a file, ccode
optimizes the code by using intermediate variables named t0, t1, and so on.
syms x
f = diff(tan(x));
ccode(f,'File','ccodetest.c')
t0 = pow(tan(x),2.0)+1.0;
Include the comment Version: 1.1 in the file by using the Comments option. ccode uses block
comments.
ccode(f,'File','ccodetest.c','Comments','Version: 1.1')
/*
Version: 1.1
*/
t0 = pow(tan(x),2.0)+1.0;
Input Arguments
f — Symbolic input
symbolic expression
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: ccode(x^2,'File','ccode.c','Comments','V1.2')
File to write to, specified as a character vector or string. When writing to a file, ccode optimizes the
code by using intermediate variables named t0, t1, and so on.
7-145
7 Functions
Comments to include in the file header, specified as a character vector, cell array of character
vectors, or string vector. Because ccode uses block comments, the comments must not contain /* or
*/.
Tips
• To generate optimized C or C++ code from a symbolic expression, especially for a large
expression, you can use the MATLAB Coder app instead of using the ccode function. This way, the
generated code is better integrated into the MATLAB ecosystem. First, convert the symbolic
expression to a deployable MATLAB function using matlabFunction. Then, generate C or C++
code from the MATLAB function using the MATLAB Coder app. For an example, see “Generate C
Code from Symbolic Expressions Using the MATLAB Coder App” on page 5-16.
Version History
Introduced before R2006a
See Also
fortran | latex | matlabFunction
7-146
cell2sym
cell2sym
Convert cell array to symbolic array
Syntax
S = cell2sym(C)
S = cell2sym(C,flag)
Description
S = cell2sym(C) converts a cell array C to a symbolic array S. The elements of C must be
convertible to symbolic objects.
If each element of the input cell array C is a scalar, then size(S) = size(C), and S(k) =
sym(C(k)) for all indices k. If the cell array C contains nonscalar elements, then the contents of C
must support concatenation into an N-dimensional rectangle. Otherwise, the results are undefined.
For example, the contents of cells in the same column must have the same number of columns.
However, they do not need to have the same number of rows. See figure.
S = cell2sym(C,flag) uses the technique specified by flag for converting floating-point numbers
to symbolic numbers.
Examples
S =
7-147
7 Functions
x y z
123
cell2sym does not create symbolic variables x, y, and z in the MATLAB® workspace. To access an
element of S, use parentheses.
S(1,1)
ans = x
Convert a cell array whose elements are scalars, vectors, and matrices into a symbolic array. Such
conversion is possible only if the contents of the cell array can be concatenated into an N-dimensional
rectangle.
Create a cell array, the elements of which are a scalar, a row vector, a column vector, and a matrix.
C = {'x' [2 3 4]; ['y'; sym(9)] [6 7 8; 10 11 12]}
S =
x 2 3 4
y 6 7 8
9 10 11 12
When converting a cell array containing floating-point numbers, you can explicitly specify the
conversion technique.
Create a cell array pi with two elements: the double-precision value of the constant pi and the exact
value pi.
C = {pi,sym(pi)}
Convert this cell array to a symbolic array. By default, cell2sym uses the rational conversion mode.
Thus, results returned by cell2sym without a flag are the same as results returned by cell2sym
with the flag 'r'.
S = cell2sym(C)
7-148
cell2sym
S = π π
S = cell2sym(C,'r')
S = π π
Convert the same cell array to a symbolic array using the flags 'd', 'e', and 'f'. See the “Input
Arguments” on page 7-149 section for the details about conversion techniques.
S = cell2sym(C,'d')
S = 3.1415926535897931159979634685442 π
S = cell2sym(C,'e')
S =
198 eps
π− π
359
S = cell2sym(C,'f')
S =
884279719003555
π
281474976710656
Input Arguments
C — Input cell array
cell array
Input cell array, specified as a cell array. The elements of C must be convertible to symbolic objects.
'r' In the rational mode, cell2sym converts floating-point numbers obtained by evaluating
expressions of the form p/q, p*pi/q, sqrt(p), 2^q, and 10^q for modest sized integers
p and q to the corresponding symbolic form. This approach effectively compensates for
the round-off error involved in the original evaluation, but might not represent the
floating-point value precisely. If cell2sym cannot find simple rational approximation,
then it uses the same technique as it would use with the flag 'f'.
'd' In the decimal mode, cell2sym takes the number of digits from the current setting of
digits. Conversions with fewer than 16 digits lose some accuracy, while more than 16
digits might not be warranted. For example, cell2sym({4/3},'d') with the 10-digit
accuracy returns 1.333333333, while with the 20-digit accuracy it returns
1.3333333333333332593. The latter does not end in 3s, but it is an accurate decimal
representation of the floating-point number nearest to 4/3.
'e' In the estimate error mode, cell2sym supplements a result obtained in the rational
mode by a term involving the variable eps. This term estimates the difference between
the theoretical rational expression and its actual floating-point value. For example,
cell2sym({3*pi/4},'e') returns (3*pi)/4 - (103*eps)/249.
7-149
7 Functions
'f' In the floating-point mode, cell2sym represents all values in the form N*2^e or -N*2^e,
where N >= 0 and e are integers. For example, cell2sym({1/10},'f') returns
3602879701896397/36028797018963968. The returned rational value is the exact
value of the floating-point number that you convert to a symbolic number.
Output Arguments
S — Resulting symbolic array
symbolic array
Version History
Introduced in R2016a
See Also
sym2cell | cell2mat | mat2cell | num2cell
7-150
changeIntegrationVariable
changeIntegrationVariable
Integration by substitution
Syntax
G = changeIntegrationVariable(F,old,new)
Description
G = changeIntegrationVariable(F,old,new) applies integration by substitution to the
integrals in F, in which old is replaced by new. old must depend on the previous integration variable
of the integrals in F and new must depend on the new integration variable. For more information, see
“Integration by Substitution” on page 7-154.
When specifying the integrals in F, you can return the unevaluated form of the integrals by using the
int function with the 'Hold' option set to true. You can then use changeIntegrationVariable
to show the steps of integration by substitution.
Examples
Change of Variable
b
Apply a change of variable to the definite integral ∫a f x + c dx.
syms f(x) y a b c
F = int(f(x+c),a,b)
F =
b
∫a f c + x dx
G = changeIntegrationVariable(F,x+c,y)
G =
b+c
∫a + c f y dy
Integration by Substitution
Define the integral without evaluating it by setting the 'Hold' option to true.
7-151
7 Functions
syms x t
F = int(cos(log(x)),'Hold',true)
F =
∫cos log x dx
G =
∫ et cos t dt
To evaluate the integral in G, use the release function to ignore the 'Hold' option.
H = release(G)
H =
et cos t + sin t
2
H =
π
2 x sin 4 + log x
2
Compare the result to the integration result returned by int without setting the 'Hold' option to
true.
Fcalc = int(cos(log(x)))
Fcalc =
π
2 x sin 4 + log x
2
F =
∫x tan log x dx
The int function cannot find the closed-form solution of the integral.
7-152
changeIntegrationVariable
syms t
G = changeIntegrationVariable(F,log(x),t)
G =
e2 t 2F1 1, − i ; 1 − i ; − e2 t i i 1 1
+ et 2 + 2 i 2F1 1, 1 − i ; 2 − i ; − e2 t i − − i
2 4 4
The closed-form solution is expressed in terms of hypergeometric functions. For more details on
hypergeometric functions, see hypergeom.
1 sin x
Compute the integral ∫0 e dx numerically with high precision.
1 sin x
Define the integral ∫0 e dx. A closed-form solution to the integral does not exist.
syms x
F = int(exp(sqrt(sin(x))),x,0,1)
F =
1
∫0 e sin x dx
You can use vpa to compute the integral numerically to 10 significant digits.
F10 = vpa(F,10)
F10 = 1.944268879
Alternatively, you can use the vpaintegral function and specify the relative error tolerance.
Fvpa = vpaintegral(exp(sqrt(sin(x))),x,0,1,'RelTol',1e-10)
Fvpa = 1.944268879
The vpa function cannot find the numerical integration to 70 significant digits, and it returns the
unevaluated integral in the form of vpaintegral.
F70 = vpa(F,70)
F70 = 1.944268879138581167466225761060083173280747314051712224507065962575967
To find the numerical integration with high precision, you can perform a change of variable.
Substitute the expression sin x with t. Compute the integral numerically to 70 significant digits.
syms t;
G = changeIntegrationVariable(F,sqrt(sin(x)),t)
G =
sin 1 2 t et
∫0 1−t 4
dt
G70 = vpa(G,70)
G70 = 1.944268879138581167466225761060083173280747314051712224507065962575967
7-153
7 Functions
Input Arguments
F — Expression containing integrals
symbolic expression | symbolic function | symbolic vector | symbolic matrix
New subexpression, specified as a symbolic scalar variable, expression, or function. new must depend
on the new integration variable.
More About
Integration by Substitution
∫
a
f (g(x)) g′(x) dx = ∫
g(a)
f (t) dt .
Version History
Introduced in R2019b
See Also
integrateByParts | release | int | diff | vpaintegral
7-154
charpoly
charpoly
Characteristic polynomial of matrix
Syntax
charpoly(A)
charpoly(A,var)
Description
charpoly(A) returns a vector of coefficients of the characteristic polynomial on page 7-156 of A. If A
is a symbolic matrix, charpoly returns a symbolic vector. Otherwise, it returns a vector of double-
precision values.
Examples
A = [1 1 0; 0 1 0; 0 0 1];
charpoly(A)
ans =
1 -3 3 -1
For symbolic input, charpoly returns a symbolic vector instead of double. Repeat the calculation for
symbolic input.
A = sym(A);
charpoly(A)
ans =
[ 1, -3, 3, -1]
syms x
A = sym([1 1 0; 0 1 0; 0 0 1]);
polyA = charpoly(A,x)
polyA =
x^3 - 3*x^2 + 3*x - 1
7-155
7 Functions
eigenA = solve(polyA)
eigenA =
1
1
1
Input Arguments
A — Input
numeric matrix | symbolic matrix
More About
Characteristic Polynomial of Matrix
The characteristic polynomial of an n-by-n matrix A is the polynomial pA(x), defined as follows.
pA x = det xIn − A
Version History
Introduced in R2012b
References
[1] Cohen, H. “A Course in Computational Algebraic Number Theory.” Graduate Texts in Mathematics
(Axler, Sheldon and Ribet, Kenneth A., eds.). Vol. 138, Springer, 1993.
[2] Abdeljaoued, J. “The Berkowitz Algorithm, Maple and Computing the Characteristic Polynomial in
an Arbitrary Commutative Ring.” MapleTech, Vol. 4, Number 3, pp 21–32, Birkhauser, 1997.
See Also
det | eig | jordan | minpoly | poly2sym | sym2poly
7-156
chebyshevT
chebyshevT
Chebyshev polynomials of the first kind
Syntax
chebyshevT(n,x)
Description
chebyshevT(n,x) represents the nth degree Chebyshev polynomial of the first kind on page 7-159
at the point x.
Examples
First Five Chebyshev Polynomials of the First Kind
Find the first five Chebyshev polynomials of the first kind for the variable x.
syms x
chebyshevT([0, 1, 2, 3, 4], x)
ans =
[ 1, x, 2*x^2 - 1, 4*x^3 - 3*x, 8*x^4 - 8*x^2 + 1]
Find the value of the fifth-degree Chebyshev polynomial of the first kind at these points. Because
these numbers are not symbolic objects, chebyshevT returns floating-point results.
ans =
0.7428 0.9531 0.9918 0.5000 -0.4856 -0.8906
Find the value of the fifth-degree Chebyshev polynomial of the first kind for the same numbers
converted to symbolic objects. For symbolic numbers, chebyshevT returns exact symbolic results.
ans =
[ 361/486, 61/64, 241/243, 1/2, -118/243, -57/64]
Find the value of the 500th-degree Chebyshev polynomial of the first kind at 1/3 and vpa(1/3).
Floating-point evaluation is numerically stable.
7-157
7 Functions
chebyshevT(500, 1/3)
chebyshevT(500, vpa(1/3))
ans =
0.9631
ans =
0.963114126817085233778571286718
Now, find the symbolic polynomial T500 = chebyshevT(500, x), and substitute x = vpa(1/3)
into the result. This approach is numerically unstable.
syms x
T500 = chebyshevT(500, x);
subs(T500, x, vpa(1/3))
ans =
-3293905791337500897482813472768.0
Approximate the polynomial coefficients by using vpa, and then substitute x = sym(1/3) into the
result. This approach is also numerically unstable.
subs(vpa(T500), x, sym(1/3))
ans =
1202292431349342132757038366720.0
syms x y
fplot(chebyshevT(0:4,x))
axis([-1.5 1.5 -2 2])
grid on
ylabel('T_n(x)')
legend('T_0(x)','T_1(x)','T_2(x)','T_3(x)','T_4(x)','Location','Best')
title('Chebyshev polynomials of the first kind')
7-158
chebyshevT
Input Arguments
n — Degree of polynomial
nonnegative integer | symbolic variable | symbolic expression | symbolic function | vector | matrix
x — Evaluation point
number | symbolic number | symbolic variable | symbolic expression | symbolic function | vector |
matrix
More About
Chebyshev Polynomials of the First Kind
T 0, x = 1, T 1, x = x, T n, x = 2xT n − 1, x − T n − 2, x
7-159
7 Functions
• Chebyshev polynomials of the first kind are orthogonal on the interval -1 ≤ x ≤ 1 with respect to
1
the weight function w x = .
1 − x2
0 if n ≠ m
1
∫
−1
T(n, x)T(m, x)
1−x 2
dx =
π if n = m = 0
π
if n = m ≠ 0.
2
• Chebyshev polynomials of the first kind are special cases of the Jacobi polynomials
2n 2
2 n! 1 1
T n, x = P n, − , − , x
2n ! 2 2
1 n+a
lim G n, a, x if n ≠ 0
2a 0 a
T n, x =
lim G 0, a, x = 1 if n = 0
a 0
Tips
• chebyshevT returns floating-point results for numeric arguments that are not symbolic objects.
• chebyshevT acts element-wise on nonscalar inputs.
• At least one input argument must be a scalar or both arguments must be vectors or matrices of
the same size. If one input argument is a scalar and the other one is a vector or a matrix, then
chebyshevT expands the scalar into a vector or matrix of the same size as the other argument
with all elements equal to that scalar.
Version History
Introduced in R2014b
References
[1] Hochstrasser, U. W. “Orthogonal Polynomials.” Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New
York: Dover, 1972.
[2] Cohl, Howard S., and Connor MacKenzie. “Generalizations and Specializations of Generating
Functions for Jacobi, Gegenbauer, Chebyshev and Legendre Polynomials with Definite
Integrals.” Journal of Classical Analysis, no. 1 (2013): 17–33. https://doi.org/10.7153/
jca-03-02.
See Also
chebyshevU | gegenbauerC | hermiteH | jacobiP | laguerreL | legendreP
7-160
chebyshevU
chebyshevU
Chebyshev polynomials of the second kind
Syntax
chebyshevU(n,x)
Description
chebyshevU(n,x) represents the nth degree Chebyshev polynomial of the second kind on page 7-
163 at the point x.
Examples
First Five Chebyshev Polynomials of the Second Kind
Find the first five Chebyshev polynomials of the second kind for the variable x.
syms x
chebyshevU([0, 1, 2, 3, 4], x)
ans =
[ 1, 2*x, 4*x^2 - 1, 8*x^3 - 4*x, 16*x^4 - 12*x^2 + 1]
Find the value of the fifth-degree Chebyshev polynomial of the second kind at these points. Because
these numbers are not symbolic objects, chebyshevU returns floating-point results.
ans =
0.8560 0.9465 0.0000 -1.2675 -1.0982
Find the value of the fifth-degree Chebyshev polynomial of the second kind for the same numbers
converted to symbolic objects. For symbolic numbers, chebyshevU returns exact symbolic results.
ans =
[ 208/243, 33/32, 230/243, 0, -308/243, -3432/3125]
Find the value of the 500th-degree Chebyshev polynomial of the second kind at 1/3 and vpa(1/3).
Floating-point evaluation is numerically stable.
7-161
7 Functions
chebyshevU(500, 1/3)
chebyshevU(500, vpa(1/3))
ans =
0.8680
ans =
0.86797529488884242798157148968078
Now, find the symbolic polynomial U500 = chebyshevU(500, x), and substitute x = vpa(1/3)
into the result. This approach is numerically unstable.
syms x
U500 = chebyshevU(500, x);
subs(U500, x, vpa(1/3))
ans =
63080680195950160912110845952.0
Approximate the polynomial coefficients by using vpa, and then substitute x = sym(1/3) into the
result. This approach is also numerically unstable.
subs(vpa(U500), x, sym(1/3))
ans =
-1878009301399851172833781612544.0
syms x y
fplot(chebyshevU(0:4, x))
axis([-1.5 1.5 -2 2])
grid on
ylabel('U_n(x)')
legend('U_0(x)', 'U_1(x)', 'U_2(x)', 'U_3(x)', 'U_4(x)', 'Location', 'Best')
title('Chebyshev polynomials of the second kind')
7-162
chebyshevU
Input Arguments
n — Degree of polynomial
nonnegative integer | symbolic variable | symbolic expression | symbolic function | vector | matrix
x — Evaluation point
number | symbolic number | symbolic variable | symbolic expression | symbolic function | vector |
matrix
More About
Chebyshev Polynomials of the Second Kind
sin n + 1 acos x
U n, x =
sin acos x
7-163
7 Functions
U 0, x = 1, U 1, x = 2x, U n, x = 2xU n − 1, x − U n − 2, x
• Chebyshev polynomials of the second kind are orthogonal on the interval -1 ≤ x ≤ 1 with respect
to the weight function w x = 1 − x2.
1 0 if n ≠ m
∫ U(n, x)U(m, x) 1 − x2 dx = π
if n = m .
−1 2
• Chebyshev polynomials of the second kind are a special case of the Jacobi polynomials
2n
2 n! n + 1 ! 1 1
U n, x = P n, , , x
2n + 1 ! 2 2
U n, x = G n, 1, x
Tips
• chebyshevU returns floating-point results for numeric arguments that are not symbolic objects.
• chebyshevU acts element-wise on nonscalar inputs.
• At least one input argument must be a scalar or both arguments must be vectors or matrices of
the same size. If one input argument is a scalar and the other one is a vector or a matrix, then
chebyshevU expands the scalar into a vector or matrix of the same size as the other argument
with all elements equal to that scalar.
Version History
Introduced in R2014b
References
[1] Hochstrasser, U. W. “Orthogonal Polynomials.” Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New
York: Dover, 1972.
[2] Cohl, Howard S., and Connor MacKenzie. “Generalizations and Specializations of Generating
Functions for Jacobi, Gegenbauer, Chebyshev and Legendre Polynomials with Definite
Integrals.” Journal of Classical Analysis, no. 1 (2013): 17–33. https://doi.org/10.7153/
jca-03-02.
See Also
chebyshevT | gegenbauerC | hermiteH | jacobiP | laguerreL | legendreP
7-164
checkUnits
checkUnits
Check for compatible dimensions and consistent units
Syntax
C = checkUnits(expr)
C = checkUnits(expr,'Compatible')
C = checkUnits(expr,'Consistent')
Description
C = checkUnits(expr) checks expr for compatible dimensions and consistent units and returns a
structure containing the fields Consistent and Compatible. The fields contain logical 0 (false) or
logical 1 (true) depending on the check results.
expr has compatible dimensions if all terms have the same dimensions, such as length or time. expr
has consistent units if all units of the same dimension can be converted to each other with a
conversion factor of 1.
Examples
Check the dimensions of an equation or expression. The dimensions are checked to confirm that the
equation or expression is valid.
m kg
A =B
s s
by using checkUnits with the option 'Compatible'. MATLAB® assumes that symbolic variables
are dimensionless. The checkUnits function returns logical 0 (false) because the dimensions of
the equation are not compatible.
u = symunit;
syms A B
eqn = A*u.m/u.s == B*u.kg/u.s;
checkUnits(eqn,'Compatible')
ans = logical
0
Replace u.kg with u.m by using subs and repeat the check. Because the dimensions are now
compatible, checkUnits returns logical 1 (true).
7-165
7 Functions
eqn = subs(eqn,u.kg,u.m);
checkUnits(eqn,'Compatible')
ans = logical
1
Checking units for consistency is a stronger check than compatibility. Units are consistent when all
units of the same dimension can be converted to each other with a conversion factor of 1. For
example, 1 Newton is consistent with 1 kg m/s² but not with 1 kg cm/s².
Show that 1 Newton is consistent with 1 kg m/s² by checking expr1 but not with 1 kg cm/s² by
checking expr2.
u = symunit;
expr1 = 1*u.N + 1*u.kg*u.m/u.s^2;
expr2 = 1*u.N + 1*u.kg*u.cm/u.s^2;
checkUnits(expr1,'Consistent')
ans = logical
1
checkUnits(expr2,'Consistent')
ans = logical
0
Show the difference between compatibility and consistency by showing that expr2 has compatible
dimensions but not consistent units.
checkUnits(expr2,'Compatible')
ans = logical
1
Check multiple equations or expressions by placing them in an array. checkUnits returns an array
whose elements correspond to the elements of the input.
Check multiple equations for compatible dimensions. checkUnits returns [1 0], meaning that the
first equation has compatible dimensions while the second equation does not.
u = symunit;
syms x y z
eqn1 = x*u.m == y*u.m^2/(z*u.m);
eqn2 = x*u.m + y*u.s == z*u.m;
7-166
checkUnits
1 0
Check for both compatible dimensions and consistent units of the equation or expression by using
checkUnits.
Define the equations for x- and y-displacement of a moving projectile. Check their units for
compatibility and consistency.
u = symunit;
syms theta x y ts
g = 9.81*u.cm/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;
S = checkUnits([x y])
The second equation has compatible dimensions but inconsistent units. This inconsistency is because
g incorrectly uses cm instead of m. Redefine g and check the equations again. The second equation
now has consistent units.
g = 9.81*u.m/u.s^2;
y = v*sin(theta)*t + (-g*t^2)/2;
S = checkUnits([x y])
Input Arguments
expr — Input expression
symbolic expression | symbolic equation | symbolic function | symbolic vector | symbolic matrix |
symbolic multidimensional array
7-167
7 Functions
Version History
Introduced in R2017a
See Also
findUnits | isUnit | newUnit | separateUnits | symunit | str2symunit | symunit2str |
unitConversionFactor
Topics
“Units of Measurement Tutorial” on page 2-47
“Unit Conversions and Unit Systems” on page 2-53
“Units and Unit Systems List” on page 2-60
7-168
children
children
Subexpressions or terms of symbolic expression
Note Starting in R2020b, the syntax subexpr = children(expr) for a scalar input expr returns
subexpr as a nonnested cell array instead of a vector. You can use subexpr =
children(expr,ind) to index into the returned cell array of subexpressions. For more information,
see “Compatibility Considerations”.
Syntax
subexpr = children(expr)
subexpr = children(A)
subexpr = children( ___ ,ind)
Description
subexpr = children(expr) returns a nonnested cell array containing the child subexpressions of
the symbolic expression expr. For example, the child subexpressions of a sum are its terms.
subexpr = children(A) returns a nested cell array containing the child subexpressions of each
expression in the symbolic matrix A.
subexpr = children( ___ ,ind) returns the child subexpressions of a symbolic expression expr
or a symbolic matrix A as a cell array indexed by ind.
Examples
Find the child subexpressions of the symbolic expression x2 + xy + y2. The subexpressions are
returned in a nonnested cell array. children uses internal sorting rules when returning the
subexpressions. You can index into each element of the cell array by using subexpr{i}, where i is
the cell index. The child subexpressions of a sum are its terms.
syms x y
subexpr = children(x^2 + x*y + y^2)
s1 = subexpr{1}
s1 = x y
s2 = subexpr{2}
s2 = x2
7-169
7 Functions
s3 = subexpr{3}
s3 = y2
You can also index into each element of the subexpressions by specifying the index ind in the
children function.
s1 = x y
s2 = x2
s3 = y2
To convert the cell array of subexpressions into a vector, you can use the command [subexpr{:}].
V = [subexpr{:}]
V = x y x2 y2
Find the child subexpressions of the equation x2 + xy = y2 + 1. The child subexpressions of the
equation are returned in a 1-by-2 cell array. Index into all elements of the cell array. The
subexpressions of an equation are the left and right sides of that equation.
syms x y
subexpr = children(x^2 + x*y == y^2 + 1)
subexpr{:}
ans = x2 + y x
ans = y2 + 1
Next, find the child subexpressions of the inequality sin(x) < cos(x). Index into all elements of the
returned cell array. The child subexpressions of an inequality are the left and right sides of that
inequality.
subexpr{:}
7-170
children
ans = sin x
ans = cos x
∫
b
Find the child subexpressions of an integral f (x) dx. The child subexpressions are returned as a
a
cell array of symbolic expressions.
syms f(x) a b
subexpr = children(int(f(x),a,b))
V = [subexpr{:}]
V = f x xa b
syms x
t = taylor(cos(x),x,2)
t =
3 5 2 4
sin 2 x − 2 sin 2 x − 2 cos 2 x − 2 cos 2 x − 2
cos 2 + − − sin 2 x − 2 − +
6 120 2 24
The Taylor expansion has six terms that are separated by + or – sign.
Plot the cos(x) function. Use children to separate out the terms of the expansion. Show that the
Taylor expansion approximates the function more closely as more terms are included.
fplot(cos(x),[0 4])
hold on
s = 0;
for i = 1:6
s = s + children(t,i);
fplot(s,[0 4],'--')
end
legend({'cos(x)','1 term','2 terms','3 terms','4 terms','5 terms','6 terms'})
7-171
7 Functions
Call the children function to find the child subexpressions of the following symbolic matrix input.
The result is a 2-by-2 nested cell array containing the child subexpressions of each element of the
matrix.
syms x y
symM = [x + y, sin(x)*cos(y); x^3 - y^3, exp(x*y^2) + 3]
symM =
x + y cos y sin x
2
x3 − y3 ex y +3
s = children(symM)
To unnest or access the elements of the nested cell array s, use braces. For example, the {1,1}-
element of s is a 1-by-2 cell array of symbolic expressions.
s11 = s{1,1}
7-172
children
Unnest each element of s using braces. Convert the nonnested cell arrays to vectors using square
brackets.
s11vec = [s{1,1}{:}]
s11vec = x y
s21vec = [s{2,1}{:}]
s21vec = x3 −y3
s12vec = [s{1,2}{:}]
s22vec = [s{2,2}{:}]
s22vec = ex y2 3
If each element of the nested cell array s contains a nonnested cell array of the same size, then you
can also use the ind input argument to access the elements of the nested cell array. The index ind
allows children to access each column of subexpressions of the symbolic matrix input symM.
scol1 = children(symM,1)
[scol1{:}].'
ans =
x
x3
cos y
2
ex y
scol2 = children(symM,2)
[scol2{:}].'
ans =
y
−y3
sin x
3
7-173
7 Functions
Input Arguments
expr — Input expression
symbolic number | symbolic variable | symbolic function | symbolic expression
A — Input matrix
symbolic matrix
• If children(expr) returns a nonnested cell array of child subexpressions, then indexing with
children(expr,ind) returns the ind-th element of the cell array.
• If children(A) returns a nested cell array of child subexpressions, where each cell element has
the same size, then indexing with children(A,ind) returns the ind-th column of the nonnested
cell array.
Version History
Introduced in R2012a
In versions before R2020b, the syntax subexpr = children(expr) returns a vector subexpr that
contains the child subexpressions of the scalar symbolic expression expr. The syntax subexpr =
children(A) returns a nonnested cell array subexpr that contains the child subexpressions of the
symbolic matrix A.
Starting in R2020b, the syntax subexpr = children(expr) returns subexpr as a cell array
instead of a vector, and the syntax subexpr = children(A) returns subexpr as a nested cell array
instead of a nonnested cell array. You can use subexpr = children(expr,ind) to index into the
returned cell arrays of subexpressions. For example, see “Plot Taylor Approximation of Expression”
on page 7-171. You can also unnest and access the elements of a cell array by indexing into the cell
array using curly braces. To convert subexpr from a nonnested cell array to a vector, you can use the
command [subexpr{:}].
See Also
coeffs | lhs | numden | rhs | subs
Topics
“Create Symbolic Numbers, Variables, and Expressions” on page 1-3
7-174
chol
chol
Cholesky factorization
Syntax
T = chol(A)
[T,p] = chol(A)
[T,p,S] = chol(A)
[T,p,s] = chol(A,'vector')
___ = chol(A,'lower')
___ = chol(A,'nocheck')
___ = chol(A,'real')
___ = chol(A,'lower','nocheck','real')
[T,p,s] = chol(A,'lower','vector','nocheck','real')
Description
T = chol(A) returns an upper triangular matrix T, such that T'*T = A. A must be a Hermitian
positive definite matrix on page 7-180. Otherwise, this syntax throws an error.
[T,p] = chol(A) computes the Cholesky factorization on page 7-180 of A. This syntax does not
error if A is not a Hermitian positive definite matrix. If A is a Hermitian positive definite matrix, then
p is 0. Otherwise, T is sym([]), and p is a positive integer (typically, p = 1).
[T,p,S] = chol(A) returns a permutation matrix S, such that T'*T = S'*A*S, and the value p =
0 if matrix A is Hermitian positive definite. Otherwise, it returns a positive integer p and an empty
object S = sym([]).
___ = chol(A,'real') computes the Cholesky factorization of A using real arithmetic. In this
case, chol computes a symmetric factorization A = T.'*T instead of a Hermitian factorization A =
T'*T. This approach is based on the fact that if A is real and symmetric, then T'*T = T.'*T. Use
'real' to avoid complex conjugates in the result.
7-175
7 Functions
Examples
Compute Cholesky Factorization of Numeric and Symbolic Matrices
Compute the Cholesky factorization of the 3-by-3 Hilbert matrix. Because these numbers are not
symbolic objects, you get floating-point results.
chol(hilb(3))
ans =
1.0000 0.5000 0.3333
0 0.2887 0.2887
0 0 0.0745
Now convert this matrix to a symbolic object, and compute the Cholesky factorization:
chol(sym(hilb(3)))
ans =
[ 1, 1/2, 1/3]
[ 0, 3^(1/2)/6, 3^(1/2)/6]
[ 0, 0, 5^(1/2)/30]
Compute the Cholesky factorization of the 3-by-3 Pascal matrix returning a lower triangular matrix as
a result:
chol(sym(pascal(3)), 'lower')
ans =
[ 1, 0, 0]
[ 1, 1, 0]
[ 1, 2, 1]
Try to compute the Cholesky factorization of this matrix. Because this matrix is not Hermitian
positive definite, chol used without output arguments or with one output argument throws an error:
A = sym([1 1 1; 1 2 3; 1 3 5]);
T = chol(A)
To suppress the error, use two output arguments, T and p. If the matrix is not recognized as
Hermitian positive definite, then this syntax assigns an empty symbolic object to T and the value 1 to
p:
[T,p] = chol(A)
T =
[ empty sym ]
7-176
chol
p =
1
[T,p] = chol(sym(pascal(3)))
T =
[ 1, 1, 1]
[ 0, 1, 2]
[ 0, 0, 1]
p =
0
Alternatively, 'nocheck' lets you skip checking whether A is a Hermitian positive definite matrix.
Thus, this flag lets you compute the Cholesky factorization of a symbolic matrix without setting
additional assumptions on its components to make it Hermitian positive definite:
syms a
A = [a 0; 0 a];
chol(A,'nocheck')
ans =
[ a^(1/2), 0]
[ 0, a^(1/2)]
If you use 'nocheck' for computing the Cholesky factorization of a matrix that is not Hermitian
positive definite, chol can return a matrix T for which the identity T'*T = A does not hold. To make
isAlways return logical 0 (false) for undecidable conditions, set Unknown to false.
T =
[ 1, 2]
[ 0, 3^(1/2)*1i]
isAlways(A == T'*T,'Unknown','false')
ans =
2×2 logical array
0 0
0 0
Compute the Cholesky factorization of the 3-by-3 inverse Hilbert matrix returning the permutation
matrix:
A = sym(invhilb(3));
[T, p, S] = chol(A)
T =
[ 3, -12, 10]
[ 0, 4*3^(1/2), -5*3^(1/2)]
[ 0, 0, 5^(1/2)]
p =
0
7-177
7 Functions
S =
1 0 0
0 1 0
0 0 1
Compute the Cholesky factorization of the 3-by-3 inverse Hilbert matrix returning the permutation
information as a vector:
A = sym(invhilb(3));
[T, p, S] = chol(A, 'vector')
T =
[ 3, -12, 10]
[ 0, 4*3^(1/2), -5*3^(1/2)]
[ 0, 0, 5^(1/2)]
p =
0
S =
1 2 3
Compute the Cholesky factorization of matrix A containing symbolic parameters. Without additional
assumptions on the parameter a, this matrix is not Hermitian. To make isAlways return logical 0
(false) for undecidable conditions, set Unknown to false.
syms a
A = [a 0; 0 a];
isAlways(A == A','Unknown','false')
ans =
2×2 logical array
0 1
1 0
By setting assumptions on a and b, you can define A to be Hermitian positive definite. Therefore, you
can compute the Cholesky factorization of A:
assume(a > 0)
chol(A)
ans =
[ a^(1/2), 0]
[ 0, a^(1/2)]
syms a
Compute the Cholesky factorization of this matrix. To skip checking whether it is Hermitian positive
definite, use 'nocheck'. By default, chol computes a Hermitian factorization A = T'*T. Thus, the
result contains complex conjugates.
7-178
chol
syms a b
A = [a b; b a];
T = chol(A, 'nocheck')
T =
[ a^(1/2), conj(b)/conj(a^(1/2))]
[ 0, (a*abs(a) - abs(b)^2)^(1/2)/abs(a)^(1/2)]
T =
[ a^(1/2), b/a^(1/2)]
[ 0, ((a^2 - b^2)/a)^(1/2)]
When you use this flag, chol computes a symmetric factorization A = T.'*T instead of a Hermitian
factorization A = T'*T. To make isAlways return logical 0 (false) for undecidable conditions, set
Unknown to false.
isAlways(A == T.'*T)
ans =
2×2 logical array
1 1
1 1
isAlways(A == T'*T,'Unknown','false')
ans =
2×2 logical array
0 0
0 0
Input Arguments
A — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
Output Arguments
T — Upper triangular matrix
symbolic matrix
Upper triangular matrix, returned as a symbolic matrix such that T'*T = A. If T is a lower triangular
matrix, then T*T' = A.
p — Output
symbolic number
Flag, returned as a symbolic number. Value 0 if A is Hermitian positive definite or if you use
'nocheck'.
7-179
7 Functions
If chol does not identify A as a Hermitian positive definite matrix, then p is a positive integer. R is an
upper triangular matrix of order q = p - 1, such that R'*R = A(1:q,1:q).
S — Permutation matrix
symbolic matrix
s — Permutation vector
symbolic vector
Limitations
Matrix computations involving many symbolic variables can be slow. To increase the computational
speed, reduce the number of symbolic variables by substituting the given values for some variables.
More About
Hermitian Positive Definite Matrix
A square complex matrix A is Hermitian positive definite if v'*A*v is real and positive for all nonzero
complex vectors v, where v' is the conjugate transpose (Hermitian transpose) of v.
The Cholesky factorization of a Hermitian positive definite n-by-n matrix A is defined by an upper or
lower triangular matrix with positive entries on the main diagonal. The Cholesky factorization of
matrix A can be defined as T'*T = A, where T is an upper triangular matrix. Here T' is the
conjugate transpose of T. The Cholesky factorization also can be defined as T*T' = A, where T is a
lower triangular matrix. T is called the Cholesky factor of A.
Tips
• Calling chol for numeric arguments that are not symbolic objects invokes the MATLAB chol
function.
• If you use 'nocheck', then the identities T'*T = A (for an upper triangular matrix T) and T*T'
= A (for a lower triangular matrix T) are not guaranteed to hold.
• If you use 'real', then the identities T'*T = A (for an upper triangular matrix T) and T*T' = A
(for a lower triangular matrix T) are only guaranteed to hold for a real symmetric positive definite
A.
• To use 'vector', you must specify three output arguments. Other flags do not require a
particular number of output arguments.
• If you use 'matrix' instead of 'vector', then chol returns permutation matrices, as it does by
default.
• If you use 'upper' instead of 'lower', then chol returns an upper triangular matrix, as it does
by default.
• If A is not a Hermitian positive definite matrix, then the syntaxes containing the argument p
typically return p = 1 and an empty symbolic object T.
7-180
chol
• To check whether a matrix is Hermitian, use the operator ' (or its functional form ctranspose).
Matrix A is Hermitian if and only if A'= A, where A' is the conjugate transpose of A.
Version History
Introduced in R2013a
See Also
chol | ctranspose | eig | isAlways | lu | qr | svd | transpose | vpa
7-181
7 Functions
coeffs
Coefficients of polynomial
Syntax
C = coeffs(p)
C = coeffs(p,var)
C = coeffs(p,vars)
[C,T] = coeffs( ___ )
___ = coeffs( ___ ,'All')
Description
C = coeffs(p) returns coefficients of the polynomial p with respect to all variables determined in p
by symvar.
C = coeffs(p,var) returns coefficients of the polynomial p with respect to the variable var.
[C,T] = coeffs( ___ ) returns the coefficient C and the corresponding terms T of the polynomial
p.
___ = coeffs( ___ ,'All') returns all coefficients, including coefficients that are 0. For
example, coeffs(2*x^2,'All') returns [ 2, 0, 0] instead of 2.
Examples
Coefficients of Univariate Polynomial
Find the coefficients of this univariate polynomial. The coefficients are ordered from the lowest
degree to the highest degree.
syms x
c = coeffs(16*x^2 + 19*x + 11)
c =
[ 11, 19, 16]
c = fliplr(c)
c =
[ 16, 19, 11]
Find the coefficients of this polynomial with respect to variable x and variable y.
7-182
coeffs
syms x y
cx = coeffs(x^3 + 2*x^2*y + 3*x*y^2 + 4*y^3, x)
cy = coeffs(x^3 + 2*x^2*y + 3*x*y^2 + 4*y^3, y)
cx =
[ 4*y^3, 3*y^2, 2*y, 1]
cy =
[ x^3, 2*x^2, 3*x, 4]
Find the coefficients of this polynomial with respect to both variables x and y.
syms x y
cxy = coeffs(x^3 + 2*x^2*y + 3*x*y^2 + 4*y^3, [x y])
cyx = coeffs(x^3 + 2*x^2*y + 3*x*y^2 + 4*y^3, [y x])
cxy =
[ 4, 3, 2, 1]
cyx =
[ 1, 2, 3, 4]
Find the coefficients and the corresponding terms of this univariate polynomial. When two outputs
are provided, the coefficients are ordered from the highest degree to the lowest degree.
syms x
[c,t] = coeffs(16*x^2 + 19*x + 11)
c =
[ 16, 19, 11]
t =
[ x^2, x, 1]
Find the coefficients and the corresponding terms of this polynomial with respect to variable x and
variable y.
syms x y
[cx,tx] = coeffs(x^3 + 2*x^2*y + 3*x*y^2 + 4*y^3, x)
[cy,ty] = coeffs(x^3 + 2*x^2*y + 3*x*y^2 + 4*y^3, y)
cx =
[ 1, 2*y, 3*y^2, 4*y^3]
tx =
[ x^3, x^2, x, 1]
cy =
[ 4, 3*x, 2*x^2, x^3]
ty =
[ y^3, y^2, y, 1]
7-183
7 Functions
Find the coefficients of this polynomial with respect to both variables x and y.
syms x y
[cxy, txy] = coeffs(x^3 + 2*x^2*y + 3*x*y^2 + 4*y^3, [x,y])
[cyx, tyx] = coeffs(x^3 + 2*x^2*y + 3*x*y^2 + 4*y^3, [y,x])
cxy =
[ 1, 2, 3, 4]
txy =
[ x^3, x^2*y, x*y^2, y^3]
cyx =
[ 4, 3, 2, 1]
tyx =
[ y^3, x*y^2, x^2*y, x^3]
Find all coefficients of a polynomial, including coefficients that are 0, by specifying the option 'All'.
The returned coefficients are ordered from the highest degree to the lowest degree.
syms x
c = coeffs(3*x^2, 'All')
c =
[ 3, 0, 0]
If you find coefficients with respect to multiple variables and specify 'All', then coeffs returns
coefficients for all combinations of the variables.
syms a b y
[cxy, txy] = coeffs(a*x^2 + b*y, [y x], 'All')
cxy =
[ 0, 0, b]
[ a, 0, 0]
txy =
[ x^2*y, x*y, y]
[ x^2, x, 1]
Input Arguments
p — Polynomial
symbolic expression | symbolic function
7-184
coeffs
Output Arguments
C — Coefficients of polynomial
symbolic number | symbolic variable | symbolic expression | symbolic vector | symbolic matrix |
symbolic multidimensional array
T — Terms of polynomial
symbolic number | symbolic variable | symbolic expression | symbolic vector | symbolic matrix |
symbolic multidimensional array
Version History
Introduced before R2006a
See Also
poly2sym | sym2poly
7-185
7 Functions
collect
Collect coefficients
Syntax
collect(P)
collect(P,expr)
Description
collect(P) collects coefficients in P of the powers of the default variable of P. The default variable
is found by symvar.
Examples
Collect Coefficients of Powers of Default Variable
syms x
coeffs = collect((exp(x) + x)*(x + 2))
coeffs =
x^2 + (exp(x) + 2)*x + 2*exp(x)
Because you did not specify the variable, collect uses the default variable defined by symvar. For
this expression, the default variable is x.
ans =
x
Collect coefficients of a particular variable by specifying the variable as the second argument to
collect.
syms x y
coeffs_x = collect(x^2*y + y*x - x^2 - 2*x,x)
coeffs_y = collect(x^2*y + y*x - x^2 - 2*x,y)
coeffs_x =
(y - 1)*x^2 + (y - 2)*x
coeffs_y =
(x^2 + x)*y - x^2 - 2*x
7-186
collect
Collect coefficients in powers of both x and y by specifying the second argument as a vector of
variables.
syms a b
coeffs_xy = collect(a^2*x*y + a*b*x^2 + a*x*y + x^2,[x y])
coeffs_xy =
(a*b + 1)*x^2 + (a^2 + a)*x*y
coeffs_i =
(2*x - 3*y)*1i
coeffs_pi =
x*pi^2 + (x + 3*y - x*y)*pi + x*1i
Collect coefficients of expressions and functions by specifying the second argument as an expression
or function. Collect coefficients of multiple expressions or functions by using vector input.
Expand sin(x + 3*y) and collect coefficients of cos(y), and then of both sin(x) and sin(y).
syms x y
f = expand(sin(x + 3*y));
coeffs_cosy = collect(f,cos(y))
coeffs_cosy =
4*sin(x)*cos(y)^3 + 4*cos(x)*sin(y)*cos(y)^2 + (-3*sin(x))*cos(y) - cos(x)*sin(y)
coeffs_sinxsiny =
(4*cos(y)^3 - 3*cos(y))*sin(x) + (4*cos(x)*cos(y)^2 - cos(x))*sin(y)
coeffs_y(x) =
x*y(x)^2 + (x + sin(x) + x^2)*y(x)
ans =
[ (y + 1)*x + y + 1, 2*x^2 - y*x]
[ (2*y - 1)*x, (y + 1/y)*x]
7-187
7 Functions
Collect coefficients of calls to a particular function by specifying the function name as the second
argument. Collect coefficients of function calls with respect to multiple functions by specifying the
multiple functions as a cell array of character vectors.
Collect coefficients of calls to the sin function in F, where F contains multiple calls to different
functions.
syms a b c d e f x
F = a*sin(2*x) + b*sin(2*x) + c*cos(x) + d*cos(x) + e*sin(3*x) + f*sin(3*x);
collect(F,'sin')
ans =
(a + b)*sin(2*x) + (e + f)*sin(3*x) + c*cos(x) + d*cos(x)
collect(F,{'sin' 'cos'})
ans =
(a + b)*sin(2*x) + (e + f)*sin(3*x) + (c + d)*cos(x)
Input Arguments
P — Input expression
symbolic expression | symbolic function | symbolic vector | symbolic matrix
Expression in terms of which you collect the coefficients, specified as a symbolic number, variable,
expression, function, or vector; a character vector; a cell array of character vectors.
Example: i, pi, x, sin(x), y(x), [sin(x) cos(y)], {'sin' 'cos'}.
Tips
• collect returns an output that is syntactically different from the input expression (although the
input and output expressions might look the same). For this reason, functions like isequal might
not return true when checking for equality. Instead, use isAlways to prove equivalence between
the input and output expressions.
Version History
Introduced before R2006a
See Also
combine | expand | factor | horner | numden | rewrite | simplify | simplifyFraction |
symvar
7-188
collect
Topics
“Choose Function to Rearrange Expression” on page 3-119
7-189
7 Functions
colon, :
Create symbolic vectors, array subscripting, and for-loop iterators
Syntax
m:n
m:d:n
x:x+r
x:d:x+r
Description
m:n returns a symbolic vector of values [m,m+1,...,n], where m and n are symbolic constants. If n
is not an increment of m, then the last value of the vector stops before n. This behavior holds for all
syntaxes.
x:x+r returns a symbolic vector of values [x,x+1,...,x+r], where x is a symbolic variable and r
is a rational number.
x:d:x+r returns a symbolic vector of values [x,x+d,...,x+r], where d and r are rational
numbers.
Examples
Create Numeric and Symbolic Arrays
Use the colon operator to create numeric and symbolic arrays. Because these inputs are not symbolic
objects, you receive floating-point results.
1/2:7/2
ans =
0.5000 1.5000 2.5000 3.5000
sym(1/2):sym(7/2)
ans =
[ 1/2, 3/2, 5/2, 7/2]
sym(1/2):2/3:sym(7/2)
ans =
[ 1/2, 7/6, 11/6, 5/2, 19/6]
7-190
colon, :
syms x
x:x+2
ans =
[ x, x + 1, x + 2]
syms x
x:3/7:x+2
ans =
[ x, x + 3/7, x + 6/7, x + 9/7, x + 12/7]
syms x
x:x/3:2*x
ans =
[ x, (4*x)/3, (5*x)/3, 2*x]
Find the product of the first four terms of the harmonic series.
syms x
p = sym(1);
for i = x:x+3
p = p*1/i;
end
p
p =
1/(x*(x + 1)*(x + 2)*(x + 3))
expand(p)
ans =
1/(x^4 + 6*x^3 + 11*x^2 + 6*x)
p = subs(p,x,1)
p =
1/24
vpa(p)
ans =
0.041666666666666666666666666666667
You can also perform the described operations in a single line of code.
7-191
7 Functions
ans =
0.041666666666666666666666666666667
Input Arguments
m — Input
symbolic constant
n — Input
symbolic constant
x — Input
symbolic variable
Upper bound on vector values, specified as a symbolic rational. For example, x:x+2 returns [ x, x
+ 1, x + 2].
Increment in vector values, specified as a symbolic rational. For example, x:1/2:x+2 returns [ x,
x + 1/2, x + 1, x + 3/2, x + 2].
Version History
Introduced before R2006a
See Also
reshape
7-192
colspace
colspace
Basis for column space of matrix
Syntax
colspace(A)
Description
colspace(A) returns a symbolic matrix whose columns form a basis for the column space of the
symbolic matrix A.
Examples
B =
[ 1, 0]
[ 0, 1]
[ -15/8, 5/4]
Input Arguments
A — Input
symbolic matrix
Version History
Introduced before R2006a
See Also
null
7-193
7 Functions
combine
Combine terms of identical algebraic structure
Syntax
Y = combine(S)
Y = combine(S,T)
Y = combine( ___ ,'IgnoreAnalyticConstraints',true)
Description
Y = combine(S) rewrites products of powers in the expression S as a single power.
Y = combine(S,T) combines multiple calls to the target function T in the expression S. Use
combine to implement the inverse functionality of expand with respect to the majority of the applied
rules.
Examples
Powers of the Same Base
syms x y z
combine(x^y*x^z)
ans =
x^(y + z)
Combine powers of numeric arguments. To prevent MATLAB from evaluating the expression, use sym
to convert at least one numeric argument into a symbolic value.
syms x y
combine(x^(3)*x^y*x^exp(sym(1)))
ans =
x^(y + exp(1) + 3)
Here, sym converts 1 into a symbolic value, preventing MATLAB from evaluating the expression e1.
combine(sqrt(sym(2))*sqrt(3))
ans =
6^(1/2)
7-194
combine
combine does not usually combine the powers because the internal simplifier applies the same rules
in the opposite direction to expand the result.
syms x y
combine(y^5*x^5)
ans =
x^5*y^5
Combine terms with logarithms by specifying the target argument as log. For real positive numbers,
the logarithm of a product equals the sum of the logarithms of its factors.
S = log(sym(2)) + log(sym(3));
combine(S,'log')
ans =
log(6)
Try combining log(a) + log(b). Because a and b are assumed to be complex numbers by default,
the rule does not hold and combine does not combine the terms.
syms a b
S = log(a) + log(b);
combine(S,'log')
ans =
log(a) + log(b)
Apply the rule by setting assumptions such that a and b satisfy the conditions for the rule.
assume(a > 0)
assume(b > 0)
S = log(a) + log(b);
combine(S,'log')
ans =
log(a*b)
For future computations, clear the assumptions set on variables a and b by recreating them using
syms.
syms a b
syms a b
S = log(a) + log(b);
combine(S,'log','IgnoreAnalyticConstraints',true)
ans =
log(a*b)
Rewrite products of sine and cosine functions as a sum of the functions by setting the target
argument to sincos.
7-195
7 Functions
syms a b
combine(sin(a)*cos(b) + sin(b)^2,'sincos')
ans =
sin(a + b)/2 - cos(2*b)/2 + sin(a - b)/2 + 1/2
Rewrite sums of sine and cosine functions by setting the target argument to sincos.
combine(cos(a) + sin(a),'sincos')
ans =
2^(1/2)*cos(a - pi/4)
combine(cos(a)^2,'sincos')
ans =
cos(2*a)/2 + 1/2
combine does not rewrite powers of sine or cosine functions with negative integer exponents.
syms a b
combine(sin(b)^(-2)*cos(b)^(-2),'sincos')
ans =
1/(cos(b)^2*sin(b)^2)
Exponential Terms
combine(exp(sym(3))*exp(sym(2)),'exp')
ans =
exp(5)
syms a
combine(exp(a)^3, 'exp')
ans =
exp(3*a)
ans =
int(f(x) + g(x), x)
ans =
int(a*f(x), x)
syms a b h(z)
combine(int(f(x),x,a,b)+int(h(z),z,a,b),'int')
7-196
combine
ans =
int(f(x) + h(x), x, a, b)
Combine two calls to the inverse tangent function by specifying the target argument as atan.
syms a b
assume(-1 < a < 1)
assume(-1 < b < 1)
combine(atan(a) + atan(b),'atan')
ans =
-atan((a + b)/(a*b - 1))
Combine two calls to the inverse tangent function. combine simplifies the expression to a symbolic
value if possible.
assume(a > 0)
combine(atan(a) + atan(1/a),'atan')
ans =
pi/2
syms a b
syms x
combine(gamma(x)*gamma(1-x),'gamma')
ans =
-pi/sin(pi*(x - 1))
Evaluate multiple expressions in one function call by using a symbolic matrix as the input parameter.
S = [sqrt(sym(2))*sqrt(5), sqrt(2)*sqrt(sym(11))];
combine(S)
ans =
[ 10^(1/2), 22^(1/2)]
Input Arguments
S — Input expression
symbolic expression | symbolic vector | symbolic matrix | symbolic function
7-197
7 Functions
T — Target function
'atan' | 'exp' | 'gamma' | 'int' | 'log' | 'sincos' | 'sinhcosh'
Target function, specified as 'atan', 'exp', 'gamma', 'int', 'log', 'sincos', or 'sinhcosh'.
The rewriting rules apply only to calls to the target function.
Output Arguments
Y — Expression with combined functions
symbolic variable | symbolic number | symbolic expression | symbolic vector | symbolic matrix
Expression with the combined functions, returned as a symbolic variable, number, expression, or as a
vector or matrix of symbolic variables, numbers, or expressions.
Algorithms
combine applies the following rewriting rules to the input expression S, depending on the value of
the target argument T.
eaeb = ea + b
b
(ea) = eab .
• When T = 'log',
If b < 1000,
blog(a) = log ab .
When b >= 1000, combine does not apply this second rule.
The rules applied to rewrite logarithms do not hold for arbitrary complex values of a and b.
Specify appropriate properties for a or b to enable these rewriting rules.
• When T = 'int',
a ∫ f x dx = ∫af x dx
∫ f x dx + ∫g x dx = ∫ f x + g x dx
∫ ∫ g x dx = ∫
b b b
f x dx + f x + g x dx
a a a
∫ ∫ g y dy = ∫
b b b
f x dx + f y + g y dy
a a a
7-198
combine
∫ yf x dx + ∫ xg y dy = ∫ yf c + xg c dc .
b b b
a a a
• When T = 'sincos',
cos x − y cos x + y
sin x sin y = − .
2 2
B2 −B
Acos x + Bsin x = A 1 + cos x + tan−1 .
A 2 A
• When T = 'atan' and -1 < x < 1, -1 < y < 1,
x+y
atan x + atan y = atan .
1 − xy
• When T = 'sinhcosh',
cosh x + y cosh(x − y)
sinh x sinh y = − .
2 2
combine applies the previous rules recursively to powers of sinh and cosh with positive integral
exponents.
• When T = 'gamma',
aΓ a = Γ a + 1 .
and,
Γ a+1
= a.
Γa
π
Γ −a Γ a = − .
sin πa
Version History
Introduced in R2014a
See Also
Functions
collect | expand | factor | horner | numden | rewrite | simplifyFraction | simplify
Topics
“Choose Function to Rearrange Expression” on page 3-119
7-199
7 Functions
7-200
compose
compose
Functional composition
Syntax
compose(f,g)
compose(f,g,z)
compose(f,g,x,z)
compose(f,g,x,y,z)
Description
compose(f,g) returns f(g(y)) where f = f(x) and g = g(y). Here x is the symbolic variable of
f as defined by symvar and y is the symbolic variable of g as defined by symvar.
compose(f,g,z) returns f(g(z)) where f = f(x), g = g(y), and x and y are the symbolic
variables of f and g as defined by symvar.
compose(f,g,x,z) returns f(g(z)) and makes x the independent variable for f. That is, if f =
cos(x/t), then compose(f,g,x,z) returns cos(g(z)/t) whereas compose(f,g,t,z) returns
cos(x/g(z)).
compose(f,g,x,y,z) returns f(g(z)) and makes x the independent variable for f and y the
independent variable for g. For f = cos(x/t) and g = sin(y/u), compose(f,g,x,y,z) returns
cos(sin(z/u)/t) whereas compose(f,g,x,u,z) returns cos(sin(y/z)/t).
Examples
Declare functions.
syms x y z t u
f = 1/(1 + x^2);
g = sin(y);
h = x^t;
p = exp(-y/u);
a =
1/(sin(y)^2 + 1)
b = compose(f,g,t)
b =
1/(sin(t)^2 + 1)
7-201
7 Functions
c = compose(h,g,x,z)
c =
sin(z)^t
d = compose(h,g,t,z)
d =
x^sin(z)
e = compose(h,p,x,y,z)
e =
exp(-z/u)^t
Input Arguments
f — Input
symbolic function | symbolic expression
g — Input
symbolic function | symbolic expression
x — Symbolic variable
symbolic variable
y — Symbolic variable
symbolic variable
z — Symbolic variable
symbolic variable
Version History
Introduced before R2006a
See Also
finverse | subs | syms
7-202
cond
cond
Condition number of matrix
Syntax
cond(A)
cond(A,P)
Description
cond(A) returns the 2-norm condition number of matrix A.
Examples
Compute the 2-norm condition number of the inverse of the 3-by-3 magic square A.
A = inv(sym(magic(3)));
condN2 = cond(A)
condN2 =
(5*3^(1/2))/2
vpa(condN2, 20)
ans =
4.3301270189221932338186158537647
Compute the 1-norm condition number, the Frobenius condition number, and the infinity condition
number of the inverse of the 3-by-3 magic square A.
A = inv(sym(magic(3)));
condN1 = cond(A, 1)
condNf = cond(A, 'fro')
condNi = cond(A, inf)
condN1 =
16/3
condNf =
(285^(1/2)*391^(1/2))/60
7-203
7 Functions
condNi =
16/3
vpa(condN1)
vpa(condNf)
vpa(condNi)
ans =
5.3333333333333333333333333333333
ans =
5.5636468855119361058627454652148
ans =
5.3333333333333333333333333333333
Hilbert matrices are examples of ill-conditioned matrices. Numerically compute the condition
numbers of the 3-by-3 Hilbert matrix by using cond and vpa.
H = hilb(sym(3));
condN2 = vpa(cond(H))
condN1 = vpa(cond(H,1))
condNf = vpa(cond(H,'fro'))
condNi = vpa(cond(H,inf))
condN2 =
524.05677758606270799646154046059
condN1 =
748.0
condNf =
526.15882107972220183000899851322
condNi =
748.0
Input Arguments
A — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
P — Input
2 (default) | number | character vector
7-204
cond
More About
Condition Number of a Matrix
Condition number of a matrix is the ratio of the largest singular value of that matrix to the smallest
singular value. The P-norm condition number of the matrix A is defined as
norm(A,P)*norm(inv(A),P).
Tips
• Calling cond for a numeric matrix that is not a symbolic object invokes the MATLAB cond
function.
Version History
Introduced in R2012b
See Also
equationsToMatrix | inv | linsolve | norm | rank
7-205
7 Functions
conj
Complex conjugate of symbolic input
Syntax
conj(x)
Description
conj(x) returns the complex conjugate of x. Because symbolic scalar variables are complex by
default, unresolved calls, such as conj(x), can appear in the output of norm, mtimes, and other
functions. For details, see “Use Assumptions on Symbolic Variables” on page 1-41.
Examples
ans =
1.0000 - 3.0000i
fConj =
conj(x)^2
Convert symbolic output to double by substituting for x with a number by using subs, and then using
double.
fConj = subs(fConj,x,1+2i); % x is 1+2i
fConj = double(fConj)
fConj =
-3.0000 - 4.0000i
If the input is real, conj returns the input instead of an unresolved call. Assume x is real and find its
conjugate. conj returns x instead of conj(x), as expected.
syms x
assume(x,'real')
conj(x)
7-206
conj
ans =
x
assume(x,'clear')
Input Arguments
x — Input
number | vector | matrix | array | symbolic number | symbolic scalar variable | symbolic matrix
variable | symbolic array | symbolic function | symbolic matrix function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, scalar variable, matrix
variable, array, function, matrix function, or expression.
Version History
Introduced before R2006a
See Also
real | imag
7-207
7 Functions
convertMuPADNotebook
(To be removed) Convert MuPAD notebook to MATLAB live script
Syntax
convertMuPADNotebook(MuPADfile,MATLABLiveScript)
convertMuPADNotebook(MuPADfile)
Description
convertMuPADNotebook(MuPADfile,MATLABLiveScript) converts a MuPAD notebook file
MuPADfile (.mn) to a MATLAB live script file MATLABLiveScript (.mlx). Both MuPADfile and
MATLABLiveScript must be full paths unless the files are in the current folder. For information on
live scripts, see “Create Live Scripts in the Live Editor”.
convertMuPADNotebook(MuPADfile) uses the same name and path, MuPADfile, for the MATLAB
live script file that contains converted code. The extension .mn changes to .mlx in the resulting
MATLAB live script file.
Examples
Convert MuPAD Notebook to MATLAB Script
Suppose that your current folder contains a MuPAD notebook named myNotebook.mn. Convert this
notebook to the MATLAB live script file named myScript.mlx.
convertMuPADNotebook('myNotebook.mn','myScript.mlx')
edit('myScript.mlx')
Visually check the code for correctness and completeness. Then verify it by running it.
Convert a MuPAD notebook to a MATLAB live script file with the same name.
Suppose that your current folder contains a MuPAD notebook named myFile.mn. Convert this
notebook to the MATLAB live script file named myFile.mlx.
convertMuPADNotebook('myFile.mn')
7-208
convertMuPADNotebook
Visually check the code for correctness and completeness. Then verify it by executing it.
If convertMuPADNotebook reports that the converted code has translation errors or warnings,
correct the resulting MATLAB code before using it.
Convert the MuPAD notebook, myNotebook.mn, to the MATLAB live script file, myScript.mlx.
Because myNotebook.mn contains commands that cannot be directly translated to MATLAB code,
convertMuPADNotebook flags these commands as translation errors and warnings.
convertMuPADNotebook('myNotebook.mn','myScript.mlx')
A translation error indicates that convertMuPADNotebook was unable to convert part of the MuPAD
notebook, and that without this part the translated code will not run properly. A translation warning
indicates that convertMuPADNotebook was unable to convert a part of the MuPAD notebook (for
example, an empty input region) and ignored it. Converted code containing warnings is likely to run
without any issues.
Eliminate translation errors. First, search for “translation error”. Next to “translation error”, the
converted code displays short comments explaining which MuPAD command did not translate
properly. There is also a link to documentation that provides more details and suggestions for fixing
the issue. After fixing the issue, remove the corresponding error message and any comments related
to it.
Find translation warnings by searching for “translation warning”. The converted code displays a short
comment and a link to documentation next to “translation warning”. Some warnings might require
you to adapt the code so it runs properly. In most cases, you can ignore translation warnings.
Whether you fixed the code or decided to ignore the warning, remove the warning message and any
comments related to it.
Verify that the resulting MATLAB code runs properly by executing it.
Convert all MuPAD notebooks in a folder by making it your current folder, and then using a loop to
call the convertMuPADNotebook function on every notebook in the folder.
files = dir('*.mn');
for i = 1:numel(files)
convertMuPADNotebook(files(i).name)
end
7-209
7 Functions
Simple procedures are converted into anonymous functions. Convert a MuPAD notebook with the
following code.
f := x -> x^2
f(2)
When procedures are too complex to convert to anonymous functions, they are converted to local
functions in the live script. Local functions are placed at the end of the live script.
7-210
convertMuPADNotebook
When converting a notebook that reads a MuPAD program file (.mu), convertMuPADNotebook
replaces the read command with the contents of the .mu file. The notebook and program files must
be in the same directory.
Input Arguments
MuPADfile — Name of MuPAD notebook
character vector
Name of a MuPAD notebook, specified as a character vector. This character vector must specify the
full path to the file, unless the file is in the current folder.
Example: 'C:\MuPAD_Notebooks\myFile.mn'
Name of a MATLAB live script file, specified as a character vector. This character vector must specify
the full path to the file, unless you intend to create a file in the current folder.
Example: 'C:\MATLAB_Scripts\myFile.mlx'
Version History
Introduced in R2016a
7-211
7 Functions
R2023a: Warns
Warns starting in R2023a
The convertMuPADNotebook function issues a warning that it will be removed in a future release.
R2022b: To be removed
Not recommended starting in R2022b
The convertMuPADNotebook function will be removed in a future release. Convert your MuPAD
notebooks to MATLAB live scripts, and use the MATLAB Live Editor instead.
See Also
Topics
“What Is a Live Script or Function?”
“Convert MuPAD Notebooks to MATLAB Live Scripts” on page 6-3
“Troubleshoot MuPAD to MATLAB Translation Errors” on page 6-8
“Troubleshoot MuPAD to MATLAB Translation Warnings” on page 6-15
7-212
cos
cos
Symbolic cosine function
Syntax
cos(X)
Description
cos(X) returns the cosine function on page 7-215 of X.
Examples
Cosine Function for Numeric and Symbolic Arguments
Compute the cosine function for these numbers. Because these numbers are not symbolic objects,
cos returns floating-point results.
A =
-0.4161 -1.0000 0.8660 -0.6235 0.0044
Compute the cosine function for the numbers converted to symbolic objects. For many symbolic
(exact) numbers, cos returns unresolved symbolic calls.
symA =
[ cos(2), -1, 3^(1/2)/2, -cos((2*pi)/7), cos(11)]
vpa(symA)
ans =
[ -0.41614683654714238699756822950076,...
-1.0,...
0.86602540378443864676372317075294,...
-0.62348980185873353052500488400424,...
0.0044256979880507857483550247239416]
syms x
fplot(cos(x),[-4*pi 4*pi])
grid on
7-213
7 Functions
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing cos.
syms x
diff(cos(x), x)
diff(cos(x), x, x)
ans =
-sin(x)
ans =
-cos(x)
int(cos(x), x)
ans =
sin(x)
taylor(cos(x), x)
7-214
cos
ans =
x^4/24 - x^2/2 + 1
rewrite(cos(x), 'exp')
ans =
exp(-x*1i)/2 + exp(x*1i)/2
cos numerically evaluates these units automatically: radian, degree, arcmin, arcsec, and
revolution.
u = symunit;
syms x
f = [x*u.degree 2*u.radian];
cosinf = cos(f)
cosinf =
[ cos((pi*x)/180), cos(2)]
You can calculate cosinf by substituting for x using subs and then using double or vpa.
Input Arguments
X — Input
symbolic number | symbolic scalar variable | symbolic matrix variable | symbolic expression |
symbolic function | symbolic matrix function | symbolic vector | symbolic matrix
Input, specified as a symbolic number, scalar variable, matrix variable, expression, function, matrix
function, or as a vector or matrix of symbolic numbers, scalar variables, expressions, or functions.
More About
Cosine Function
adjacent side b
cos(α) = = .
hypotenuse h
7-215
7 Functions
eiα + e−iα
cos(α) = .
2
Version History
Introduced before R2006a
See Also
acos | asin | atan | acsc | asec | acot | sin | tan | csc | sec | cot
7-216
cosh
cosh
Symbolic hyperbolic cosine function
Syntax
cosh(X)
Description
cosh(X) returns the hyperbolic cosine function of X.
Examples
Hyperbolic Cosine Function for Numeric and Symbolic Arguments
Compute the hyperbolic cosine function for these numbers. Because these numbers are not symbolic
objects, cosh returns floating-point results.
A =
3.7622 -1.0000 0.8660 -0.6235 -0.0000
Compute the hyperbolic cosine function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, cosh returns unresolved symbolic calls.
symA =
[ cosh(2), -1, 3^(1/2)/2, -cosh((pi*2i)/7), 0]
vpa(symA)
ans =
[ 3.7621956910836314595622134777737,...
-1.0,...
0.86602540378443864676372317075294,...
-0.62348980185873353052500488400424,...
0]
syms x
fplot(cosh(x),[-pi pi])
grid on
7-217
7 Functions
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing cosh.
Find the first and second derivatives of the hyperbolic cosine function:
syms x
diff(cosh(x), x)
diff(cosh(x), x, x)
ans =
sinh(x)
ans =
cosh(x)
int(cosh(x), x)
ans =
sinh(x)
taylor(cosh(x), x)
7-218
cosh
ans =
x^4/24 + x^2/2 + 1
rewrite(cosh(x), 'exp')
ans =
exp(-x)/2 + exp(x)/2
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Version History
Introduced before R2006a
See Also
acosh | asinh | atanh | acsch | asech | acoth | sinh | tanh | csch | sech | coth
7-219
7 Functions
coshint
Hyperbolic cosine integral function
Syntax
coshint(X)
Description
coshint(X) returns the hyperbolic cosine integral function on page 7-222 of X.
Examples
Hyperbolic Cosine Integral Function for Numeric and Symbolic Arguments
Compute the hyperbolic cosine integral function for these numbers. Because these numbers are not
symbolic objects, coshint returns floating-point results.
A =
0.8379 + 3.1416i -Inf + 0.0000i -0.0528 + 0.0000i 0.8379...
+ 0.0000i 1.7127 + 0.0000i 5.4587 + 0.0000i
Compute the hyperbolic cosine integral function for the numbers converted to symbolic objects. For
many symbolic (exact) numbers, coshint returns unresolved symbolic calls.
symA =
[ coshint(1) + pi*1i, -Inf, coshint(1/2), coshint(1), coshint(pi/2), coshint(pi)]
vpa(symA)
ans =
[ 0.83786694098020824089467857943576...
+ 3.1415926535897932384626433832795i,...
-Inf,...
-0.052776844956493615913136063326141,...
0.83786694098020824089467857943576,...
1.7126607364844281079951569897796,...
5.4587340442160681980014878977798]
Plot the hyperbolic cosine integral function on the interval from 0 to 2*pi.
7-220
coshint
syms x
fplot(coshint(x),[0 2*pi])
grid on
Many functions, such as diff and int, can handle expressions containing coshint.
Find the first and second derivatives of the hyperbolic cosine integral function:
syms x
diff(coshint(x), x)
diff(coshint(x), x, x)
ans =
cosh(x)/x
ans =
sinh(x)/x - cosh(x)/x^2
int(coshint(x), x)
ans =
x*coshint(x) - sinh(x)
7-221
7 Functions
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
More About
Hyperbolic Cosine Integral Function
Version History
Introduced in R2014a
References
[1] Cautschi, W. and W. F. Cahill. “Exponential Integral and Related Functions.” Handbook of
Mathematical Functions with Formulas, Graphs, and Mathematical Tables. (M. Abramowitz
and I. A. Stegun, eds.). New York: Dover, 1972.
See Also
cos | cosint | eulergamma | int | sinhint | sinint | ssinint
7-222
cosint
cosint
Cosine integral function
Syntax
cosint(X)
Description
cosint(X) returns the cosine integral function on page 7-225 of X.
Examples
Cosine Integral Function for Numeric and Symbolic Arguments
Compute the cosine integral function for these numbers. Because these numbers are not symbolic
objects, cosint returns floating-point results.
A =
0.3374 + 3.1416i -Inf + 0.0000i 0.4720 + 0.0000i...
0.0737 + 0.0000i 0.3374 + 0.0000i
Compute the cosine integral function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, cosint returns unresolved symbolic calls.
symA =
[ cosint(1) + pi*1i, -Inf, cosint(pi/2), cosint(pi), cosint(1)]
vpa(symA)
ans =
[ 0.33740392290096813466264620388915...
+ 3.1415926535897932384626433832795i,...
-Inf,...
0.47200065143956865077760610761413,...
0.07366791204642548599010096523015,...
0.33740392290096813466264620388915]
7-223
7 Functions
syms x
fplot(cosint(x),[0 4*pi])
grid on
Many functions, such as diff and int, can handle expressions containing cosint.
Find the first and second derivatives of the cosine integral function:
syms x
diff(cosint(x), x)
diff(cosint(x), x, x)
ans =
cos(x)/x
ans =
- cos(x)/x^2 - sin(x)/x
int(cosint(x), x)
ans =
x*cosint(x) - sin(x)
7-224
cosint
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
More About
Cosine Integral Function
Version History
Introduced before R2006a
References
[1] Gautschi, W. and W. F. Cahill. “Exponential Integral and Related Functions.” Handbook of
Mathematical Functions with Formulas, Graphs, and Mathematical Tables. (M. Abramowitz
and I. A. Stegun, eds.). New York: Dover, 1972.
See Also
cos | coshint | eulergamma | int | sinhint | sinint | ssinint
7-225
7 Functions
cot
Symbolic cotangent function
Syntax
cot(X)
Description
cot(X) returns the cotangent function on page 7-228 of X.
Examples
Cotangent Function for Numeric and Symbolic Arguments
Compute the cotangent function for these numbers. Because these numbers are not symbolic objects,
cot returns floating-point results.
A =
0.4577 -0.0000 1.7321 -0.7975 -0.0044
Compute the cotangent function for the numbers converted to symbolic objects. For many symbolic
(exact) numbers, cot returns unresolved symbolic calls.
symA =
[ -cot(2), 0, 3^(1/2), -cot((2*pi)/7), cot(11)]
vpa(symA)
ans =
[ 0.45765755436028576375027741043205,...
0,...
1.7320508075688772935274463415059,...
-0.79747338888240396141568825421443,...
-0.0044257413313241136855482762848043]
syms x
fplot(cot(x),[-pi pi])
grid on
7-226
cot
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing cot.
syms x
diff(cot(x), x)
diff(cot(x), x, x)
ans =
- cot(x)^2 - 1
ans =
2*cot(x)*(cot(x)^2 + 1)
int(cot(x), x)
ans =
log(sin(x))
taylor(cot(x), x, pi/2)
7-227
7 Functions
ans =
pi/2 - x - (x - pi/2)^3/3 - (2*(x - pi/2)^5)/15
Rewrite the cotangent function in terms of the sine and cosine functions:
rewrite(cot(x), 'sincos')
ans =
cos(x)/sin(x)
rewrite(cot(x), 'exp')
ans =
(exp(x*2i)*1i + 1i)/(exp(x*2i) - 1)
cot numerically evaluates these units automatically: radian, degree, arcmin, arcsec, and
revolution.
u = symunit;
syms x
f = [x*u.degree 2*u.radian];
cotf = cot(f)
cotf =
[ cot((pi*x)/180), cot(2)]
You can calculate cotf by substituting for x using subs and then using double or vpa.
Input Arguments
X — Input
symbolic number | symbolic scalar variable | symbolic matrix variable | symbolic expression |
symbolic function | symbolic matrix function | symbolic vector | symbolic matrix
Input, specified as a symbolic number, scalar variable, matrix variable, expression, function, matrix
function, or as a vector or matrix of symbolic numbers, scalar variables, expressions, or functions.
More About
Cotangent Function
1 adjacent side b
cot α = = = .
tan α opposite side a
7-228
cot
i eiα + e−iα
cot α = .
eiα − e−iα
Version History
Introduced before R2006a
See Also
acos | asin | atan | acsc | asec | acot | sin | cos | tan | csc | sec
7-229
7 Functions
coth
Symbolic hyperbolic cotangent function
Syntax
coth(X)
Description
coth(X) returns the hyperbolic cotangent function of X
Examples
Hyperbolic Cotangent Function for Numeric and Symbolic Arguments
Compute the hyperbolic cotangent function for these numbers. Because these numbers are not
symbolic objects, coth returns floating-point results.
A = coth([-2, -pi*i/3, pi*i/6, 5*pi*i/7, 3*pi*i/2])
A =
-1.0373 + 0.0000i 0.0000 + 0.5774i 0.0000 - 1.7321i...
0.0000 + 0.7975i 0.0000 - 0.0000i
Compute the hyperbolic cotangent function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, coth returns unresolved symbolic calls.
symA = coth(sym([-2, -pi*i/3, pi*i/6, 5*pi*i/7, 3*pi*i/2]))
symA =
[ -coth(2), (3^(1/2)*1i)/3, -3^(1/2)*1i, -coth((pi*2i)/7), 0]
ans =
[ -1.0373147207275480958778097647678,...
0.57735026918962576450914878050196i,...
-1.7320508075688772935274463415059i,...
0.79747338888240396141568825421443i,...
0]
Plot the hyperbolic cotangent function on the interval from -10 to 10.
syms x
fplot(coth(x),[-10 10])
grid on
7-230
coth
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing coth.
Find the first and second derivatives of the hyperbolic cotangent function:
syms x
diff(coth(x), x)
diff(coth(x), x, x)
ans =
1 - coth(x)^2
ans =
2*coth(x)*(coth(x)^2 - 1)
int(coth(x), x)
ans =
log(sinh(x))
taylor(coth(x), x, pi*i/2)
7-231
7 Functions
ans =
x - (pi*1i)/2 - (x - (pi*1i)/2)^3/3 + (2*(x - (pi*1i)/2)^5)/15
rewrite(coth(x), 'exp')
ans =
(exp(2*x) + 1)/(exp(2*x) - 1)
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Version History
Introduced before R2006a
See Also
acosh | asinh | atanh | acsch | asech | acoth | sinh | cosh | tanh | csch | sech
7-232
csc
csc
Symbolic cosecant function
Syntax
csc(X)
Description
csc(X) returns the cosecant function on page 7-235 of X.
Examples
Cosecant Function for Numeric and Symbolic Arguments
Compute the cosecant function for these numbers. Because these numbers are not symbolic objects,
csc returns floating-point results.
A =
-1.0998 -1.0000 2.0000 1.2790 -1.0000
Compute the cosecant function for the numbers converted to symbolic objects. For many symbolic
(exact) numbers, csc returns unresolved symbolic calls.
symA =
[ -1/sin(2), -1, 2, 1/sin((2*pi)/7), 1/sin(11)]
vpa(symA)
ans =
[ -1.0997501702946164667566973970263,...
-1.0,...
2.0,...
1.2790480076899326057478506072714,...
-1.0000097935452091313874644503551]
syms x
fplot(csc(x),[-4*pi 4*pi])
grid on
7-233
7 Functions
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing csc.
syms x
diff(csc(x), x)
diff(csc(x), x, x)
ans =
-cos(x)/sin(x)^2
ans =
1/sin(x) + (2*cos(x)^2)/sin(x)^3
int(csc(x), x)
ans =
log(tan(x/2))
taylor(csc(x), x, pi/2)
7-234
csc
ans =
(x - pi/2)^2/2 + (5*(x - pi/2)^4)/24 + 1
rewrite(csc(x), 'exp')
ans =
1/((exp(-x*1i)*1i)/2 - (exp(x*1i)*1i)/2)
csc numerically evaluates these units automatically: radian, degree, arcmin, arcsec, and
revolution.
u = symunit;
syms x
f = [x*u.degree 2*u.radian];
cosecf = csc(f)
cosecf =
[ 1/sin((pi*x)/180), 1/sin(2)]
You can calculate cosecf by substituting for x using subs and then using double or vpa.
Input Arguments
X — Input
symbolic number | symbolic scalar variable | symbolic matrix variable | symbolic expression |
symbolic function | symbolic matrix function | symbolic vector | symbolic matrix
Input, specified as a symbolic number, scalar variable, matrix variable, expression, function, matrix
function, or as a vector or matrix of symbolic numbers, scalar variables, expressions, or functions.
More About
Cosecant Function
1 hypotenuse h
csc(α) = = = .
sin α opposite side a
7-235
7 Functions
2i
csc α = .
eiα − e−iα
Version History
Introduced before R2006a
See Also
acos | asin | atan | acsc | asec | acot | sin | cos | tan | cot
7-236
csch
csch
Symbolic hyperbolic cosecant function
Syntax
csch(X)
Description
csch(X) returns the hyperbolic cosecant function of X.
Examples
Hyperbolic Cosecant Function for Numeric and Symbolic Arguments
Compute the hyperbolic cosecant function for these numbers. Because these numbers are not
symbolic objects, csch returns floating-point results.
A =
-0.2757 + 0.0000i 0.0000 + 1.0000i Inf + 0.0000i...
0.0000 - 1.1547i 0.0000 - 1.2790i 0.0000 - 1.0000i
Compute the hyperbolic cosecant function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, csch returns unresolved symbolic calls.
symA =
[ -1/sinh(2), 1i, Inf, -(3^(1/2)*2i)/3, 1/sinh((pi*2i)/7), -1i]
vpa(symA)
ans =
[ -0.27572056477178320775835148216303,...
1.0i,...
Inf,...
-1.1547005383792515290182975610039i,...
-1.2790480076899326057478506072714i,...
-1.0i]
Plot the hyperbolic cosecant function on the interval from -10 to 10.
7-237
7 Functions
syms x
fplot(csch(x),[-10 10])
grid on
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing csch.
Find the first and second derivatives of the hyperbolic cosecant function:
syms x
diff(csch(x), x)
diff(csch(x), x, x)
ans =
-cosh(x)/sinh(x)^2
ans =
(2*cosh(x)^2)/sinh(x)^3 - 1/sinh(x)
ans =
log(tanh(x/2))
7-238
csch
taylor(csch(x), x, pi*i/2)
ans =
((x - (pi*1i)/2)^2*1i)/2 - ((x - (pi*1i)/2)^4*5i)/24 - 1i
rewrite(csch(x), 'exp')
ans =
-1/(exp(-x)/2 - exp(x)/2)
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Version History
Introduced before R2006a
See Also
acosh | asinh | atanh | acsch | asech | acoth | sinh | cosh | tanh | sech | coth
7-239
7 Functions
ctranspose, '
Symbolic matrix complex conjugate transpose
Syntax
A'
ctranspose(A)
Description
A' computes the complex conjugate transpose on page 7-241 of A.
Examples
Conjugate Transpose of Real Matrix
syms x y real
A = [x x x; y y y]
A =
[ x, x, x]
[ y, y, y]
A'
ans =
[ x, y]
[ x, y]
[ x, y]
If all elements of a matrix represent real numbers, then its complex conjugate transform equals to its
nonconjugate transform.
isAlways(A' == A.')
ans =
3×2 logical array
1 1
1 1
1 1
syms x y real
A = [x + y*i x - y*i; y + x*i y - x*i]
7-240
ctranspose, '
A =
[ x + y*1i, x - y*1i]
[ y + x*1i, y - x*1i]
Find the conjugate transpose of this matrix. The complex conjugate transpose operator, A', performs
a transpose and negates the sign of the imaginary portion of the complex elements in A.
A'
ans =
[ x - y*1i, y - x*1i]
[ x + y*1i, y + x*1i]
For a matrix of complex numbers with nonzero imaginary parts, the complex conjugate transform is
not equal to the nonconjugate transform.
isAlways(A' == A.','Unknown','false')
ans =
2×2 logical array
0 0
0 0
Input Arguments
A — Input
number | symbolic number | symbolic scalar variable | symbolic matrix variable | symbolic function |
symbolic matrix function | symbolic expression | symbolic vector | symbolic matrix | symbolic array
Input, specified as a number, or a symbolic number, scalar variable, matrix variable, function, matrix
function, expression, or vector, matrix, or array of symbolic scalar variables.
More About
Complex Conjugate Transpose
The complex conjugate transpose of a matrix interchanges the row and column index for each
element, reflecting the elements across the main diagonal. The operation also negates the imaginary
part of any complex numbers.
For example, if B = A' and A(1,2) is 1+1i, then the element B(2,1) is 1-1i.
Version History
Introduced before R2006a
7-241
7 Functions
See Also
ldivide | minus | mldivide | mpower | mrdivide | mtimes | plus | power | rdivide | times |
transpose
7-242
cumprod
cumprod
Symbolic cumulative product
Syntax
B = cumprod(A)
B = cumprod(A,dim)
B = cumprod( ___ ,direction)
B = cumprod( ___ ,nanflag)
Description
B = cumprod(A) returns the cumulative product of A starting at the beginning of the first array
dimension in A whose size does not equal 1. The output B has the same size as A.
• If A is a vector, then cumprod(A) returns a vector containing the cumulative product of the
elements of A.
• If A is a matrix, then cumprod(A) returns a matrix containing the cumulative products of each
column of A.
• If A is a multidimensional array, then cumprod(A) acts along the first nonsingleton dimension on
page 7-247.
B = cumprod(A,dim) returns the cumulative product along dimension dim. For example, if A is a
matrix, then cumprod(A,2) returns the cumulative product of each row.
B = cumprod( ___ ,direction) specifies the direction using any of the previous syntaxes. For
instance, cumprod(A,2,'reverse') returns the cumulative product within the rows of A by
working from end to beginning of the second dimension.
B = cumprod( ___ ,nanflag) specifies whether to include or omit NaN values from the calculation
for any of the previous syntaxes. cumprod(A,'includenan') includes all NaN values in the
calculation while cumprod(A,'omitnan') ignores them.
Examples
syms x
A = (1:5)*x
A = x 2x 3x 4x 5x
In the vector of cumulative products, element B(2) is the product of A(1) and A(2), while B(5) is
the product of elements A(1) through A(5).
B = cumprod(A)
7-243
7 Functions
B = x 2 x2 6 x3 24 x4 120 x5
syms x
A = ones(3)*x
A =
xxx
xxx
xxx
Compute the cumulative product of elements of A. By default, cumprod returns the cumulative
product of each column.
B = cumprod(A)
B =
x x x
x2 x2 x2
x3 x3 x3
To compute the cumulative product of each row, set the value of the dim option to 2.
B = cumprod(A,2)
B =
x x2 x3
x x2 x3
x x2 x3
syms x y
A(:,:,1) = [x y 0; x 3 x*y; x 1/3 y];
A(:,:,2) = [x y 3; 3 x y; y 3 x];
A
A(:,:,1) =
x y 0
x 3 xy
1
x y
3
A(:,:,2) =
7-244
cumprod
x y 3
3 x y
y 3 x
Compute the cumulative product along the rows by specifying dim as 2. Specify the 'reverse'
option to work from right to left in each row. The result is the same size as A.
B = cumprod(A,2,'reverse')
B(:,:,1) =
0 0 0
3 x2 y 3 x y x y
xy y
y
3 3
B(:,:,2) =
3xy 3y 3
3xy xy y
3xy 3x x
To compute the cumulative product along the third (page) dimension, specify dim as 3. Specify the
'reverse' option to work from the largest page index to the smallest page index.
B = cumprod(A,3,'reverse')
B(:,:,1) =
x2 y2 0
3 x 3 x x y2
xy 1 xy
B(:,:,2) =
x y 3
3 x y
y 3 x
Create a symbolic vector containing NaN values. Compute the cumulative products.
A = a b 1 NaN 2
B = cumprod(A)
B = a a b a b NaN NaN
You can ignore NaN values in the cumulative product calculation using the 'omitnan' option.
B = cumprod(A,'omitnan')
B = a ab ab ab 2ab
7-245
7 Functions
Input Arguments
A — Input array
symbolic vector | symbolic matrix | symbolic multidimensional array
Dimension to operate along, specified as a positive integer scalar. If no value is specified, then the
default is the first array dimension whose size does not equal 1.
• cumprod(A,1) works on successive elements in the columns of A and returns the cumulative
product of each column.
• cumprod(A,2) works on successive elements in the rows of A and returns the cumulative product
of each row.
• 'includenan' — Include NaN values from the input when computing the cumulative products,
resulting in NaN values in the output.
• 'omitnan' — Ignore all NaN values in the input. The product of elements containing NaN values
is the product of all non-NaN elements. If all elements are NaN, then cumprod returns 1.
7-246
cumprod
Output Arguments
B — Cumulative product array
vector | matrix | multidimensional array
Cumulative product array, returned as a vector, matrix, or multidimensional array of the same size as
the input A.
More About
First Nonsingleton Dimension
The first nonsingleton dimension is the first dimension of an array whose size is not equal to 1.
For example:
• If X is a 1-by-n row vector, then the second dimension is the first nonsingleton dimension of X.
• If X is a 1-by-0-by-n empty array, then the second dimension is the first nonsingleton dimension of
X.
• If X is a 1-by-1-by-3 array, then the third dimension is the first nonsingleton dimension of X.
Version History
Introduced in R2013b
cumprod can exclude NaNs when evaluating the cumulative product of an array that contains NaNs.
You can use the option 'omitnan' to exclude NaNs and 'includenan' to include NaNs.
See Also
cumsum | fold | int | symprod | symsum
7-247
7 Functions
cumsum
Symbolic cumulative sum
Syntax
B = cumsum(A)
B = cumsum(A,dim)
B = cumsum( ___ ,direction)
B = cumsum( ___ ,nanflag)
Description
B = cumsum(A) returns the cumulative sum of A starting at the beginning of the first array
dimension in A whose size does not equal 1. The output B has the same size as A.
• If A is a vector, then cumsum(A) returns a vector containing the cumulative sum of the elements
of A.
• If A is a matrix, then cumsum(A) returns a matrix containing the cumulative sums of each column
of A.
• If A is a multidimensional array, then cumsum(A) acts along the first nonsingleton dimension on
page 7-252.
B = cumsum(A,dim) returns the cumulative sum along dimension dim. For example, if A is a matrix,
then cumsum(A,2) returns the cumulative sum of each row.
B = cumsum( ___ ,direction) specifies the direction using any of the previous syntaxes. For
instance, cumsum(A,2,'reverse') returns the cumulative sum within the rows of A by working
from end to beginning of the second dimension.
B = cumsum( ___ ,nanflag) specifies whether to include or omit NaN values from the calculation
for any of the previous syntaxes. cumsum(A,'includenan') includes all NaN values in the
calculation while cumsum(A,'omitnan') ignores them.
Examples
A = x 2x 3x 4x 5x
In the vector of cumulative sums, element B(2) is the sum of A(1) and A(2), while B(5) is the sum
of elements A(1) through A(5).
B = cumsum(A)
B = x 3 x 6 x 10 x 15 x
7-248
cumsum
A = sym(ones(3))
A =
111
111
111
Compute the cumulative sum of elements of A. By default, cumsum returns the cumulative sum of
each column.
B = cumsum(A)
B =
111
222
333
To compute the cumulative sum of each row, set the value of the dim option to 2.
B = cumsum(A,2)
B =
123
123
123
syms x y
A(:,:,1) = [x y 3; 3 x y; y 2 x];
A(:,:,2) = [x y 1/3; 1 y x; 1/3 x 2];
A
A(:,:,1) =
x y 3
3 x y
y 2 x
A(:,:,2) =
1
x y
3
1 y x
1
x 2
3
7-249
7 Functions
Compute the cumulative sum along the rows by specifying dim as 2. Specify the 'reverse' option to
work from right to left in each row. The result is the same size as A.
B = cumsum(A,2,'reverse')
B(:,:,1) =
x+y+3 y+3 3
x+y+3 x+y y
x+y+2 x+2 x
B(:,:,2) =
1 1 1
x+y+ y+
3 3 3
x+y+1 x+y x
7
x+ x+2 2
3
To compute the cumulative sum along the third (page) dimension, specify dim as 3. Specify the
'reverse' option to work from largest page index to smallest page index.
B = cumsum(A,3,'reverse')
B(:,:,1) =
10
2x 2y
3
4 x+y x+y
1
y+ x+2 x+2
3
B(:,:,2) =
1
x y
3
1 y x
1
x 2
3
Create a symbolic vector containing NaN values. Compute the cumulative sums.
A = a b 1 NaN 2
B = cumsum(A)
B = a a + b a + b + 1 NaN NaN
You can ignore NaN values in the cumulative sum calculation using the 'omitnan' option.
B = cumsum(A,'omitnan')
7-250
cumsum
Input Arguments
A — Input array
symbolic vector | symbolic matrix | symbolic multidimensional array
Dimension to operate along, specified as a positive integer scalar. If no value is specified, then the
default is the first array dimension whose size does not equal 1.
• cumsum(A,1) works on successive elements in the columns of A and returns the cumulative sum
of each column.
• cumsum(A,2) works on successive elements in the rows of A and returns the cumulative sum of
each row.
• 'includenan' — Include NaN values from the input when computing the cumulative sums,
resulting in NaN values in the output.
• 'omitnan' — Ignore all NaN values in the input. The sum of elements containing NaN values is
the sum of all non-NaN elements. If all elements are NaN, then cumsum returns 0.
7-251
7 Functions
Output Arguments
B — Cumulative sum array
vector | matrix | multidimensional array
Cumulative sum array, returned as a vector, matrix, or multidimensional array of the same size as the
input A.
More About
First Nonsingleton Dimension
The first nonsingleton dimension is the first dimension of an array whose size is not equal to 1.
For example:
• If X is a 1-by-n row vector, then the second dimension is the first nonsingleton dimension of X.
• If X is a 1-by-0-by-n empty array, then the second dimension is the first nonsingleton dimension of
X.
• If X is a 1-by-1-by-3 array, then the third dimension is the first nonsingleton dimension of X.
Version History
Introduced in R2013b
cumsum can exclude NaNs when evaluating the cumulative sum of an array that contains NaNs. You
can use the option 'omitnan' to exclude NaNs and 'includenan' to include NaNs.
See Also
cumprod | fold | int | symprod | symsum
7-252
curl
curl
Curl of symbolic vector field
Syntax
c = curl(V,X)
c = curl(V)
Description
c = curl(V,X) returns the curl on page 7-257 of symbolic vector field V with respect to vector X in
three-dimensional Cartesian coordinates. Both the vector field V and the vector X must be vectors
with three components.
c = curl(V) returns the curl of the vector field V with respect to a default vector constructed from
the symbolic variables in V.
Examples
Find the curl of the vector field V x, y, z = x3 y2z, y3z2x, z3x2 y with respect to vector X = x, y, z in
Cartesian coordinates.
syms x y z
V = [x^3*y^2*z, y^3*z^2*x, z^3*x^2*y];
X = [x y z];
c = curl(V,X)
c =
x2 z3 − 2 x y3 z
x3 y2 − 2 x y z3
y3 z2 − 2 x3 y z
Find the curl of a 2-D vector field F x, y = cos x + y , sin x − y , 0 . Plot the vector field as a quiver
(velocity) plot and the z-component of its curl as a contour plot.
Create the 2-D vector field F x, y and find its curl. The curl is a vector with only the z-component.
syms x y z
F = [cos(x+y) sin(x-y) 0];
c = curl(F,[x,y,z])
c =
7-253
7 Functions
0
0
cos x − y + sin x + y
Plot the 2-D vector field F x, y for the region −2 < x < 2 and −2 < y < 2. MATLAB® provides the
quiver plotting function for this task. The function does not accept symbolic arguments. First,
replace symbolic variables in expressions for components of F with numeric values. Then use
quiver.
v = -2:0.1:2;
[xPlot,yPlot] = meshgrid(v);
Fx = subs(F(1),{x,y},{xPlot,yPlot});
Fy = subs(F(2),{x,y},{xPlot,yPlot});
quiver(xPlot,yPlot,Fx,Fy)
hold on
Next, plot the contour of the z-component of the curl using contour.
cPlot = subs(c(3),{x,y},{xPlot,yPlot});
contour(xPlot,yPlot,cPlot,"ShowText","on")
title("Contour Plot of Curl of 2-D Vector Field")
xlabel("x")
ylabel("y")
7-254
curl
Derive the electromagnetic wave equation in free space without charge and without current sources
from Maxwell's equations.
First, create symbolic scalar variables to represent the vacuum permeability and permittivity. Create
a symbolic matrix variable to represent the Cartesian coordinates. Create two symbolic matrix
functions to represent the electric and magnetic fields as functions of space and time.
Maxwell1 = divergence(E,X) == 0
Maxwell1(X, t) = ∇ X · E X, t = 01, 1
Maxwell2(X, t) =
∂
∇ X × E X, t = − B X, t
∂t
Maxwell3 = divergence(B,X) == 0
Maxwell3(X, t) = ∇ X · B X, t = 01, 1
Maxwell4(X, t) =
∂
∇ X × B X, t = ε0 μ0 E X, t
∂t
Then, find the wave equation for the electric field. Compute the curl of the second Maxwell equation.
wave_E = curl(Maxwell2,X)
wave_E(X, t) =
∂
∇ X ∇ X · E X, t − ΔX E X, t = − ∇ X × B X, t
∂t
Substitute the first Maxwell equation in the electric field wave equation. Use lhs and rhs to obtain
the left and right sides of the first Maxwell equation.
wave_E = subs(wave_E,lhs(Maxwell1),rhs(Maxwell1))
wave_E(X, t) =
∂
−ΔX E X, t = − ∇ X × B X, t
∂t
dMaxwell4 = diff(Maxwell4,t)
dMaxwell4(X, t) =
∂ ∂ ∂
∇X × B X, t = ε0 μ0 E X, t
∂t ∂t ∂t
7-255
7 Functions
∂
Substitute the term that involves the magnetic field ∇ X × ∂t
B X, t in wave_E with the right side of
dMaxwell4. Use lhs and rhs to obtain these terms from dMaxwell4.
wave_E = subs(wave_E,lhs(dMaxwell4),rhs(dMaxwell4))
wave_E(X, t) =
∂ ∂
−ΔX E X, t = − ε0 μ0 E X, t
∂t ∂t
Using similar steps, you can also find the wave equation for the magnetic field.
wave_B = curl(Maxwell4,X)
wave_B(X, t) =
∂
∇ X ∇ X · B X, t − ΔX B X, t = ε0 μ0 ∇X × E X, t
∂t
wave_B = subs(wave_B,lhs(Maxwell3),rhs(Maxwell3))
wave_B(X, t) =
∂
−ΔX B X, t = ε0 μ0 ∇X × E X, t
∂t
dMaxwell2 = diff(Maxwell2,t)
dMaxwell2(X, t) =
∂ ∂ ∂
∇X × E X, t = − B X, t
∂t ∂t ∂t
wave_B = subs(wave_B,lhs(dMaxwell2),rhs(dMaxwell2))
wave_B(X, t) =
∂ ∂
−ΔX B X, t = − ε0 μ0 B X, t
∂t ∂t
Input Arguments
V — Three-dimensional symbolic vector field
vector of symbolic scalar variables | symbolic function | symbolic matrix variable | symbolic matrix
function
Three-dimensional symbolic vector field, specified as a vector of symbolic scalar variables, symbolic
function, symbolic matrix variable, or symbolic matrix function. V must have a size of 1-by-3 or 3-
by-1.
• If V is a function of symbolic scalar variables, where V is of type sym or symfun, then the vector X
must be of type sym or symfun.
• If V is a function of symbolic matrix variables, where V is of type symmatrix or symfunmatrix,
then the vector X must be of type symmatrix or symfunmatrix.
7-256
curl
Three-dimensional vector with respect to which you find the curl, specified as a vector of symbolic
scalar variables, symbolic function, symbolic matrix variable, or symbolic matrix function. X must
have a size of 1-by-3 or 3-by-1.
If you do not specify X and V is a function of symbolic scalar variables, then, by default, curl
constructs vector X from the symbolic scalar variables in V with the order of variables as defined by
symvar(V).
Data Types: sym | symfun | symmatrix | symfunmatrix
Limitations
• The curl function does not support tensor derivatives. If the input V is a tensor field or a matrix
rather than a vector, then the curl function returns an error.
• Symbolic Math Toolbox currently does not support the dot or cross functions for symbolic matrix
variables and functions of type symmatrix and symfunmatrix. If vector calculus identities
involve dot or cross products, then the toolbox displays those identities in terms of other
supported functions instead. To see a list of all the functions that support symbolic matrix
variables and functions, use the commands methods symmatrix and methods symfunmatrix.
More About
Curl of Symbolic Vector Field
The curl of the symbolic vector field V = (V1, V2, V3) with respect to the vector X = (X1, X2, X3) in
Cartesian coordinates is this vector.
∂V 3 ∂V 2
−
∂ X2 ∂ X3
∂V 1 ∂V 3
curl(V) = ∇ X × V = −
∂ X3 ∂ X1
∂V 2 ∂V 1
−
∂ X1 ∂ X2
Version History
Introduced in R2012a
The curl function accepts symbolic matrix variables and functions of type symmatrix and
symfunmatrix as input arguments. For example, see “Derive Electromagnetic Wave Equation” on
page 7-254.
See Also
diff | divergence | gradient | jacobian | hessian | laplacian | potential |
vectorPotential
7-257
7 Functions
daeFunction
Convert system of differential algebraic equations to MATLAB function handle suitable for ode15i
Syntax
f = daeFunction(eqs,vars)
f = daeFunction(eqs,vars,p1,...,pN)
f = daeFunction( ___ ,Name,Value)
Description
f = daeFunction(eqs,vars) converts a system of symbolic first-order differential algebraic
equations (DAEs) to a MATLAB function handle acceptable as an input argument to the numerical
MATLAB DAE solver ode15i.
Examples
Create the system of differential algebraic equations. Here, the symbolic functions x1(t) and x2(t)
represent the state variables of the system. The system also contains constant symbolic parameters a,
b, and the parameter function r(t). These parameters do not represent state variables. Specify the
equations and state variables as two symbolic vectors: equations as a vector of symbolic equations,
and variables as a vector of symbolic function calls.
syms x1(t) x2(t) a b r(t)
eqs = [diff(x1(t),t) == a*x1(t) + b*x2(t)^2,...
x1(t)^2 + x2(t)^2 == r(t)^2];
vars = [x1(t),x2(t)];
Use daeFunction to generate a MATLAB® function handle f depending on the variables x1(t),
x2(t) and on the parameters a, b, r(t).
f = daeFunction(eqs,vars,a,b,r(t))
Specify the parameter values, and create the reduced function handle F as follows.
a = -0.6;
b = -0.1;
r = @(t) cos(t)/(1 + t^2);
F = @(t,Y,YP) f(t,Y,YP,a,b,r(t));
7-258
daeFunction
t0 = 0;
y0 = [-r(t0)*sin(0.1); r(t0)*cos(0.1)];
yp0= [a*y0(1) + b*y0(2)^2; 1.234];
ode15i(F,[t0,1],y0,yp0)
Write the generated function handle to a file by specifying the File option. When writing to a file,
daeFunction optimizes the code using intermediate variables named t0, t1, .… Include comments
in the file using the Comments option.
7-259
7 Functions
% This function was generated by the Symbolic Math Toolbox version 7.3.
% 01-Jan-2017 00:00:00
YP1 = in3(1,:);
x1 = in2(1,:);
x2 = in2(2,:);
t2 = x2.^2;
eqs = [YP1-param2.*t2-param1.*x1;t2-param3.^2+x1.^2];
Input Arguments
eqs — System of first-order DAEs
vector of symbolic equations | vector of symbolic expressions
State variables, specified as a vector of symbolic functions or function calls, such as x(t).
Example: [x(t),y(t)] or [x(t);y(t)]
Parameters of the system, specified as symbolic variables, functions, or function calls, such as f(t).
You can also specify parameters of the system as a vector or matrix of symbolic variables, functions,
or function calls. If eqs contains symbolic parameters other than the variables specified in vars, you
must specify these additional parameters as p1,...,pN.
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: daeFunction(eqns,vars,'File','myfile')
7-260
daeFunction
Comments to include in the file header, specified as a character vector, cell array of character
vectors, or string vector.
Path to the file containing generated code, specified as a character vector. The generated file accepts
arguments of type double, and can be used without Symbolic Math Toolbox. If the value is an empty
character vector, odeFunction generates an anonymous function. If the character vector does not
end in .m, the function appends .m.
By default, daeFunction with the File argument generates a file containing optimized code.
Optimized means intermediate variables are automatically generated to simplify or speed up the
code. MATLAB generates intermediate variables as a lowercase letter t followed by an automatically
generated number, for example t32. To disable code optimization, use the Optimize argument.
Flag preventing optimization of code written to a function file, specified as false or true.
By default, daeFunction with the File argument generates a file containing optimized code.
Optimized means intermediate variables are automatically generated to simplify or speed up the
code. MATLAB generates intermediate variables as a lowercase letter t followed by an automatically
generated number, for example t32.
daeFunction without the File argument (or with a file path specified by an empty character vector)
creates a function handle. In this case, the code is not optimized. If you try to enforce code
optimization by setting Optimize to true, then daeFunction throws an error.
Sparse — Flag that switches between sparse and dense matrix generation
false (default) | true
Flag that switches between sparse and dense matrix generation, specified as true or false. When
you specify 'Sparse',true, the generated function represents symbolic matrices by sparse numeric
matrices. Use 'Sparse',true when you convert symbolic matrices containing many zero elements.
Often, operations on sparse matrices are more efficient than the same operations on dense matrices.
Output Arguments
f — Function handle that can serve as input argument to ode15i
MATLAB function handle
Function handle that can serve as input argument to ode15i, returned as a MATLAB function handle.
Version History
Introduced in R2014b
See Also
findDecoupledBlocks | decic | incidenceMatrix | isLowIndexDAE | massMatrixForm |
matlabFunction | ode15i | odeFunction | reduceDAEIndex | reduceDAEToODE |
reduceDifferentialOrder | reduceRedundancies
7-261
7 Functions
Topics
“Solve Differential Algebraic Equations (DAEs)” on page 3-61
7-262
dawson
dawson
Dawson integral
Syntax
dawson(X)
Description
dawson(X) represents the Dawson integral on page 7-265.
Examples
Dawson Integral for Numeric and Symbolic Arguments
Compute the Dawson integrals for these numbers. Because these numbers are not symbolic objects,
dawson returns floating-point results.
A = dawson([-Inf, -3/2, -1, 0, 2, Inf])
A =
0 -0.4282 -0.5381 0 0.3013 0
Compute the Dawson integrals for the numbers converted to symbolic objects. For many symbolic
(exact) numbers, dawson returns unresolved symbolic calls.
symA = dawson(sym([-Inf, -3/2, -1, 0, 2, Inf]))
symA =
[ 0, -dawson(3/2), -dawson(1), 0, dawson(2), 0]
ans =
[ 0,...
-0.42824907108539862547719010515175,...
-0.53807950691276841913638742040756,...
0,...
0.30134038892379196603466443928642,...
0]
7-263
7 Functions
Many functions, such as diff and limit, can handle expressions containing dawson.
syms x
diff(dawson(x), x)
diff(dawson(x), x, x)
ans =
1 - 2*x*dawson(x)
ans =
2*x*(2*x*dawson(x) - 1) - 2*dawson(x)
limit(x*dawson(x), Inf)
ans =
1/2
7-264
dawson
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
More About
Dawson Integral
The Dawson integral, also called the Dawson function, is defined as follows:
x
dawson x = D x = e−x
2
0
∫e t2dt
0
∫e −t2dt
Tips
• dawson(0) returns 0.
• dawson(Inf) returns 0.
• dawson(-Inf) returns 0.
Version History
Introduced in R2014a
See Also
erf | erfc
7-265
7 Functions
dec2bin
Convert symbolic integer in decimal to binary representation
Syntax
str = dec2bin(d)
str = dec2bin(d,n)
Description
str = dec2bin(d) returns the binary representation of symbolic integer d as a character vector.
Examples
60
Define a large integer 2 as a symbolic number.
d = sym(2)^60
d = 1152921504606846976
str =
'1000000000000000000000000000000000000000000000000000000000000'
d =
64 123
54 11
Convert the integers to binary representation using dec2bin. dec2bin returns 4 rows of character
vectors. Each row contains a 7-digit binary number.
str = dec2bin(d)
7-266
dec2bin
Return a binary representation with at least 8 digits by specifying the number of digits.
str = dec2bin(d,8)
Input Arguments
d — Integers in decimal representation
symbolic number | symbolic vector | symbolic matrix | symbolic array
d can include negative integers. The function converts negative integers using their two's
complement binary values.
Example: sym([2 4])
n — Number of bits
scalar positive integer
Version History
Introduced in R2019a
See Also
dec2hex
External Websites
Two's complement
7-267
7 Functions
dec2hex
Convert symbolic integer in decimal to hexadecimal representation
Syntax
str = dec2hex(d)
str = dec2hex(d,n)
Description
str = dec2hex(d) returns the hexadecimal representation of symbolic integer d as a character
vector.
Examples
60
Define a large integer 2 − 1 as a symbolic number.
d = sym(2)^60 - 1
d = 1152921504606846975
str = dec2hex(d)
str =
'FFFFFFFFFFFFFFF'
d =
64 123
54 11
Convert the integers to hexadecimal representation using dec2hex. dec2hex returns 4 rows of
character vectors. Each row contains a 2-digit hexadecimal number.
7-268
dec2hex
str = dec2hex(d)
Return a hexadecimal representation with at least 4 digits by specifying the number of digits.
str = dec2hex(d,4)
Input Arguments
d — Integers in decimal representation
symbolic number | symbolic vector | symbolic matrix | symbolic array
d can include negative integers. The function converts negative integers using their two's
complement binary values.
Example: sym([2 4])
Version History
Introduced in R2019a
See Also
dec2bin
External Websites
Two's complement
7-269
7 Functions
decic
Find consistent initial conditions for first-order implicit ODE system with algebraic constraints
Syntax
[y0,yp0] = decic(eqs,vars,constraintEqs,t0,y0_est,fixedVars,yp0_est,options)
Description
[y0,yp0] = decic(eqs,vars,constraintEqs,t0,y0_est,fixedVars,yp0_est,options)
finds consistent initial conditions for the system of first-order implicit ordinary differential equations
with algebraic constraints returned by the reduceDAEToODE function.
Substituting the numerical values y0, yp0 into the differential equations subs(eqs, [t; vars(t);
diff(vars(t))], [t0; y0; yp0]) and the constraint equations subs(constr, [t;
vars(t); diff(vars(t))], [t0; y0; yp0]) produces zero vectors. Here, vars must be a
column vector.
y0_est specifies numerical estimates for the values of the variables vars at the time t0, and
fixedVars indicates the values in y0_est that must not change during the numerical search. The
optional argument yp0_est lets you specify numerical estimates for the values of the derivatives of
the variables vars at the time t0.
Examples
Find Consistent Initial Conditions for ODE System
Reduce the DAE system to a system of implicit ODEs. Then, find consistent initial conditions for the
variables of the resulting ODE system and their first derivatives.
eqs =
diff(x(t), t) - y(t) - cos(t)
- 2*x(t)*diff(x(t), t) - 2*y(t)*diff(y(t), t)
constraintEqs =
1 - y(t)^2 - x(t)^2
7-270
decic
Create an option set that specifies numerical tolerances for the numerical search.
options = odeset('RelTol', 10.0^(-7), 'AbsTol', 10.0^(-7));
Fix values t0 = 0 for the time and numerical estimates for consistent values of the variables and
their derivatives.
t0 = 0;
y0_est = [0.1, 0.9];
yp0_est = [0.0, 0.0];
You can treat the constraint as an algebraic equation for the variable x with the fixed parameter y.
For this, set fixedVars = [0 1]. Alternatively, you can treat it as an algebraic equation for the
variable y with the fixed parameter x. For this, set fixedVars = [1 0].
y0 =
0.1000
0.9950
yp0 =
1.9950
-0.2005
y0 =
-0.4359
0.9000
yp0 =
1.9000
0.9202
Verify that these initial values are consistent initial values satisfying the equations and the
constraints.
subs(eqs, [t; vars; diff(vars,t)], [t0; y0; yp0])
ans =
0
0
ans =
0
Input Arguments
eqs — System of implicit ordinary differential equations
vector of symbolic equations | vector of symbolic expressions
7-271
7 Functions
State variables of original DAE system, specified as a vector of symbolic functions or function calls,
such as x(t).
Example: [x(t),y(t)] or [x(t);y(t)]
t0 — Initial time
number
Estimates for the values of the variables vars at the initial time t0, specified as a numeric vector.
fixedVars — Input vector indicating which elements of y0_est are fixed values
vector with elements 0 or 1
Input vector indicating which elements of y0_est are fixed values, specified as a vector with 0s or
1s. Fixed values of y0_est correspond to values 1 in fixedVars. These values are not modified
during the numerical search. The zero entries in fixedVars correspond to those variables in y0_est
for which decic solves the constraint equations. The number of 0s must coincide with the number of
constraint equations. The Jacobian matrix of the constraints with respect to the variables
vars(fixedVars == 0) must be invertible.
yp0_est — Estimates for values of first derivatives of variables vars at initial time t0
numeric vector
Estimates for the values of the first derivatives of the variables vars at the initial time t0, specified
as a numeric vector.
Options for numerical search, specified as an options structure, returned by odeset. For example,
you can specify tolerances for the numerical search here.
7-272
decic
Output Arguments
y0 — Consistent initial values for variables
numeric column vector
Consistent initial values for first derivatives of variables, returned as a numeric column vector.
Version History
Introduced in R2014b
See Also
findDecoupledBlocks | daeFunction | incidenceMatrix | isLowIndexDAE |
massMatrixForm | odeFunction | reduceDAEIndex | reduceDAEToODE |
reduceDifferentialOrder | reduceRedundancies
Topics
“Solve Differential Algebraic Equations (DAEs)” on page 3-61
7-273
7 Functions
derivedUnits
Derived units of unit system
Syntax
derivedUnits(unitSystem)
Description
derivedUnits(unitSystem) returns the derived units of the unit system unitSystem as a vector
of symbolic units. You can use the returned units to create new unit systems by using
newUnitSystem.
Examples
Get the derived units of a unit system by using derivedUnits. Then, modify the derived units and
create a new unit system using the modified derived units. Available unit systems include SI, CGS,
and US. For all unit systems, see “Unit Systems List” on page 2-71.
dunits = derivedUnits('SI')
dunits =
[ [F], [C], [S], [H], [V], [J], [N], [lx], [lm], [Wb], [W], [Pa],...
[Ohm], [T], [Gy], [Bq], [Sv], [Hz], [kat], [rad], [sr], [Celsius]]
Note Do not define a variable called derivedUnits because the variable will prevent access to the
derivedUnits function.
Define derived units that use kilonewton for force and millibar for pressure by modifying dunits
using subs.
u = symunit;
newUnits = subs(dunits,[u.N u.Pa],[u.kN u.mbar])
newUnits =
[ [F], [C], [S], [H], [V], [J], [kN], [lx], [lm], [Wb], [W], [mbar],...
[Ohm], [T], [Gy], [Bq], [Sv], [Hz], [kat], [rad], [sr], [Celsius]]
Define the new unit system by using newUnitSystem. Keep the SI base units.
bunits = baseUnits('SI');
newUnitSystem('SI_kN_mbar',bunits,newUnits)
ans =
"SI_kN_mbar"
7-274
derivedUnits
To convert between unit systems, see “Unit Conversions and Unit Systems” on page 2-53.
Input Arguments
unitSystem — Name of unit system
string | character vector
Version History
Introduced in R2017b
See Also
baseUnits | newUnitSystem | removeUnitSystem | rewrite | symunit | unitSystems
Topics
“Units of Measurement Tutorial” on page 2-47
“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)
7-275
7 Functions
det
Determinant of symbolic matrix
Syntax
B = det(A)
B = det(A,'Algorithm','minor-expansion')
B = det(M)
Description
B = det(A) returns the determinant of the square matrix of symbolic numbers, scalar variables, or
functions A.
B = det(M) returns the determinant of the square symbolic matrix variable or matrix function M.
Examples
B = ad−bc
B =
1
3
7-276
det
syms a x
A = [1, a*x^2+x, x;
0, a*x, 2;
3*x+2, a*x^2-1, 0]
A =
1 a x2 + x x
0 ax 2
3 x + 2 a x2 − 1 0
B = 3 a x3 + 6 x2 + 4 x + 2
A 02, 2
M=
C B
where A, B, and C are 2-by-2 submatrices. The notation 02, 2 represents a 2-by-2 submatrix of zeros.
Use symbolic matrix variables to represent the submatrices in the block matrix.
syms A B C [2 2] matrix
Z = symmatrix(zeros(2))
Z = 02, 2
M = [A Z; C B]
M =
A 02, 2
C B
ans =
A 02, 2
det
C B
Convert the result from symbolic matrix variables to symbolic scalar variables using
symmatrix2sym.
D1 = simplify(symmatrix2sym(det(M)))
Check if the determinant of matrix M is equal to the determinant of A times the determinant of B.
7-277
7 Functions
D2 = symmatrix2sym(det(A)*det(B))
isequal(D1,D2)
ans = logical
1
Create the matrix A as a symbolic matrix variable and the coefficient a0 as a symbolic scalar variable.
Create the matrix polynomial as a symbolic matrix function f with a0 and A as its parameters.
syms A [2 2] matrix
syms a0
syms f(a0,A) [2 2] matrix keepargs
f(a0,A) = a0*eye(2) + A
f(a0, A) = a0 I2 + A
Find the determinant of f using det. The result is a symbolic matrix function of type symfunmatrix
that accepts scalars, vectors, and matrices as its input arguments.
fInv = det(f)
fInv(a0, A) = det a0 I2 + A
Convert the result from the symfunmatrix data type to the symfun data type using
symfunmatrix2symfun. The result is a symbolic function that accepts scalars as its input
arguments.
gInv = symfunmatrix2symfun(fInv)
gInv(a0, A1_1, A1_2, A2_1, A2_2) = A1, 1 a0 + A2, 2 a0 + a02 + A1, 1 A2, 2 − A1, 2 A2, 1
Input Arguments
A — Input matrix
square matrix of symbolic numbers | square matrix of symbolic scalar variables | square matrix of
symbolic functions
Input matrix, specified as a square matrix of symbolic numbers, square matrix of symbolic scalar
variables, or square matrix of symbolic functions.
Data Types: single | double | sym | symfun
M — Input matrix
square symbolic matrix variable | square symbolic matrix function
7-278
det
Input matrix, specified as a square symbolic matrix variable or square symbolic matrix function.
Data Types: symmatrix | symfunmatrix
Tips
• Matrix computations involving many symbolic variables can be slow. To increase the
computational speed, reduce the number of symbolic variables by substituting the given values for
some variables.
• The minor expansion method is generally useful to evaluate the determinant of a matrix that
contains many symbolic scalar variables. This method is often suited to matrices that contain
polynomial entries with multivariate coefficients.
Version History
Introduced before R2006a
The det function accepts an input argument of type symfunmatrix. For an example, see “Compute
Determinant of Matrix Polynomial” on page 7-278.
The det function accepts an input argument of type symmatrix. For an example, see “Compute
Determinant of Block Matrix” on page 7-277.
References
[1] Khovanova, T. and Z. Scully. "Efficient Calculation of Determinants of Symbolic Matrices with
Many Variables." arXiv preprint arXiv:1304.4691 (2013).
See Also
rank | eig
7-279
7 Functions
diag
Create diagonal matrix or get diagonals from symbolic matrices
Syntax
D = diag(v)
D = diag(v,k)
x = diag(A)
x = diag(A,k)
Description
D = diag(v) returns a square diagonal matrix with vector v as the main diagonal.
D = diag(v,k) places vector v on the kth diagonal. k = 0 represents the main diagonal, k > 0 is
above the main diagonal, and k < 0 is below the main diagonal.
Examples
Create a symbolic matrix with the main diagonal specified by the vector v.
syms a b c
v = [a b c];
diag(v)
ans =
[ a, 0, 0]
[ 0, b, 0]
[ 0, 0, c]
Create a symbolic matrix with the second diagonal below the main diagonal specified by the vector v.
syms a b c
v = [a b c];
diag(v,-2)
ans =
[ 0, 0, 0, 0, 0]
[ 0, 0, 0, 0, 0]
[ a, 0, 0, 0, 0]
7-280
diag
[ 0, b, 0, 0, 0]
[ 0, 0, c, 0, 0]
syms x y z
A = magic(3).*[x, y, z];
diag(A)
ans =
8*x
5*y
2*z
syms x y z
A = magic(3).*[x, y, z];
diag(A,1)
ans =
y
7*z
Input Arguments
v — Diagonal elements
symbolic vector
Diagonal elements, specified as a symbolic vector. If v is a vector with N elements, then diag(v,k) is
a square matrix of order N + abs(k).
A — Input matrix
symbolic matrix
k — Diagonal number
integer
Diagonal number, specified as an integer. k = 0 represents the main diagonal, k > 0 is above the
main diagonal, and k < 0 is below the main diagonal.
Tips
• The trace of a matrix is equal to sum(diag(A)).
7-281
7 Functions
Version History
Introduced before R2006a
See Also
tril | triu
7-282
diff
diff
Differentiate symbolic expression or function
Syntax
Df = diff(f)
Df = diff(f,n)
Df = diff(f,var)
Df = diff(f,var,n)
Df = diff(f,var1,...,varN)
Df = diff(f,mvar)
Description
Df = diff(f) differentiates f with respect to the symbolic scalar variable determined by
symvar(f,1).
Df = diff(f,n) computes the nth derivative of f with respect to the symbolic scalar variable
determined by symvar.
Df = diff(f,var) differentiates f with respect to the differentiation parameter var. var can be a
symbolic scalar variable, such as x, a symbolic function, such as f(x), or a derivative function, such
as diff(f(t),t).
Examples
Differentiate Function
syms f(x)
f(x) = sin(x^2);
Df = diff(f,x)
Df(x) = 2 x cos x2
Df2 = Df(2)
Df2 = 4 cos 4
7-283
7 Functions
double(Df2)
ans = -2.6146
syms x t
Df = diff(sin(x*t^2))
Df = t2 cos t2 x
Because you did not specify the differentiation variable, diff uses the default variable determined by
symvar. For this expression, the default variable is x.
var = symvar(sin(x*t^2),1)
var = x
Now, find the derivative of this expression with respect to the variable t.
Df = diff(sin(x*t^2),t)
Df = 2 t x cos t2 x
syms t
D4 = diff(t^6,4)
D4 = 360 t2
D5 = diff(t^6,5)
D5 = 720 t
D6 = diff(t^6,6)
D6 = 720
Find the second derivative of the expression x*cos(x*y) with respect to the variable y.
syms x y
Df = diff(x*cos(x*y),y,2)
7-284
diff
Df = −x3 cos x y
Find the second derivative of the expression x*y. If you do not specify the differentiation variable,
diff uses the variable determined by symvar. Because symvar(x*y,1) returns x, diff computes
the second derivative of x*y with respect to x.
syms x y
Df = diff(x*y,2)
Df = 0
If you use nested diff calls and do not specify the differentiation variable, diff determines the
differentiation variable for each call. For example, find the second derivative of the expression x*y by
calling the diff function twice.
Df = diff(diff(x*y))
Df = 1
In the first call, diff differentiates x*y with respect to x and returns y. In the second call, diff
differentiates y with respect to y and returns 1.
Mixed Derivatives
syms x y
Df = diff(x*sin(x*y),x,y)
Df = 2 x cos x y − x2 y sin x y
You also can compute mixed higher-order derivatives by specifying all differentiation variables. Find
the mixed fourth derivative of the expression with respect to the variables x, x, x, and then y.
syms x y
Df = diff(x*sin(x*y),x,x,x,y)
2 df
Find the derivative of the function y = f (x) with respect to f (x).
dx
7-285
7 Functions
syms f(x) y
y = f(x)^2*diff(f(x),x);
Dy = diff(y,f(x))
Dy =
∂
2f x f x
∂x
2 df
Find the second derivative of the function y = f (x) with respect to f (x).
dx
Dy2 = diff(y,f(x),2)
Dy2 =
∂
2 f x
∂x
2 df df
Find the mixed derivative of the function y = f (x) with respect to f (x) and .
dx dx
Dy3 = diff(y,f(x),diff(f(x)))
Dy3 = 2 f x
Euler–Lagrange Equation
Find the Euler–Lagrange equation that describes the motion of a mass-spring system. Define the
kinetic and potential energy of the system.
syms x(t) m k
T = m/2*diff(x(t),t)^2;
V = k/2*x(t)^2;
L = T - V
L =
∂ 2
m ∂t x t kx t
2
−
2 2
D1 = diff(L,diff(x(t),t))
D1 =
∂
m xt
∂t
7-286
diff
D2 = diff(L,x)
D2(t) = −k x t
diff(D1,t) - D2 == 0
ans(t) =
∂2
m x t +kx t = 0
∂t2
To evaluate derivatives with respect to vectors, you can use symbolic matrix variables. For example,
find the derivatives ∂α/ ∂x and ∂α/ ∂y for the expression α = yT Ax, where y is a 3-by-1 vector, A is a 3-
by-4 matrix, and x is a 4-by-1 vector.
Create three symbolic matrix variables x, y, and A, of the appropriate sizes, and use them to define
alpha.
syms x [4 1] matrix
syms y [3 1] matrix
syms A [3 4] matrix
alpha = y.'*A*x
alpha = yT A x
Dx = diff(alpha,x)
Dx = yT A
Dy = diff(alpha,y)
Dy = xT AT
To evaluate derivatives with respect to matrices, you can use symbolic matrix variables. For example,
find the derivative ∂Y / ∂ A for the expression Y = X T AX, where X is a 3-by-1 vector, and A is a 3-by-3
matrix. Here, Y is a scalar that is a function of the vector X and the matrix A.
syms X [3 1] matrix
syms A [3 3] matrix
Y = X.'*A*X
Y = XT A X
7-287
7 Functions
D = diff(Y,A)
D = XT ⊗ X
size(D)
ans = 1×2
3 3
Find the derivative of the function t X = A ⋅ sin B ⋅ X , where A is a 1-by-3 matrix, B is a 3-by-2
matrix, and X is a 2-by-1 matrix. Create symbolic matrix variables to represent A, B, and X, and
create a symbolic matrix function to represent t X .
syms A [1 3] matrix
syms B [3 2] matrix
syms X [2 1] matrix
syms t(X) [1 1] matrix keepargs
t(X) = A*sin(B*X)
t(X) = A sin B X
Dt = diff(t,X)
Dt(X) = A cos B X ⊙ B
To find the gradient of a scalar expression with respect to a vector, you can use a symbolic matrix
variable as the differentiation parameter.
Create a symbolic matrix variable X to represent a vector with three components. To see how these
components are stored in Symbolic Math Toolbox™, use symmatrix2sym to display the elements of
the symbolic matrix variable.
syms X [1 3] matrix
symmatrix2sym(X)
7-288
diff
The components of the symbolic matrix variable are X1_1, X1_2, and X1_3. Create three symbolic
scalar variables for these components. Create a scalar symbolic expression expr using these scalar
variables.
Find the gradient of the scalar expression expr with respect to X. The diff function finds the first
partial derivatives of expr with respect to each component of X.
g = diff(expr,X)
g =
Σ1
where
Input Arguments
f — Expression or function to differentiate
symbolic expression | symbolic function | symbolic vector | symbolic matrix | symbolic matrix variable
| symbolic matrix function | numeric expression
• Symbolic expression
• Symbolic function
• Symbolic vector or symbolic matrix (a vector or a matrix of symbolic expressions or functions)
• Symbolic matrix variable
• Symbolic matrix function
• Numeric expression
If f is a symbolic vector or matrix, diff differentiates each element of f and returns a vector or a
matrix of the same size as f.
Data Types: sym | symfun | symmatrix | symfunmatrix | double | single
n — Order of derivative
nonnegative integer
7-289
7 Functions
If you specify differentiation with respect to the symbolic function var = f(x) or the derivative
function var = diff(f(x),x), then the first argument f must not contain any of these values:
Differentiation parameter in the form of a matrix, specified as a symbolic matrix variable or symbolic
matrix function.
When using a symbolic matrix variable as the differentiation parameter, f must be a differentiable
scalar function or expression, where mvar can represent a scalar, vector, or matrix. The derivative of
f cannot be a tensor or a matrix in terms of tensors. For examples, see “Differentiate with Respect to
Vectors” on page 7-287 and “Differentiate with Respect to Matrix” on page 7-287.
Data Types: symmatrix | symfunmatrix
Limitations
• The diff function does not support tensor derivatives when using a symbolic matrix variable as
the differentiation parameter. If the derivative is a tensor, or the derivative is a matrix in terms of
tensors, then the diff function generates an error.
Tips
• When computing mixed higher-order derivatives with more than one variable, do not use n to
specify the order of the derivative. Instead, specify all differentiation variables explicitly.
• To improve performance, diff assumes that all mixed derivatives commute. For example,
∂ ∂ ∂ ∂
f x, y = f x, y
∂x ∂y ∂y ∂x
7-290
diff
• If you differentiate an expression or function containing abs or sign, the arguments must be real
values. For complex arguments of abs and sign, the diff function formally computes the
derivative, but this result is not generally valid because abs and sign are not differentiable over
complex numbers.
Version History
Introduced before R2006a
The diff function can differentiate expressions or functions of type sym, symfun, symmatrix,
symfunmatrix, double, and single with respect to differentiation parameters of type symmatrix
and symfunmatrix. For an example, see “Find Gradient with Respect to Vector” on page 7-288.
The diff function accepts an input argument of type symfunmatrix. You can differentiate symbolic
matrix functions with respect to differentiation parameters of type sym, symfun, symmatrix,
symfunmatrix, double, and single. For an example, see “Differentiate Symbolic Matrix Function”
on page 7-288.
The diff function accepts an input argument of type symmatrix. You can differentiate symbolic
matrix variables with respect to differentiation parameters of type sym, symfun, symmatrix,
double, and single. For examples, see “Differentiate with Respect to Vectors” on page 7-287 and
“Differentiate with Respect to Matrix” on page 7-287.
See Also
Functions
curl | divergence | functionalDerivative | gradient | hessian | int | jacobian |
laplacian | symvar
Topics
“Differentiation” on page 3-171
“Find Asymptotes, Critical, and Inflection Points” on page 3-212
External Websites
Calculus Derivatives (MathWorks Teaching Resources)
Beam Bending and Deflection (MathWorks Teaching Resources)
7-291
7 Functions
digits
Change variable precision used
Syntax
digits(d)
d1 = digits
d1 = digits(d)
Description
digits(d) sets the precision used by vpa to d significant decimal digits. The default is 32 digits.
d1 = digits(d) sets the new precision d and returns the old precision in d1.
Examples
Increase Precision of Results
By default, MATLAB uses 16 digits of precision. For higher precision, use vpa. The default precision
for vpa is 32 digits. Increase precision beyond 32 digits by using digits.
Find pi using vpa, which uses the default 32 digits of precision. Confirm that the current precision is
32 by using digits.
pi32 = vpa(pi)
pi32 =
3.1415926535897932384626433832795
currentPrecision = digits
currentPrecision =
32
Save the current value of digits in digitsOld and set the new precision to 100 digits. Find pi
using vpa. The result has 100 digits.
digitsOld = digits(100);
pi100 = vpa(pi)
pi100 =
3.1415926535897932384626433832795028841971693993751058209...
74944592307816406286208998628034825342117068
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.
7-292
digits
digits(digitsOld)
For more information, see “Increase Precision of Numeric Calculations” on page 2-36.
Increase the speed of MATLAB calculations by using vpa with a lower precision. Set the lower
precision by using digits.
input = 1:0.01:500;
tic
zeta(input);
toc
Now, repeat the operation with a lower precision by using vpa. Lower the precision to 10 digits by
using digits. Then, use vpa to reduce the precision of input and perform the same operation. The
time taken decreases significantly.
digitsOld = digits(10);
vpaInput = vpa(input);
tic
zeta(vpaInput);
toc
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(digitsOld)
For more information, see “Increase Speed by Reducing Precision” on page 3-321.
Guard Digits
The number of digits that you specify using the vpa function or the digits function is the
guaranteed number of digits. Internally, the toolbox can use a few more digits than you specify. These
additional digits are called guard digits. For example, set the number of digits to 4, and then display
the floating-point approximation of 1/3 using four digits:
old = digits(4);
a = vpa(1/3)
a =
0.3333
Now, display a using 20 digits. The result shows that the toolbox internally used more than four digits
when computing a. The last digits in the following result are incorrect because of the round-off error:
7-293
7 Functions
digits(20)
vpa(a)
digits(old)
ans =
0.33333333333303016843
Hidden round-off errors can cause unexpected results. For example, compute the number 1/10 with
the default 32-digit accuracy and with 10-digit accuracy:
a = vpa(1/10)
old = digits(10);
b = vpa(1/10)
digits(old)
a =
0.1
b =
0.1
ans =
0.000000000000000000086736173798840354720600815844403
The difference a - b is not equal to zero because the toolbox internally boosts the 10-digit number b
= 0.1 to 32-digit accuracy. This process implies round-off errors. The toolbox actually computes the
difference a - b as follows:
b = vpa(b)
a - b
b =
0.09999999999999999991326382620116
ans =
0.000000000000000000086736173798840354720600815844403
Suppose you convert a double number to a symbolic object, and then perform VPA operations on that
object. The results can depend on the conversion technique that you used to convert a floating-point
number to a symbolic object. The sym function lets you choose the conversion technique by specifying
the optional second argument, which can be 'r', 'f', 'd', or 'e'. The default is 'r'. For example,
convert the constant π = 3.141592653589793... to a symbolic object:
r = sym(pi)
f = sym(pi,'f')
d = sym(pi,'d')
e = sym(pi,'e')
r =
pi
7-294
digits
f =
884279719003555/281474976710656
d =
3.1415926535897931159979634685442
e =
pi - (198*eps)/359
Although the toolbox displays these numbers differently on the screen, they are rational
approximations of pi. Use vpa to convert these rational approximations of pi back to floating-point
values.
Set the number of digits to 4. Three of the four approximations give the same result.
digits(4)
vpa(r)
vpa(f)
vpa(d)
vpa(e)
ans =
3.142
ans =
3.142
ans =
3.142
ans =
3.142 - 0.5515*eps
Now, set the number of digits to 40. The differences between the symbolic approximations of pi
become more visible.
digits(40)
vpa(r)
vpa(f)
vpa(d)
vpa(e)
ans =
3.141592653589793238462643383279502884197
ans =
3.141592653589793115997963468544185161591
ans =
3.1415926535897931159979634685442
ans =
3.141592653589793238462643383279502884197 -...
0.5515320334261838440111420612813370473538*eps
7-295
7 Functions
Input Arguments
d — New accuracy setting
number | symbolic number
New accuracy setting, specified as a number or symbolic number. The setting specifies the number of
significant decimal digits to be used for variable-precision calculations. If the value d is not an
integer, digits rounds it to the nearest integer.
Output Arguments
d1 — Current accuracy setting
double-precision number
Current accuracy setting, returned as a double-precision number. The setting specifies the number of
significant decimal digits currently used for variable-precision calculations.
Version History
Introduced before R2006a
See Also
double | vpa
Topics
“Increase Precision of Numeric Calculations” on page 2-36
“Recognize and Avoid Round-Off Errors” on page 3-317
“Increase Speed by Reducing Precision” on page 3-321
“Change Output Format of Symbolic and Variable-Precision Arithmetic” on page 2-8
7-296
dilog
dilog
Dilogarithm function
Syntax
dilog(X)
Description
dilog(X) returns the dilogarithm function.
Examples
Dilogarithm Function for Numeric and Symbolic Arguments
Compute the dilogarithm function for these numbers. Because these numbers are not symbolic
objects, dilog returns floating-point results.
A =
2.4674 - 2.1776i 1.6449 + 0.0000i 0.9785 + 0.0000i...
0.5822 + 0.0000i 0.0000 + 0.0000i -0.8225 + 0.0000i
Compute the dilogarithm function for the numbers converted to symbolic objects. For many symbolic
(exact) numbers, dilog returns unresolved symbolic calls.
symA =
[ pi^2/4 - pi*log(2)*1i, pi^2/6, dilog(1/4), pi^2/12 - log(2)^2/2, 0, -pi^2/12]
vpa(symA)
ans =
[ 2.467401100272339654708622749969 - 2.1775860903036021305006888982376i,...
1.644934066848226436472415166646,...
0.97846939293030610374306666652456,...
0.58224052646501250590265632015968,...
0,...
-0.82246703342411321823620758332301]
7-297
7 Functions
syms x
fplot(dilog(x),[0 10])
grid on
Many functions, such as diff, int, and limit, can handle expressions containing dilog.
ans =
-log(x)/(x - 1)
ans =
log(x)/(x - 1)^2 - 1/(x*(x - 1))
ans =
x*(dilog(x) + log(x) - 1) - dilog(x)
7-298
dilog
limit(dilog(x)/x, Inf)
ans =
0
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
More About
Dilogarithm Function
Tips
• dilog(sym(-1)) returns pi^2/4 - pi*log(2)*i.
• dilog(sym(0)) returns pi^2/6.
• dilog(sym(1/2)) returns pi^2/12 - log(2)^2/2.
• dilog(sym(1)) returns 0.
• dilog(sym(2)) returns -pi^2/12.
• dilog(sym(i)) returns pi^2/16 - (pi*log(2)*i)/4 - catalan*i.
• dilog(sym(-i)) returns catalan*i + (pi*log(2)*i)/4 + pi^2/16.
• dilog(sym(1 + i)) returns - catalan*i - pi^2/48.
• dilog(sym(1 - i)) returns catalan*i - pi^2/48.
• dilog(sym(Inf)) returns -Inf.
Version History
Introduced in R2014a
7-299
7 Functions
References
[1] Stegun, I. A. “Miscellaneous Functions.” Handbook of Mathematical Functions with Formulas,
Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New York: Dover,
1972.
See Also
log | zeta
7-300
dirac
dirac
Dirac delta function
Syntax
d = dirac(x)
d = dirac(n,x)
Description
d = dirac(x) represents the Dirac delta function on page 7-304 of x.
Examples
Handle Expressions Involving Dirac and Heaviside Functions
Compute derivatives and integrals of expressions involving the Dirac delta and Heaviside functions.
Find the first and second derivatives of the Heaviside function. The result is the Dirac delta function
and its first derivative.
syms x
diff(heaviside(x), x)
diff(heaviside(x), x, x)
ans =
dirac(x)
ans =
dirac(1, x)
Find the indefinite integral of the Dirac delta function. The results returned by int do not include
integration constants.
int(dirac(x), x)
ans =
sign(x)/2
Find the integral of the sine function involving the Dirac delta function.
syms a
int(dirac(x - a)*sin(x), x, -Inf, Inf)
ans =
sin(a)
7-301
7 Functions
syms x real
assumeAlso(x ~= 0)
dirac(x)
ans =
0
syms x
Compute the Dirac delta function of x and its first three derivatives.
Use a vector n = [0,1,2,3] to specify the order of derivatives. The dirac function expands the
scalar into a vector of the same size as n and computes the result.
syms x
n = [0,1,2,3];
d = dirac(n,x)
d =
[ dirac(x), dirac(1, x), dirac(2, x), dirac(3, x)]
Substitute x with 0.
subs(d,x,0)
ans =
[ Inf, -Inf, Inf, -Inf]
You can use fplot to plot the Dirac delta function over the default interval [-5 5]. However,
dirac(x) returns Inf at x equal to 0, and fplot does not plot the infinity.
Declare a symbolic variable x and plot the symbolic expression dirac(x) by using fplot.
syms x
fplot(dirac(x))
7-302
dirac
To handle the infinity at x equal to 0, use numeric values instead of symbolic values. Set the Inf
value to 1 and plot the Dirac delta function by using stem.
x = -1:0.1:1;
y = dirac(x);
idx = y == Inf; % find Inf
y(idx) = 1; % set Inf to finite value
stem(x,y)
7-303
7 Functions
Input Arguments
x — Input
number | symbolic number | symbolic variable | symbolic expression | symbolic function | vector |
matrix | multidimensional array
Input, specified as a number, symbolic number, variable, expression, or function, representing a real
number. This input can also be a vector, matrix, or multidimensional array of numbers, symbolic
numbers, variables, expressions, or functions.
n — Order of derivative
nonnegative number | symbolic variable | symbolic expression | symbolic function | vector | matrix |
multidimensional array
More About
Dirac Delta Function
The Dirac delta function, δ(x), has the value 0 for all x ≠ 0, and ∞ for x = 0. The Dirac delta function
satisfies the identity
7-304
dirac
−∞
∫ δ(x) dx = 1 .
This is a heuristic definition of the Dirac delta function. A rigorous definition of the Dirac delta
function requires the theory of distributions or measure theory.
For any smooth function f and a real number a, the Dirac delta function has the property
∞
−∞
∫ δ(x − a) f (x) = f (a) .
Tips
• For complex values x with nonzero imaginary parts, dirac returns NaN.
• dirac returns floating-point results for numeric arguments that are not symbolic objects.
• dirac acts element-wise on nonscalar inputs.
• The input arguments x and n must be vectors or matrices of the same size, or else one of them
must be a scalar. If one input argument is a scalar and the other one is a vector or a matrix, then
dirac expands the scalar into a vector or matrix of the same size as the other argument with all
elements equal to that scalar.
Version History
Introduced before R2006a
See Also
heaviside | kroneckerDelta
7-305
7 Functions
displayFormula
Display symbolic formula from string
Syntax
displayFormula(symstr)
displayFormula(symstr,old,new)
Description
displayFormula(symstr) displays the symbolic formula from the string symstr without
evaluating the operations. All workspace variables that are specified in symstr are replaced by their
values.
Examples
Create a 3-by-3 matrix. Multiply the matrix by the scalar coefficient K^2.
syms K A
A = [-1, 0, 1; 1, 2, 0; 1, 1, 0];
B = K^2*A
B =
−K 2 0 K2
K2 2 K2 0
K2 K2 0
The result automatically shows the multiplication being carried out element-wise.
Show the multiplication formula without evaluating the operations by using displayFormula. Input
the formula as a string. The variable A in the string is replaced by its values.
displayFormula("F = K^2*A")
−1 0 1
F = K2 1 2 0
1 10
Create a 3-by-3 matrix and a 3-by-1 vector. Create a symbolic equation that multiplies the matrix and
the vector.
7-306
displayFormula
syms A [3 3]
syms v B [3 1]
eqn = B == A*v
eqn =
B1 = A1, 1 v1 + A1, 2 v2 + A1, 3 v3
B2 = A2, 1 v1 + A2, 2 v2 + A2, 3 v3
B3 = A3, 1 v1 + A3, 2 v2 + A3, 3 v3
The result shows the multiplication being carried out where the elements of the matrix and the vector
are combined.
Show the multiplication formula without combining the elements by using displayFormula. Input
the formula as a string.
displayFormula("B == A*v")
S = "m*diff(y,t,t) == m*g-k*y";
Create a string array that combines the differential equation and additional text. Display the formula
along with the text.
∂2
m y = mg−ky
∂t2
S = "exp(2*pi*i)";
7-307
7 Functions
symstr =
"1 + S + S^2 + cos(S)"
displayFormula(symstr)
2
1 + e2 π i + e2 π i + cos e2 π i
S = str2sym(S)
S = 1
expr = str2sym(symstr)
2
expr = S + cos S + S + 1
Substitute the variable S with its value by using subs. Evaluate the result in double precision using
double.
double(subs(expr))
ans = 3.5403
Define a string that represents a quadratic formula with the coefficients a, b, and c.
syms a b c k
symstr = "a*x^2 + b*x + c";
displayFormula(symstr,a,k)
k x2 + b x + c
Display the quadratic formula again, replacing a, b, and c with 2, 3, and -1, respectively.
2 x2 + 3 x − 1
To solve the quadratic equation, convert the string into a symbolic expression using str2sym. Use
solve to find the zeros of the quadratic equation.
f = str2sym(symstr);
sol = solve(f)
sol =
7-308
displayFormula
2
b+ b −4ac
−
2a
2
b− b −4ac
−
2a
Use subs to replace a, b, and c in the solution with 2, 3, and -1, respectively.
solValues =
17 3
− −
4 4
17 3
−
4 4
Input Arguments
symstr — String representing symbolic formula
character vector | string scalar | cell array of character vectors | string array
String representing a symbolic formula, specified as a character vector, string scalar, cell array of
character vectors, or string array.
You can also combine a string that represents a symbolic formula with regular text (enclosed in single
quotation marks) as a string array. For an example, see “Display Differential Equation” on page 7-307.
Expression or variable to be replaced, specified as a character vector, string scalar, cell array of
character vectors, string array, symbolic variable, function, expression, or array.
New value, specified as a number, character vector, string scalar, cell array of character vectors,
string array, symbolic number, variable, expression, or array.
Version History
Introduced in R2019b
See Also
str2sym | subs | syms | sym | solve
7-309
7 Functions
divergence
Divergence of symbolic vector field
Syntax
d = divergence(V,X)
d = divergence(V)
Description
d = divergence(V,X) returns the divergence on page 7-315 of symbolic vector field V with respect
to vector X in Cartesian coordinates. Vectors V and X must have the same length.
d = divergence(V) returns the divergence of the vector field V with respect to a default vector
constructed from the symbolic variables in V.
Examples
Find the divergence of the vector field V x, y, z = x, 2y2, 3z3 with respect to vector X = x, y, z .
syms x y z
V = [x 2*y^2 3*z^3];
X = [x y z];
div = divergence(V,X)
div = 9 z2 + 4 y + 1
divCurl = 0
Find the divergence of the gradient of the scalar field f x, y, z = x2 + y2 + z2. The result is the
Laplacian of the scalar field.
syms x y z
f = x^2 + y^2 + z^2;
divGrad = divergence(gradient(f,X),X)
divGrad = 6
Gauss’s Law in differential form states that the divergence of an electric field is proportional to the
electric charge density.
7-310
divergence
→ →→ →
ρ( r )
∇ ⋅ E( r ) =
ϵ0
→
Find the electric charge density for the electric field E = x2 i + y2 j.
syms x y ep0
E = [x^2 y^2];
rho = divergence(E,[x y])*ep0
rho = ep0 2 x + 2 y
Visualize the electric field and electric charge density for −2 < x < 2 and −2 < y < 2 with ep0 = 1.
Create a grid of values of x and y using meshgrid. Find the values of the electric field and charge
density by substituting grid values using subs. Simultaneously substitute the grid values xPlot and
yPlot into the charge density rho by using cell arrays as inputs to subs.
rho = subs(rho,ep0,1);
v = -2:0.1:2;
[xPlot,yPlot] = meshgrid(v);
Ex = subs(E(1),x,xPlot);
Ey = subs(E(2),y,yPlot);
rhoPlot = double(subs(rho,{x,y},{xPlot,yPlot}));
Plot the electric field using quiver. Overlay the charge density using contour. The contour lines
indicate the values of the charge density.
quiver(xPlot,yPlot,Ex,Ey)
hold on
contour(xPlot,yPlot,rhoPlot,"ShowText","on")
title("Contour Plot of Charge Density Over Electric Field")
xlabel("x")
ylabel("y")
7-311
7 Functions
Derive the electromagnetic wave equation in free space without charge and without current sources
from Maxwell's equations.
First, create symbolic scalar variables to represent the vacuum permeability and permittivity. Create
a symbolic matrix variable to represent the Cartesian coordinates. Create two symbolic matrix
functions to represent the electric and magnetic fields as functions of space and time.
Maxwell1 = divergence(E,X) == 0
Maxwell1(X, t) = ∇ X · E X, t = 01, 1
Maxwell2(X, t) =
∂
∇ X × E X, t = − B X, t
∂t
7-312
divergence
Maxwell3 = divergence(B,X) == 0
Maxwell3(X, t) = ∇ X · B X, t = 01, 1
Maxwell4(X, t) =
∂
∇ X × B X, t = ε0 μ0 E X, t
∂t
Then, find the wave equation for the electric field. Compute the curl of the second Maxwell equation.
wave_E = curl(Maxwell2,X)
wave_E(X, t) =
∂
∇ X ∇ X · E X, t − ΔX E X, t = − ∇ X × B X, t
∂t
Substitute the first Maxwell equation in the electric field wave equation. Use lhs and rhs to obtain
the left and right sides of the first Maxwell equation.
wave_E = subs(wave_E,lhs(Maxwell1),rhs(Maxwell1))
wave_E(X, t) =
∂
−ΔX E X, t = − ∇ X × B X, t
∂t
dMaxwell4 = diff(Maxwell4,t)
dMaxwell4(X, t) =
∂ ∂ ∂
∇X × B X, t = ε0 μ0 E X, t
∂t ∂t ∂t
∂
Substitute the term that involves the magnetic field ∇ X × ∂t
B X, t in wave_E with the right side of
dMaxwell4. Use lhs and rhs to obtain these terms from dMaxwell4.
wave_E = subs(wave_E,lhs(dMaxwell4),rhs(dMaxwell4))
wave_E(X, t) =
∂ ∂
−ΔX E X, t = − ε0 μ0 E X, t
∂t ∂t
Using similar steps, you can also find the wave equation for the magnetic field.
wave_B = curl(Maxwell4,X)
wave_B(X, t) =
∂
∇ X ∇ X · B X, t − ΔX B X, t = ε0 μ0 ∇X × E X, t
∂t
wave_B = subs(wave_B,lhs(Maxwell3),rhs(Maxwell3))
wave_B(X, t) =
∂
−ΔX B X, t = ε0 μ0 ∇X × E X, t
∂t
dMaxwell2 = diff(Maxwell2,t)
7-313
7 Functions
dMaxwell2(X, t) =
∂ ∂ ∂
∇X × E X, t = − B X, t
∂t ∂t ∂t
wave_B = subs(wave_B,lhs(dMaxwell2),rhs(dMaxwell2))
wave_B(X, t) =
∂ ∂
−ΔX B X, t = − ε0 μ0 B X, t
∂t ∂t
Input Arguments
V — Symbolic vector field
vector of symbolic scalar variables | symbolic function | symbolic matrix variable | symbolic matrix
function
Symbolic vector field, specified as a vector of symbolic scalar variables, symbolic function, symbolic
matrix variable, or symbolic matrix function. V must have the same length as X.
• If V is a function of symbolic scalar variables, where V is of type sym or symfun, then the vector X
must be of type sym or symfun.
• If V is a function of symbolic matrix variables, where V is of type symmatrix or symfunmatrix,
then the vector X must be of type symmatrix or symfunmatrix.
Vector with respect to which you find the divergence, specified as a vector of symbolic scalar
variables, symbolic function, symbolic matrix variable, or symbolic matrix function. X must have the
same length as V.
• If you do not specify X and V is a function of symbolic scalar variables, then, by default,
divergence constructs vector X from the symbolic scalar variables in V with the order of
variables as defined by symvar(V).
• If X is a symbolic matrix variable of type symmatrix, then X must have a size of 1-by-N or N-by-1.
• If V and X are scalars, then divergence(V,X) = diff(V,X).
Limitations
• The divergence function does not support tensor derivatives. If the input V is a tensor field or a
matrix rather than a vector, then the divergence function returns an error.
• Symbolic Math Toolbox currently does not support the dot or cross functions for symbolic matrix
variables and functions of type symmatrix and symfunmatrix. If vector calculus identities
involve dot or cross products, then the toolbox displays those identities in terms of other
supported functions instead. To see a list of all the functions that support symbolic matrix
variables and functions, use the commands methods symmatrix and methods symfunmatrix.
7-314
divergence
More About
Divergence of Symbolic Vector Field
The divergence of the symbolic vector field V = (V1,...,Vn) with respect to the vector X = (X1,...,Xn) in
Cartesian coordinates is the sum of partial derivatives of V with respect to X1,...,Xn.
n ∂V i
div(V ) = ∇ X ⋅ V = ∑ ∂ Xi
i=1
Version History
Introduced in R2012a
The divergence function accepts symbolic matrix variables and functions of type symmatrix and
symfunmatrix as input arguments. For example, see “Derive Electromagnetic Wave Equation” on
page 7-312.
See Also
curl | diff | gradient | jacobian | hessian | laplacian | potential | vectorPotential
7-315
7 Functions
divisors
Divisors of integer or expression
Syntax
divisors(n)
divisors(expr,vars)
Description
divisors(n) finds all nonnegative divisors of an integer n.
divisors(expr,vars) finds the divisors of a polynomial expression expr. Here, vars are
polynomial variables.
Examples
Divisors of Integers
Find the divisors of integers. You can use double precision numbers or numbers converted to
symbolic objects. If you call divisors for a double-precision number, then it returns a vector of
double-precision numbers.
divisors(42)
ans =
1 2 3 6 7 14 21 42
Find the divisors of negative integers. divisors returns nonnegative divisors for negative integers.
divisors(-42)
ans =
1 2 3 6 7 14 21 42
divisors(sym(42))
ans =
[ 1, 2, 3, 6, 7, 14, 21, 42]
divisors(0)
ans =
0
7-316
divisors
Find the divisors of this univariate polynomial. You can specify the polynomial as a symbolic
expression.
syms x
divisors(x^4 - 1, x)
ans =
[ 1, x - 1, x + 1, (x - 1)*(x + 1), x^2 + 1, (x^2 + 1)*(x - 1),...
(x^2 + 1)*(x + 1), (x^2 + 1)*(x - 1)*(x + 1)]
ans(t) =
[ 1, t, t^2, t^3, t^4, t^5]
When finding the divisors of a polynomial, divisors does not return the divisors of the constant
factor.
f(t) = 9*t^5;
divisors(f,t)
ans(t) =
[ 1, t, t^2, t^3, t^4, t^5]
Find the divisors of the multivariate polynomial expression. Suppose that u and v are variables, and a
is a symbolic parameter. Specify the variables as a symbolic vector.
syms a u v
divisors(a*u^2*v^3, [u,v])
ans =
[ 1, u, u^2, v, u*v, u^2*v, v^2, u*v^2, u^2*v^2, v^3, u*v^3, u^2*v^3]
Now, suppose that this expression contains only one variable (for example, v), while a and u are
symbolic parameters. Here, divisors treats the expression a*u^2 as a constant and ignores it,
returning only the divisors of v^3.
divisors(a*u^2*v^3, v)
ans =
[ 1, v, v^2, v^3]
Input Arguments
n — Number for which to find divisors
number | symbolic number
7-317
7 Functions
Number for which to find the divisors, specified as a number or symbolic number.
Polynomial expression for which to find divisors, specified as a symbolic expression or symbolic
function.
Tips
• divisors(0) returns 0.
• divisors(expr,vars) does not return the divisors of the constant factor when finding the
divisors of a polynomial.
• If you do not specify polynomial variables, divisors returns as many divisors as it can find,
including the divisors of constant symbolic expressions. For example,
divisors(sym(pi)^2*x^2) returns [ 1, pi, pi^2, x, pi*x, pi^2*x, x^2, pi*x^2,
pi^2*x^2] while divisors(sym(pi)^2*x^2, x) returns [ 1, x, x^2].
• For rational numbers, divisors returns all divisors of the numerator divided by all divisors of the
denominator. For example, divisors(sym(9/8)) returns [ 1, 3, 9, 1/2, 3/2, 9/2,
1/4, 3/4, 9/4, 1/8, 3/8, 9/8].
Version History
Introduced in R2014b
See Also
coeffs | factor | numden
7-318
double
double
Convert symbolic values to MATLAB double precision
Syntax
d = double(s)
Description
d = double(s) converts the symbolic values s to double precision. Converting symbolic values to
double precision is useful when a MATLAB function does not accept symbolic values. For differences
between symbolic and double-precision numbers, see “Choose Numeric or Symbolic Arithmetic” on
page 2-32.
Examples
Convert symbolic numbers to double precision by using double. Symbolic numbers are exact, while
double-precision numbers have round-off errors.
1
Convert π and 3 from symbolic form to double precision.
symN =
1
π
3
doubleN = double(symN)
doubleN = 1×2
3.1416 0.3333
For information on round-off errors, see “Recognize and Avoid Round-Off Errors” on page 3-317.
Variable-precision numbers created by vpa are symbolic values. When a MATLAB function does not
accept symbolic values, convert variable precision to double precision by using double.
1
Convert π and 3 from variable-precision form to double precision.
7-319
7 Functions
doubleN = double(vpaN)
doubleN = 1×2
3.1416 0.3333
Convert the symbolic numbers in matrix symM to double-precision numbers by using double.
a = sym(sqrt(2));
b = sym(2/3);
symM = [a b; a*b b/a]
symM =
2
2
3
2 2 2
3 3
doubleM = double(symM)
doubleM = 2×2
1.4142 0.6667
0.9428 0.4714
High-Precision Conversion
When converting symbolic expressions that suffer from internal cancellation or round-off errors,
increase the working precision by using digits before converting the number.
Convert a numerically unstable expression Y with double. Then, increase precision to 100 digits by
using digits and convert Y again. This high-precision conversion is accurate, while the low-
precision conversion is not.
Y = ((exp(sym(200)) + 1)/(exp(sym(200)) - 1)) - 1;
lowPrecisionY = double(Y)
lowPrecisionY = 0
digitsOld = digits(100);
highPrecisionY = double(Y)
highPrecisionY = 2.7678e-87
7-320
double
Solve the trigonometric equation sin 2x + cos x = 0 by using solve. Set the ReturnConditions
option to true to return the complete solution, parameters used in the solution, and conditions on
those parameters.
syms x
eqn = sin(2*x) + cos(x) == 0;
[solx,params,conds] = solve(eqn,x,ReturnConditions=true)
solx =
π
+πk
2
π
2πk−
6
7π
+2πk
6
params = k
conds =
k∈ℤ
k∈ℤ
k∈ℤ
The solver does not create the variable k for the parameters in the MATLAB® workspace. Create this
variable. Find the solutions for k = 2 by using subs.
syms k
sols_k2 = subs(solx,k,2)
sols_k2 =
5π
2
23 π
6
31 π
6
The solutions are exact symbolic numbers. Convert these numbers to double-precision numbers.
doublesols_k2 = double(sols_k2)
doublesols_k2 = 3×1
7.8540
12.0428
16.2316
7-321
7 Functions
Create a symbolic expression S that represents A2 − 2A + I2, where A is a 2-by-2 symbolic matrix
variable.
syms A 2 matrix
S = A*A - 2*A + eye(2)
S = I2 − 2 A + A2
π π
cos 5
sin 4
Substitute A with symbolic numbers .
−1 0
symS =
−2 Σ1 + Σ12 + I2
where
5 1 2
+
Σ1 = 4 4 2
−1 0
doubleS = double(symS)
doubleS = 2×2
-0.6706 -0.8422
1.1910 0.2929
Input Arguments
s — Symbolic input
symbolic number | array of symbolic numbers | symbolic matrix variable of numbers
Symbolic input, specified as a symbolic number, array of symbolic numbers, or symbolic matrix
variable of numbers. If the input contains only numeric values (does not contain symbolic numbers),
then the MATLAB double function is called.
Data Types: sym | symmatrix
Version History
Introduced before R2006a
7-322
double
You can convert a symbolic matrix variable of numbers of type symmatrix to a double-precision
matrix of type double. For an example, see “Convert Symbolic Matrix Variable of Numbers to Double
Precision” on page 7-321.
See Also
sym | vpa | subs
Topics
“Choose Numeric or Symbolic Arithmetic” on page 2-32
“Increase Precision of Numeric Calculations” on page 2-36
“Recognize and Avoid Round-Off Errors” on page 3-317
“Increase Speed by Reducing Precision” on page 3-321
“Change Output Format of Symbolic and Variable-Precision Arithmetic” on page 2-8
7-323
7 Functions
dsolve
Solve system of differential equations
Syntax
S = dsolve(eqn)
S = dsolve(eqn,cond)
S = dsolve( ___ ,Name,Value)
Description
S = dsolve(eqn) solves the differential equation eqn, where eqn is a symbolic equation. Use diff
and == to represent differential equations. For example, diff(y,x) == y represents the equation
dy/dx = y. Solve a system of differential equations by specifying eqn as a vector of those equations.
S = dsolve( ___ ,Name,Value) uses additional options specified by one or more Name,Value
pair arguments.
Examples
Specify the first-order derivative by using diff and the equation by using ==. Then, solve the
equation by using dsolve.
syms y(t) a
eqn = diff(y,t) == a*y;
S = dsolve(eqn)
S = C1 ea t
The solution includes a constant. To eliminate constants, see “Solve Differential Equations with
Conditions” on page 7-325. For a full workflow, see “Solve Partial Differential Equation of Tsunami
Model” on page 3-54.
7-324
dsolve
Specify the second-order derivative of y by using diff(y,t,2) and the equation by using ==. Then,
solve the equation by using dsolve.
syms y(t) a
eqn = diff(y,t,2) == a*y;
ySol(t) = dsolve(eqn)
ySol(t) = C1 e− a t + C2 e a t
Specify the initial condition as the second input to dsolve by using the == operator. Specifying
condition eliminates arbitrary constants, such as C1, C2, ..., from the solution.
syms y(t) a
eqn = diff(y,t) == a*y;
cond = y(0) == 5;
ySol(t) = dsolve(eqn,cond)
ySol(t) = 5 ea t
2
d y
Next, solve the second-order differential equation 2
= a2 y with the initial conditions y(0) = b and
dt
y′(0) = 1.
Specify the second initial condition by assigning diff(y,t) to Dy and then using Dy(0) == 1.
syms y(t) a b
eqn = diff(y,t,2) == a^2*y;
Dy = diff(y,t);
cond = [y(0)==b, Dy(0)==1];
ySol(t) = dsolve(eqn,cond)
ySol(t) =
ea t a b + 1 e−a t a b − 1
+
2a 2a
This second-order differential equation has two specified conditions, so constants are eliminated from
the solution. In general, to eliminate constants from the solution, the number of conditions must
equal the order of the equation.
dy
=z
dt
dz
= − y.
dt
7-325
7 Functions
Specify the system of equations as a vector. dsolve returns a structure containing the solutions.
ySol(t) = S.y
zSol(t) = S.z
When solving for multiple functions, dsolve returns a structure by default. Alternatively, you can
assign solutions to functions or variables directly by explicitly specifying the outputs as a vector.
dsolve sorts the outputs in alphabetical order using symvar.
∂
Solve the differential equation y(t) = e−y(t) + y(t). dsolve returns an explicit solution in terms of a
∂t
Lambert W function that has a constant value.
syms y(t)
eqn = diff(y) == y+exp(-y)
eqn(t) =
∂
y t = e−y t + y t
∂t
sol = dsolve(eqn)
sol = W0 −1
7-326
dsolve
To return implicit solutions of the differential equation, set the 'Implicit' option to true. An
implicit solution has the form F(y(t)) = g(t).
sol = dsolve(eqn,'Implicit',true)
sol =
y
∫ y eey + 1 dy
y=yt
= C1 + t
e−y t ey t y t + 1 = 0
If dsolve cannot find an explicit solution of a differential equation analytically, then it returns an
empty symbolic array. You can solve the differential equation by using MATLAB® numerical solver,
such as ode45. For more information, see “Solve a Second-Order Differential Equation Numerically”
on page 3-52.
syms y(x)
eqn = diff(y) == (x-exp(-x))/(y(x)+exp(y(x)));
S = dsolve(eqn)
S =
[ empty sym ]
Alternatively, you can try finding an implicit solution of the differential equation by specifying the
'Implicit' option to true. An implicit solution has the form F(y(x)) = g(x).
S = dsolve(eqn,'Implicit',true)
S =
2
yx x2
ey x + = C1 + e−x +
2 2
dy a
Solve the differential equation dt
= + y with condition y(a) = 1. By default, dsolve applies
y
simplifications that are not generally correct, but produce simpler solutions. For more details, see
“Algorithms” on page 7-332.
syms a y(t)
eqn = diff(y) == a/sqrt(y) + y;
cond = y(a) == 1;
ySimplified = dsolve(eqn,cond)
ySimplified =
7-327
7 Functions
3t 3a 2/3
e 2 − 2 + log a + 1 − a
To return the solutions that include all possible values of the parameter a, turn off simplifications by
setting 'IgnoreAnalyticConstraints' to false.
yNotSimplified = dsolve(eqn,cond,'IgnoreAnalyticConstraints',false)
yNotSimplified =
π
σ1 if − < σ2
2
3t 3a 1 3/2 2/3 if C2 ∈ ℤ
1 π
σ1, − −a + e 2 − 2 + log a + − 2 + σ3 + 2 π C2 i + σ3 if σ2 ≤ −
2 2
∅ if C2 ∉ ℤ
where
3t 3a 2/3
σ1 = −a + e 2 − 2 + log a + 1 + 2 π C2 i
3 C1 3t
σ2 = angle e 2 + 2 − a
3 i
σ3 =
2
∂2 ∂ 2
Solve the second-order differential equation (x2 − 1) y(x) + (x + 1) y(x) − y(x) = 0. dsolve
∂x 2 ∂x
returns a solution that contains a term with unevaluated integral.
syms y(x)
eqn = (x^2-1)^2*diff(y,2) + (x+1)*diff(y) - y == 0;
S = dsolve(eqn)
S =
1 1/4
C2 x + 1 + C1 x + 1 ∫ e2 x − 1 1 − x
x+1
9/4
dx
To return series solutions of the differential equation around x = − 1, set the 'ExpansionPoint' to
-1. dsolve returns two linearly independent solutions in terms of a Puiseux series expansion.
S = dsolve(eqn,'ExpansionPoint',-1)
S =
x+1
3/4 7/4 11/4 15/4 19/4
1 5 x+1 5 x+1 5 x+1 115 x + 1 169 x + 1
− + + + +
x+1
1/4 4 48 336 33792 184320
Find other series solutions around the expansion point ∞ by setting 'ExpansionPoint' to Inf.
7-328
dsolve
S = dsolve(eqn,'ExpansionPoint',Inf)
S =
1 1
x− −
6 x2 8 x4
1 1 1
+ + +1
6 x2 8 x4 90 x5
The default truncation order of the series expansion is 6. To obtain more terms in the Puiseux series
solutions, set 'Order' to 8.
S = dsolve(eqn,'ExpansionPoint',Inf,'Order',8)
S =
1 1 1 37
x− 2
− 4
− 5
−
6x 8x 90 x 336 x6
1 1 1 37 37
+ + + + +1
6 x2 8 x4 90 x5 336 x6 1680 x7
dy 1 −1
Solve the differential equation dx
= e x without specifying the initial condition.
x2
syms y(x)
eqn = diff(y) == exp(-1/x)/x^2;
ySol(x) = dsolve(eqn)
ySol(x) =
1
C1 + e− x
cond = y(0) == 1;
S = dsolve(eqn,cond)
S =
1
e− x + 1
1
The function e− x in the solution ySol(x) has different one-sided limits at x = 0. The function has a
1 1
right-side limit, lim e− x = 0, but it has undefined left-side limit, lim− e− x = ∞.
+ x 0
x 0
When you specify the condition y(x0) for a function with different one-sided limits at x0, dsolve
treats the condition as a limit from the right, lim x x0+.
7-329
7 Functions
Input Arguments
eqn — Differential equation or system of equations
symbolic equation | vector of symbolic equations
In the equation, represent differentiation by using diff. For example, diff(y,x) differentiates the
symbolic function y(x) with respect to x. Create the symbolic function y(x) by using syms and solve
the equation d2y(x)/dx2 = x*y(x) using dsolve.
syms y(x)
S = dsolve(diff(y,x,2) == x*y)
Specify a system of differential equations by using a vector of equations, as in syms y(t) z(t); S
= dsolve([diff(y,t) == z, diff(z,t) == -y]). Here, y and z must be symbolic functions
that depend on symbolic variables, which are t in this case. The right side must be symbolic
expressions that depend on t, y and z. Note that Symbolic Math Toolbox currently does not support
composite symbolic functions, that is, symbolic functions that depend on another symbolic functions.
When a condition contains a derivative, represent the derivative with diff. Assign the diff call to a
variable and use the variable to specify the condition. For example, see “Solve Differential Equations
with Conditions” on page 7-325.
Specify multiple conditions by using a vector of equations. If the number of conditions is less than the
number of dependent variables, the solutions contain the arbitrary constants C1, C2,....
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: 'IgnoreAnalyticConstraints',false does not apply internal simplifications.
Expansion point of a Puiseux series solution, specified as a number, or a symbolic number, variable,
function, or expression. Specifying this option returns the solution of a differential equation in terms
of a Puiseux series (a power series that allows negative and fractional exponents). The expansion
point cannot depend on the series variable. For example, see “Find Series Solution of Differential
Equation” on page 7-328.
Data Types: single | double | sym
Complex Number Support: Yes
7-330
dsolve
By default, the solver applies simplifications while solving the differential equation, which could lead
to results not generally valid. In other words, this option applies mathematical identities that are
convenient, but the results might not hold for all possible values of the variables. Therefore, by
default, the solver does not guarantee the completeness of results. If
'IgnoreAnalyticConstraints' is true, always verify results returned by the dsolve function.
For more details, see “Algorithms” on page 7-332.
Option to return an implicit solution, specified as false or true. For a differential equation with
variables x and y(x), an implicit solution has the form F(y(x)) = g(x).
By default, the solver tries to find an explicit solution y(x) = f(x) analytically when solving a
differential equation. If dsolve cannot find an explicit solution, then you can try finding a solution in
implicit form by specifying the 'Implicit' option to true.
MaxDegree — Maximum degree of polynomial equation for which solver uses explicit
formulas
2 (default) | positive integer smaller than 5
Maximum degree of polynomial equations for which the solver uses explicit formulas, specified as a
positive integer smaller than 5. dsolve does not use explicit formulas when solving polynomial
equations of degrees larger than 'MaxDegree'.
Truncation order of a Puiseux series solution, specified as a positive integer or a symbolic positive
integer. Specifying this option returns the solution of a differential equation in terms of a Puiseux
series (a power series that allow negative and fractional exponents). The truncation order n is the
exponent in the O-term: O(varn) or O(var−n).
Output Arguments
S — Solutions of differential equation
symbolic expression | vector of symbolic expressions
7-331
7 Functions
Variables storing solutions of differential equations, returned as a vector of symbolic variables. The
number of output variables must equal the number of dependent variables in a system of equations.
dsolve sorts the dependent variables alphabetically, and then assigns the solutions for the variables
to output variables or symbolic arrays.
Tips
• If dsolve cannot find an explicit or implicit solution, then it issues a warning and returns the
empty sym. In this case, try to find a numeric solution using the MATLAB ode23 or ode45
function. Sometimes, the output is an equivalent lower-order differential equation or an integral.
• dsolve does not always return complete solutions even if 'IgnoreAnalyticConstraints' is
false.
• If dsolve returns a function that has different one-sided limits at x0 and you specify the condition
y(x0), then dsolve treats the condition as a limit from the right, limx x0+ .
Algorithms
If you do not set 'IgnoreAnalyticConstraints' to false, then dsolve applies some of these
rules while solving the equation:
• log(a) + log(b) = log(a·b) for all values of a and b. In particular, the following equality is applied
for all values of a, b, and c:
(a·b)c = ac·bc.
• log(ab) = b·log(a) for all values of a and b. In particular, the following equality is applied for all
values of a, b, and c:
(ab)c = ab·c.
• If f and g are standard mathematical functions and f(g(x)) = x for all small positive numbers,
f(g(x)) = x is assumed to be valid for all complex x. In particular:
• log(ex) = x
• asin(sin(x)) = x, acos(cos(x)) = x, atan(tan(x)) = x
• asinh(sinh(x)) = x, acosh(cosh(x)) = x, atanh(tanh(x)) = x
• Wk(x·ex) = x for all branch indices k of the Lambert W function.
• The solver can multiply both sides of an equation by any expression except 0.
• The solutions of polynomial equations must be complete.
Version History
Introduced before R2006a
With dsolve:
7-332
dsolve
• Use the 'Implicit' name-value pair to return implicit solutions of differential equations.
• Use the 'ExpansionPoint' and 'Order' name-value pairs to specify the expansion point and
truncation order of Puiseux series solutions of differential equations.
dsolve will not accept equations as strings or character vectors in a future release. Instead, use
symbolic expressions or sym objects to define differential equations. For example, replace inputs such
as dsolve('Dy = exp(y)') with syms y(t); dsolve(diff(y,t) == exp(y)).
See Also
functionalDerivative | isolate | linsolve | ode23 | ode45 | odeToVectorField | solve |
syms | vpasolve
Topics
“Solve Differential Equation” on page 3-43
“Solve a System of Differential Equations” on page 3-47
External Websites
Beam Bending and Deflection (MathWorks Teaching Resources)
7-333
7 Functions
ei
One-argument exponential integral function
Syntax
ei(x)
Description
ei(x) returns the one-argument exponential integral defined as
x
t
ei x = ∫ et dt .
−∞
Examples
Exponential Integral for Floating-Point and Symbolic Numbers
Compute exponential integrals for numeric inputs. Because these numbers are not symbolic objects,
you get floating-point results.
s =
-0.0489 -0.5598 1.8951 3.0485
Compute exponential integrals for the same numbers converted to symbolic objects. For most
symbolic (exact) numbers, ei returns unresolved symbolic calls.
s =
[ ei(-2), ei(-1/2), ei(1), ei(2^(1/2))]
vpa(s, 10)
ans =
[ -0.04890051071, -0.5597735948, 1.895117816, 3.048462479]
The negative real axis is a branch cut. The exponential integral has a jump of height 2 π i when
crossing this cut. Compute the exponential integrals at -1, above -1, and below -1 to demonstrate
this.
ans =
-0.2194 + 0.0000i -0.2194 + 3.1416i -0.2194 - 3.1416i
7-334
ei
Compute the first, second, and third derivatives of a one-argument exponential integral.
syms x
diff(ei(x), x)
diff(ei(x), x, 2)
diff(ei(x), x, 3)
ans =
exp(x)/x
ans =
exp(x)/x - exp(x)/x^2
ans =
exp(x)/x - (2*exp(x))/x^2 + (2*exp(x))/x^3
syms x
limit(ei(2*x^2/(1+x)), x, -Inf)
limit(ei(2*x^2/(1+x)), x, 0)
limit(ei(2*x^2/(1+x)), x, Inf)
ans =
0
ans =
-Inf
ans =
Inf
Input Arguments
x — Input
floating-point number | symbolic number | symbolic variable | symbolic expression | symbolic function
| symbolic vector | symbolic matrix
Input specified as a floating-point number or symbolic number, variable, expression, function, vector,
or matrix.
Tips
• The one-argument exponential integral is singular at x = 0. The toolbox uses this special value:
ei(0) = -Inf.
Algorithms
The relation between ei and expint is
7-335
7 Functions
Both functions ei(x) and expint(1,x) have a logarithmic singularity at the origin and a branch cut
along the negative real axis. The ei function is not continuous when approached from above or below
this branch cut.
Version History
Introduced in R2013a
References
[1] Gautschi, W., and W. F. Gahill “Exponential Integral and Related Functions.” Handbook of
Mathematical Functions with Formulas, Graphs, and Mathematical Tables. (M. Abramowitz
and I. A. Stegun, eds.). New York: Dover, 1972.
See Also
expint | int | vpa
7-336
eig
eig
Eigenvalues and eigenvectors of symbolic matrix
Syntax
lambda = eig(A)
[V,D] = eig(A)
[V,D,p] = eig(A)
Description
lambda = eig(A) returns the eigenvalues of the square symbolic matrix A as a symbolic vector.
[V,D] = eig(A) returns the eigenvectors and eigenvalues of A as symbolic matrices V and D. The
columns of V present eigenvectors of A. The main diagonal of D present eigenvalues of A.
• If V is the same size as A, then the matrix A has a full set of linearly independent eigenvectors that
satisfy A*V = V*D.
• If V has fewer columns than A, then the matrix A is defective. In this case, at least one of the
eigenvalues λ has an algebraic multiplicity m > 1 with fewer than m linearly independent
eigenvectors associated with λ.
[V,D,p] = eig(A) also returns a vector of indices p. The length of p is equal to the number of
linearly independent eigenvectors, so A*V = V*D(p,p).
Examples
Compute Eigenvalues
A = sym(magic(5));
lambda = eig(A)
lambda =
65
625 5 3145
−
2 2
5 3145 625
+
2 2
625 5 3145
− −
2 2
5 3145 625
− +
2 2
7-337
7 Functions
Compute numeric eigenvalues for the magic square of order 5 using variable-precision arithmetic.
A = magic(5);
lambda = eig(vpa(A))
lambda =
65.0
21.276765471473795530626426697974
13.126280930709218802525643085949
−13.126280930709218802525643085949
−21.276765471473795530626426697974
Create a 5-by-5 symbolic matrix from the magic square of order 6. Compute the eigenvalues of the
matrix using eig.
M = magic(6);
A = sym(M(1:5,1:5));
lambda = eig(A)
lambda =
root σ1, z, 1
root σ1, z, 2
root σ1, z, 3
root σ1, z, 4
root σ1, z, 5
where
The eig function cannot find the exact eigenvalues in terms of symbolic numbers. Instead, it returns
them in terms of the root function.
lambdaVpa = vpa(lambda)
lambdaVpa =
−2.181032364984695108354692701065
9.8395828502812312578803604206392
−25.131641669799891607267584639192
26.341617610275869035465716505806
91.131473574227486422276200413812
7-338
eig
Compute the exact eigenvalues and eigenvectors for one of the MATLAB® test matrices that is
defective.
A = sym(gallery(5))
A =
−9 11 −21 63 −252
70 −69 141 −421 1684
−575 575 −1149 3451 −13801
3891 −3891 7782 −23345 93365
1024 −1024 2048 −6144 24572
[V,D] = eig(A)
V =
0
21
256
71
−
128
973
256
1
D =
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
The output V is a 5-by-1 column vector with five-fold eigenvalues of 0. This result means that the
matrix A has an eigenvalue of 0 with algebraic multiplicity 5 and geometric multiplicity 1.
Compute the exact eigenvalues and eigenvectors of a 4-by-4 symbolic matrix. Return a vector of
indices that relate the eigenvalues to their linearly independent eigenvectors.
syms c
A = [c 1 0 0; 0 c 0 0; 0 0 3*c 0; 0 0 0 3*c];
[V,D,p] = eig(A)
V =
1 0 0
0 0 0
0 1 0
0 0 1
D =
7-339
7 Functions
c 0 0 0
0 c 0 0
0 0 3c 0
0 0 0 3c
p = 1×3
1 3 4
The matrix A has two eigenvalues, c and 3 c, where each eigenvalue occurs twice. Meanwhile, there
are three linearly independent eigenvectors. The vector of indices p shows that:
• p(1) = 1, so the first eigenvector (the first column of V) corresponds to the first diagonal
element of D with eigenvalue c.
• p(2) = 3, so the second eigenvector (the second column of V) corresponds to the third diagonal
element of D with eigenvalue 3 c.
• p(3) = 4, so the third eigenvector (the third column of V) corresponds to the fourth diagonal
element of D with eigenvalue 3 c.
This result means the eigenvalue c that occurs twice has only one linearly independent eigenvector
(the eigenvalue c has algebraic multiplicity 2 and geometric multiplicity 1). The eigenvalue 3 c that
occurs twice has two linearly independent eigenvectors (the eigenvalue 3 c has algebraic multiplicity
2 and geometric multiplicity 2).
A*V
ans =
c 0 0
0 0 0
0 3c 0
0 0 3c
V*D(p,p)
ans =
c 0 0
0 0 0
0 3c 0
0 0 3c
tf = isequal(A*V,V*D(p,p))
tf = logical
1
Input Arguments
A — Square matrix
symbolic matrix
7-340
eig
Output Arguments
lambda — Eigenvalues (returned as vector)
symbolic column vector | column vector of symbolic numbers
V — Right eigenvectors
square symbolic matrix
Right eigenvectors, returned as a square symbolic matrix. The columns of V are the right
eigenvectors of A.
Eigenvalues, returned as a symbolic diagonal matrix. The eigenvalues of A are on the main diagonal
of D.
p — Vector of indices
symbolic row vector
Vector of indices, returned as a symbolic row vector. The length of p is the total number of linearly
independent eigenvectors of A.
Tips
• Matrix computations involving many symbolic variables can be slow. To increase the
computational speed, reduce the number of symbolic variables by substituting the given values for
some variables.
• Calling eig for numeric matrices that are not symbolic objects (not created by sym, syms, or vpa)
invokes the MATLAB eig function.
• The symbolic eig function does not support solving the generalized eigenvalue problem (with two
input arguments). To solve the generalized eigenvalue problem, use the MATLAB eig function
instead by converting the input matrices to a MATLAB numeric type.
Version History
Introduced before R2006a
If eig(A) cannot find the exact eigenvalues in terms of symbolic numbers, it now returns the exact
eigenvalues in terms of the root function instead. In previous releases, eig(A) returns the
eigenvalues as floating-point numbers.
For example, compute the eigenvalues of a 5-by-5 symbolic matrix. The eig function returns the
exact eigenvalues in terms of the root function. This output is consistent with the results returned by
the solve or root function when solving for the roots of a polynomial.
7-341
7 Functions
M = magic(6);
A = sym(M(1:5,1:5));
lambda = eig(A)
lambda =
root(z^5 - 100*z^4 + 134*z^3 + 66537*z^2 - 450198*z - 1294704, z, 1)
root(z^5 - 100*z^4 + 134*z^3 + 66537*z^2 - 450198*z - 1294704, z, 2)
root(z^5 - 100*z^4 + 134*z^3 + 66537*z^2 - 450198*z - 1294704, z, 3)
root(z^5 - 100*z^4 + 134*z^3 + 66537*z^2 - 450198*z - 1294704, z, 4)
root(z^5 - 100*z^4 + 134*z^3 + 66537*z^2 - 450198*z - 1294704, z, 5)
lambdaVpa = vpa(lambda)
lambdaVpa =
-2.181032364984695108354692701065
9.8395828502812312578803604206392
-25.131641669799891607267584639192
26.341617610275869035465716505806
91.131473574227486422276200413812
See Also
charpoly | jordan | svd | vpa
Topics
“Eigenvalues” on page 3-282
7-342
eliminate
eliminate
Eliminate variables from rational equations
Syntax
expr = eliminate(eqns,vars)
Description
expr = eliminate(eqns,vars) eliminates the variables vars from the rational equations eqns.
The result is a vector of symbolic expressions that is equal to zero.
Examples
syms x y
eqns = [x*y/(x-2) + y == 5/(y - x), y-x == 1/(x-1)]
eqns =
xy 5 1
y+ =− y−x=
x−2 x−y x−1
Eliminate the variable x. The result is a symbolic expression that is equal to zero.
expr = eliminate(eqns,x)
expr = 6 y2 − 5 y − 75
syms x y
eqns = [2*x+y == 5; y-x == 1]
eqns =
2x+y = 5
y−x=1
Eliminate the variable x from the equations. The result is a symbolic expression that is equal to zero.
expr = eliminate(eqns,x)
expr = 3 y − 7
7-343
7 Functions
Now, create three polynomial equations that contain the variables x, y, and z. Eliminate the variable
x. The result is a vector of symbolic expressions that is equal to zero.
syms z
eqns = [x^2 + y-z^2 == 2;
x - z == y;
x^2 + y^2-z == 4];
expr = eliminate(eqns,x)
expr = 5 z3 − 5 z2 − 8 z + 4 y − 8, 5 z4 − 11 z2 − 18 z − 8
To eliminate both x and y, use the eliminate function and specify the two variables as the vector [x
y].
expr = 5 z4 − 11 z2 − 18 z − 8
Input Arguments
eqns — Rational equations
vector of symbolic equations | vector of symbolic expressions
The relation operator == defines symbolic equations. If a symbolic expression eqn in eqns has no
right side, then a symbolic equation with a right side equal to 0 is assumed.
Version History
Introduced in R2018a
See Also
gbasis | solve
7-344
ellipj
ellipj
Jacobi elliptic functions
Syntax
[SN,CN,DN] = ellipj(u,m)
Description
[SN,CN,DN] = ellipj(u,m) returns the Jacobi sn, cn, and dn elliptic functions evaluated for the
corresponding elements of u and m. Inputs u and m must be the same size, or either u or m must be
scalar.
Examples
Compute the Jacobi elliptic functions for u = 0.75 and m = 0.5. Because these numbers are not
symbolic objects, you get floating-point results.
[SN,CN,DN] = ellipj(0.75,0.5)
SN = 0.6585
CN = 0.7526
DN = 0.8850
Compute the Jacobi elliptic functions for the same numbers converted to symbolic objects. For most
symbolic (exact) numbers, ellipj returns results using the jacobiSN, jacobiCN, and jacobiDN
functions.
[SN,CN,DN] = ellipj(sym(3/4),sym(1/2))
SN =
3 1
sn
4 2
CN =
3 1
cn
4 2
DN =
3 1
dn
4 2
vpa([SN,CN,DN],10)
7-345
7 Functions
If the argument m is not in [0 1], then convert that argument to a symbolic object before using
ellipj.
[SN,CN,DN] = ellipj(1,sym(pi/2))
SN =
π
sn 1
2
CN =
π
cn 1
2
DN =
π
dn 1
2
Alternatively, use jacobiSN, jacobiCN, and jacobiDN to compute the Jacobi elliptic functions
separately.
SN = jacobiSN(1,sym(pi/2))
SN =
π
sn 1
2
CN = jacobiCN(1,sym(pi/2))
CN =
π
cn 1
2
DN = jacobiDN(1,sym(pi/2))
DN =
π
dn 1
2
Call ellipj for symbolic matrix input. When the input arguments are matrices with the same size,
ellipj computes the Jacobi elliptic functions for each element.
SN =
−tanh 1 0
1
sn 1 −1 sin
2
CN =
7-346
ellipj
1
1
cosh 1
1
cn 1 −1 cos
2
DN =
1
1
cosh 1
dn 1 −1 1
Input Arguments
u — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
m — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
Output Arguments
SN — Jacobi sn elliptic function
symbolic expression
More About
Jacobi Elliptic Functions
sn(u, m) = sinϕ
cn(u, m) = cosϕ
2
dn(u, m) = 1 − msin ϕ
7-347
7 Functions
∫
ϕ dθ
u= .
0 2
1 − msin θ
Tips
• Calling ellipj for numbers that are not symbolic objects invokes the MATLAB ellipj function.
This function accepts only 0 <= m <= 1. To compute the Jacobi elliptic functions for values out of
this range, use sym or vpa to convert the numbers to symbolic objects, and then call ellipj for
those symbolic objects. Alternatively, use the jacobiSN, jacobiCN, and jacobiDN functions to
compute the elliptic functions separately.
• For most symbolic (exact) numbers, ellipj returns results using the jacobiSN, jacobiCN, and
jacobiDN functions. You can approximate such results with floating-point numbers using vpa.
Version History
Introduced in R2017b
References
[1] Abramowitz, M. and I. A. Stegun, Handbook of Mathematical Functions, Dover Publications
(1965), 17.6.
See Also
ellipticF | jacobiAM | jacobiSN | jacobiCN | jacobiDN
7-348
ellipke
ellipke
Complete elliptic integrals of the first and second kinds
Syntax
[K,E] = ellipke(m)
Description
[K,E] = ellipke(m) returns the complete elliptic integrals of the first on page 7-351 and second
kinds on page 7-351.
Examples
Compute Complete Elliptic Integrals of First and Second Kind
Compute the complete elliptic integrals of the first and second kinds for these numbers. Because
these numbers are not symbolic objects, you get floating-point results.
K0 =
1.5708
E0 =
1.5708
K05 =
1.8541
E05 =
1.3506
Compute the complete elliptic integrals for the same numbers converted to symbolic objects. For
most symbolic (exact) numbers, ellipke returns results using the ellipticK and ellipticE
functions.
K0 =
pi/2
E0 =
pi/2
K05 =
ellipticK(1/2)
E05 =
ellipticE(1/2)
7-349
7 Functions
ans =
[ 1.854074677, 1.350643881]
If the argument does not belong to the range from 0 to 1, then convert that argument to a symbolic
object before using ellipke:
[K, E] = ellipke(sym(pi/2))
K =
ellipticK(pi/2)
E =
ellipticE(pi/2)
Alternatively, use ellipticK and ellipticE to compute the integrals of the first and the second
kinds separately:
K = ellipticK(sym(pi/2))
E = ellipticE(sym(pi/2))
K =
ellipticK(pi/2)
E =
ellipticE(pi/2)
Call ellipke for this symbolic matrix. When the input argument is a matrix, ellipke computes the
complete elliptic integrals of the first and second kinds for each element.
K =
[ ellipticK(-1), pi/2]
[ ellipticK(1/2), Inf]
E =
[ ellipticE(-1), pi/2]
[ ellipticE(1/2), 1]
Input Arguments
m — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
7-350
ellipke
Output Arguments
K — Complete elliptic integral of the first kind
symbolic expression
More About
Complete Elliptic Integral of the First Kind
Note that some definitions use the elliptical modulus k or the modular angle α instead of the
parameter m. They are related as m = k2 = sin2α.
Note that some definitions use the elliptical modulus k or the modular angle α instead of the
parameter m. They are related as m = k2 = sin2α.
Tips
• Calling ellipke for numbers that are not symbolic objects invokes the MATLAB ellipke
function. This function accepts only 0 <= m <= 1. To compute the complete elliptic integrals of
the first and second kinds for the values out of this range, use sym to convert the numbers to
symbolic objects, and then call ellipke for those symbolic objects. Alternatively, use the
ellipticK and ellipticE functions to compute the integrals separately.
• For most symbolic (exact) numbers, ellipke returns results using the ellipticK and
ellipticE functions. You can approximate such results with floating-point numbers using vpa.
• If m is a vector or a matrix, then [K,E] = ellipke(m) returns the complete elliptic integrals of
the first and second kinds, evaluated for each element of m.
Alternatives
You can use ellipticK and ellipticE to compute elliptic integrals of the first and second kinds
separately.
7-351
7 Functions
Version History
Introduced in R2013a
References
[1] Milne-Thomson, L. M. “Elliptic Integrals.” Handbook of Mathematical Functions with Formulas,
Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New York: Dover,
1972.
See Also
ellipke | ellipticE | ellipticK | vpa
7-352
ellipticCE
ellipticCE
Complementary complete elliptic integral of the second kind
Syntax
ellipticCE(m)
Description
ellipticCE(m) returns the complementary complete elliptic integral of the second kind on page 7-
355.
Examples
Find Complementary Complete Elliptic Integral of the Second Kind
Compute the complementary complete elliptic integrals of the second kind for these numbers.
Because these numbers are not symbolic objects, you get floating-point results.
s = [ellipticCE(0), ellipticCE(pi/4),...
ellipticCE(1), ellipticCE(pi/2)]
s =
1.0000 1.4828 1.5708 1.7753
Compute the complementary complete elliptic integrals of the second kind for the same numbers
converted to symbolic objects. For most symbolic (exact) numbers, ellipticCE returns unresolved
symbolic calls.
s = [ellipticCE(sym(0)), ellipticCE(sym(pi/4)),...
ellipticCE(sym(1)), ellipticCE(sym(pi/2))]
s =
[ 1, ellipticCE(pi/4), pi/2, ellipticCE(pi/2)]
vpa(s, 10)
ans =
[ 1.0, 1.482786927, 1.570796327, 1.775344699]
Call ellipticCE for this symbolic matrix. When the input argument is a matrix, ellipticCE
computes the complementary complete elliptic integral of the second kind for each element.
ans =
[ ellipticCE(pi/6), ellipticCE(pi/4)]
[ ellipticCE(pi/3), ellipticCE(pi/2)]
7-353
7 Functions
Differentiate these expressions involving the complementary complete elliptic integral of the second
kind:
syms m
diff(ellipticCE(m))
diff(ellipticCE(m^2), m, 2)
ans =
ellipticCE(m)/(2*m - 2) - ellipticCK(m)/(2*m - 2)
ans =
(2*ellipticCE(m^2))/(2*m^2 - 2) -...
(2*ellipticCK(m^2))/(2*m^2 - 2) +...
2*m*(((2*m*ellipticCK(m^2))/(2*m^2 - 2) -...
ellipticCE(m^2)/(m*(m^2 - 1)))/(2*m^2 - 2) +...
(2*m*(ellipticCE(m^2)/(2*m^2 - 2) -...
ellipticCK(m^2)/(2*m^2 - 2)))/(2*m^2 - 2) -...
(4*m*ellipticCE(m^2))/(2*m^2 - 2)^2 +...
(4*m*ellipticCK(m^2))/(2*m^2 - 2)^2)
Here, ellipticCK represents the complementary complete elliptic integral of the first kind.
syms m
fplot(ellipticCE(m))
title('Complementary complete elliptic integral of the second kind')
ylabel('ellipticCE(m)')
grid on
7-354
ellipticCE
Input Arguments
m — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
More About
Complementary Complete Elliptic Integral of the Second Kind
The complementary complete elliptic integral of the second kind is defined as E'(m) = E(1–m), where
E(m) is the complete elliptic integral of the second kind:
π/2
Em =E
π
2
m =
0
∫ 2
1 − msin θdθ
Note that some definitions use the elliptical modulus k or the modular angle α instead of the
parameter m. They are related as m = k2 = sin2α.
7-355
7 Functions
Tips
• ellipticCE returns floating-point results for numeric arguments that are not symbolic objects.
• For most symbolic (exact) numbers, ellipticCE returns unresolved symbolic calls. You can
approximate such results with floating-point numbers using vpa.
• If m is a vector or a matrix, then ellipticCE(m) returns the complementary complete elliptic
integral of the second kind, evaluated for each element of m.
Version History
Introduced in R2013a
References
[1] Milne-Thomson, L. M. “Elliptic Integrals.” Handbook of Mathematical Functions with Formulas,
Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New York: Dover,
1972.
See Also
ellipke | ellipticCK | ellipticCPi | ellipticE | ellipticK | ellipticF | ellipticPi |
vpa
7-356
ellipticCK
ellipticCK
Complementary complete elliptic integral of the first kind
Syntax
ellipticCK(m)
Description
ellipticCK(m) returns the complementary complete elliptic integral of the first kind on page 7-359.
Examples
Find Complementary Complete Elliptic Integral of First Kind
Compute the complementary complete elliptic integrals of the first kind for these numbers. Because
these numbers are not symbolic objects, you get floating-point results.
s =
1.8541 1.6671 1.5708 NaN
Compute the complete elliptic integrals of the first kind for the same numbers converted to symbolic
objects. For most symbolic (exact) numbers, ellipticCK returns unresolved symbolic calls.
s = [ellipticCK(sym(1/2)), ellipticCK(sym(pi/4)),...
ellipticCK(sym(1)), ellipticCK(sym(inf))]
s =
[ ellipticCK(1/2), ellipticCK(pi/4), pi/2, ellipticCK(Inf)]
vpa(s, 10)
ans =
[ 1.854074677, 1.667061338, 1.570796327, NaN]
Differentiate these expressions involving the complementary complete elliptic integral of the first
kind:
syms m
diff(ellipticCK(m))
diff(ellipticCK(m^2), m, 2)
ans =
ellipticCE(m)/(2*m*(m - 1)) - ellipticCK(m)/(2*m - 2)
ans =
(2*(ellipticCE(m^2)/(2*m^2 - 2) -...
7-357
7 Functions
Here, ellipticCE represents the complementary complete elliptic integral of the second kind.
Call ellipticCK for this symbolic matrix. When the input argument is a matrix, ellipticCK
computes the complementary complete elliptic integral of the first kind for each element.
ans =
[ ellipticCK(pi/6), ellipticCK(pi/4)]
[ ellipticCK(pi/3), ellipticCK(pi/2)]
syms m
fplot(ellipticCK(m),[0.1 5])
title('Complementary complete elliptic integral of the first kind')
ylabel('ellipticCK(m)')
grid on
hold off
7-358
ellipticCK
Input Arguments
m — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
More About
Complementary Complete Elliptic Integral of the First Kind
The complementary complete elliptic integral of the first kind is defined as K'(m) = K(1–m), where
K(m) is the complete elliptic integral of the first kind:
π/2
K m =F
π
2
m = ∫
0
1
2
1 − msin θ
dθ
Note that some definitions use the elliptical modulus k or the modular angle α instead of the
parameter m. They are related as m = k2 = sin2α.
7-359
7 Functions
Tips
• ellipticK returns floating-point results for numeric arguments that are not symbolic objects.
• For most symbolic (exact) numbers, ellipticCK returns unresolved symbolic calls. You can
approximate such results with floating-point numbers using the vpa function.
• If m is a vector or a matrix, then ellipticCK(m) returns the complementary complete elliptic
integral of the first kind, evaluated for each element of m.
Version History
Introduced in R2013a
References
[1] Milne-Thomson, L. M. “Elliptic Integrals.” Handbook of Mathematical Functions with Formulas,
Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New York: Dover,
1972.
See Also
ellipke | ellipticCE | ellipticCPi | ellipticE | ellipticK | ellipticF | ellipticPi |
vpa
7-360
ellipticCPi
ellipticCPi
Complementary complete elliptic integral of the third kind
Syntax
ellipticCPi(n,m)
Description
ellipticCPi(n,m) returns the complementary complete elliptic integral of the third kind on page
7-362.
Examples
Compute Complementary Complete Elliptic Integrals of Third Kind
Compute the complementary complete elliptic integrals of the third kind for these numbers. Because
these numbers are not symbolic objects, you get floating-point results.
s =
1.3703 1.8541 4.9673 Inf
Compute the complementary complete elliptic integrals of the third kind for the same numbers
converted to symbolic objects. For most symbolic (exact) numbers, ellipticCPi returns unresolved
symbolic calls.
s =
[ ellipticCPi(-1, 1/3), ellipticCK(1/2), (pi*10^(1/2))/2, Inf]
Here, ellipticCK represents the complementary complete elliptic integrals of the first kind.
vpa(s, 10)
ans =
[ 1.370337322, 1.854074677, 4.967294133, Inf]
Differentiate these expressions involving the complementary complete elliptic integral of the third
kind:
syms n m
diff(ellipticCPi(n, m), n)
diff(ellipticCPi(n, m), m)
7-361
7 Functions
ans =
ellipticCK(m)/(2*n*(n - 1)) -...
ellipticCE(m)/(2*(n - 1)*(m + n - 1)) -...
(ellipticCPi(n, m)*(n^2 + m - 1))/(2*n*(n - 1)*(m + n - 1))
ans =
ellipticCE(m)/(2*m*(m + n - 1)) - ellipticCPi(n, m)/(2*(m + n - 1))
Here, ellipticCK and ellipticCE represent the complementary complete elliptic integrals of the
first and second kinds.
Input Arguments
n — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
m — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
More About
Complementary Complete Elliptic Integral of the Third Kind
The complementary complete elliptic integral of the third kind is defined as Π'(m) = Π(n, 1–m), where
Π(n,m) is the complete elliptic integral of the third kind:
π/2
Π n, m = Π n;
π
2
m = ∫
0
2
1
2
1 − nsin θ 1 − msin θ
dθ
Note that some definitions use the elliptical modulus k or the modular angle α instead of the
parameter m. They are related as m = k2 = sin2α.
Tips
• ellipticCPi returns floating-point results for numeric arguments that are not symbolic objects.
• For most symbolic (exact) numbers, ellipticCPi returns unresolved symbolic calls. You can
approximate such results with floating-point numbers using vpa.
• At least one input argument must be a scalar or both arguments must be vectors or matrices of
the same size. If one input argument is a scalar and the other one is a vector or a matrix, then
ellipticCPi expands the scalar into a vector or matrix of the same size as the other argument
with all elements equal to that scalar.
7-362
ellipticCPi
Version History
Introduced in R2013a
References
[1] Milne-Thomson, L. M. “Elliptic Integrals.” Handbook of Mathematical Functions with Formulas,
Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New York: Dover,
1972.
See Also
ellipke | ellipticCE | ellipticCK | ellipticE | ellipticK | ellipticF | ellipticPi | vpa
7-363
7 Functions
ellipticE
Complete and incomplete elliptic integrals of the second kind
Syntax
ellipticE(m)
ellipticE(phi,m)
Description
ellipticE(m) returns the complete elliptic integral of the second kind on page 7-367.
ellipticE(phi,m) returns the incomplete elliptic integral of the second kind on page 7-366.
Examples
Find Complete Elliptic Integrals of Second Kind
Compute the complete elliptic integrals of the second kind for these numbers. Because these
numbers are not symbolic objects, you get floating-point results.
s = [ellipticE(-10.5), ellipticE(-pi/4),...
ellipticE(0), ellipticE(1)]
s =
3.7096 1.8443 1.5708 1.0000
Compute the complete elliptic integral of the second kind for the same numbers converted to
symbolic objects. For most symbolic (exact) numbers, ellipticE returns unresolved symbolic calls.
s = [ellipticE(sym(-10.5)), ellipticE(sym(-pi/4)),...
ellipticE(sym(0)), ellipticE(sym(1))]
s =
[ ellipticE(-21/2), ellipticE(-pi/4), pi/2, 1]
ans =
[ 3.70961391, 1.844349247, 1.570796327, 1.0]
Differentiate these expressions involving elliptic integrals of the second kind. ellipticK and
ellipticF represent the complete and incomplete elliptic integrals of the first kind, respectively.
syms m
diff(ellipticE(pi/3, m))
diff(ellipticE(m^2), m, 2)
ans =
ellipticE(pi/3, m)/(2*m) - ellipticF(pi/3, m)/(2*m)
7-364
ellipticE
ans =
2*m*((ellipticE(m^2)/(2*m^2) -...
ellipticK(m^2)/(2*m^2))/m - ellipticE(m^2)/m^3 +...
ellipticK(m^2)/m^3 + (ellipticK(m^2)/m +...
ellipticE(m^2)/(m*(m^2 - 1)))/(2*m^2)) +...
ellipticE(m^2)/m^2 - ellipticK(m^2)/m^2
Call ellipticE for this symbolic matrix. When the input argument is a matrix, ellipticE computes
the complete elliptic integral of the second kind for each element.
ans =
[ ellipticE(1/3), 1]
[ ellipticE(1/2), pi/2]
Plot the incomplete elliptic integrals ellipticE(phi,m) for phi = pi/4 and phi = pi/3. Also
plot the complete elliptic integral ellipticE(m).
syms m
fplot([ellipticE(pi/4,m) ellipticE(pi/3,m) ellipticE(m)])
7-365
7 Functions
Input Arguments
m — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
phi — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
More About
Incomplete Elliptic Integral of the Second Kind
7-366
ellipticE
Note that some definitions use the elliptical modulus k or the modular angle α instead of the
parameter m. They are related as m = k2 = sin2α.
Note that some definitions use the elliptical modulus k or the modular angle α instead of the
parameter m. They are related as m = k2 = sin2α.
Tips
• ellipticE returns floating-point results for numeric arguments that are not symbolic objects.
• For most symbolic (exact) numbers, ellipticE returns unresolved symbolic calls. You can
approximate such results with floating-point numbers using vpa.
• If m is a vector or a matrix, then ellipticE(m) returns the complete elliptic integral of the
second kind, evaluated for each element of m.
• At least one input argument must be a scalar or both arguments must be vectors or matrices of
the same size. If one input argument is a scalar and the other one is a vector or a matrix, then
ellipticE expands the scalar into a vector or matrix of the same size as the other argument with
all elements equal to that scalar.
• ellipticE(pi/2, m) = ellipticE(m).
Alternatives
You can use ellipke to compute elliptic integrals of the first and second kinds in one function call.
Version History
Introduced in R2013a
References
[1] Milne-Thomson, L. M. “Elliptic Integrals.” Handbook of Mathematical Functions with Formulas,
Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New York: Dover,
1972.
See Also
ellipke | ellipticCE | ellipticCK | ellipticCPi | ellipticF | ellipticK | ellipticPi |
vpa
7-367
7 Functions
ellipticF
Incomplete elliptic integral of the first kind
Syntax
ellipticF(phi,m)
Description
ellipticF(phi,m) returns the incomplete elliptic integral of the first kind on page 7-370.
Examples
Find Incomplete Elliptic Integrals of First Kind
Compute the incomplete elliptic integrals of the first kind for these numbers. Because these numbers
are not symbolic objects, you get floating-point results.
s =
0.6184 0.6486 0.8964 1.5708
Compute the incomplete elliptic integrals of the first kind for the same numbers converted to
symbolic objects. For most symbolic (exact) numbers, ellipticF returns unresolved symbolic calls.
s =
[ ellipticF(pi/3, -21/2), ellipticF(pi/4, -pi), ellipticF(1, -1), pi/6]
vpa(s, 10)
ans =
[ 0.6184459461, 0.6485970495, 0.8963937895, 0.5235987756]
Differentiate this expression involving the incomplete elliptic integral of the first kind. ellipticE
represents the incomplete elliptic integral of the second kind.
syms m
diff(ellipticF(pi/4, m))
ans =
1/(4*(1 - m/2)^(1/2)*(m - 1)) - ellipticF(pi/4, m)/(2*m) -...
ellipticE(pi/4, m)/(2*m*(m - 1))
7-368
ellipticF
Plot the incomplete elliptic integrals ellipticF(phi,m) for phi = pi/4 and phi = pi/3. Also
plot the complete elliptic integral ellipticK(m).
syms m
fplot([ellipticF(pi/4, m) ellipticF(pi/3, m) ellipticK(m)])
grid on
Input Arguments
m — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
phi — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
7-369
7 Functions
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
More About
Incomplete Elliptic Integral of the First Kind
Note that some definitions use the elliptical modulus k or the modular angle α instead of the
parameter m. They are related as m = k2 = sin2α.
Tips
• ellipticF returns floating-point results for numeric arguments that are not symbolic objects.
• For most symbolic (exact) numbers, ellipticF returns unresolved symbolic calls. You can
approximate such results with floating-point numbers using vpa.
• At least one input argument must be a scalar or both arguments must be vectors or matrices of
the same size. If one input argument is a scalar and the other one is a vector or a matrix,
ellipticF expands the scalar into a vector or matrix of the same size as the other argument with
all elements equal to that scalar.
• ellipticF(pi/2, m) = ellipticK(m).
Version History
Introduced in R2013a
References
[1] Milne-Thomson, L. M. “Elliptic Integrals.” Handbook of Mathematical Functions with Formulas,
Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New York: Dover,
1972.
See Also
ellipke | ellipticCE | ellipticCK | ellipticCPi | ellipticE | ellipticK | ellipticPi |
vpa
7-370
ellipticK
ellipticK
Complete elliptic integral of the first kind
Syntax
ellipticK(m)
Description
ellipticK(m) returns the complete elliptic integral of the first kind on page 7-373.
Examples
Find Complete Elliptic Integrals of First Kind
Compute the complete elliptic integrals of the first kind for these numbers. Because these numbers
are not symbolic objects, you get floating-point results.
s =
1.8541 2.2253 Inf 0.9325
Compute the complete elliptic integrals of the first kind for the same numbers converted to symbolic
objects. For most symbolic (exact) numbers, ellipticK returns unresolved symbolic calls.
s = [ellipticK(sym(1/2)), ellipticK(sym(pi/4)),...
ellipticK(sym(1)), ellipticK(sym(-5.5))]
s =
[ ellipticK(1/2), ellipticK(pi/4), Inf, ellipticK(-11/2)]
vpa(s, 10)
ans =
[ 1.854074677, 2.225253684, Inf, 0.9324665884]
Differentiate these expressions involving the complete elliptic integral of the first kind. ellipticE
represents the complete elliptic integral of the second kind.
syms m
diff(ellipticK(m))
diff(ellipticK(m^2), m, 2)
ans =
- ellipticK(m)/(2*m) - ellipticE(m)/(2*m*(m - 1))
ans =
(2*ellipticE(m^2))/(m^2 - 1)^2 - (2*(ellipticE(m^2)/(2*m^2) -...
7-371
7 Functions
Call ellipticK for this symbolic matrix. When the input argument is a matrix, ellipticK computes
the complete elliptic integral of the first kind for each element.
ans =
[ ellipticK(-2*pi), ellipticK(-4)]
[ pi/2, Inf]
syms m
fplot(ellipticK(m))
title('Complete elliptic integral of the first kind')
ylabel('ellipticK(m)')
grid on
7-372
ellipticK
Input Arguments
m — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
More About
Complete Elliptic Integral of the First Kind
π/2
K m =F
π
2
m =
0
∫ 1
2
1 − msin θ
dθ
Note that some definitions use the elliptical modulus k or the modular angle α instead of the
parameter m. They are related as m = k2 = sin2α.
Tips
• ellipticK returns floating-point results for numeric arguments that are not symbolic objects.
• For most symbolic (exact) numbers, ellipticK returns unresolved symbolic calls. You can
approximate such results with floating-point numbers using vpa.
• If m is a vector or a matrix, then ellipticK(m) returns the complete elliptic integral of the first
kind, evaluated for each element of m.
Alternatives
You can use ellipke to compute elliptic integrals of the first and second kinds in one function call.
Version History
Introduced in R2013a
References
[1] Milne-Thomson, L. M. “Elliptic Integrals.” Handbook of Mathematical Functions with Formulas,
Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New York: Dover,
1972.
See Also
ellipke | ellipticCE | ellipticCK | ellipticCPi | ellipticE | ellipticF | ellipticPi |
vpa
7-373
7 Functions
ellipticNome
Elliptic nome function
Syntax
ellipticNome(m)
Description
ellipticNome(m) returns the “Elliptic Nome” on page 7-376 of m. If m is an array, then
ellipticNome acts element-wise.
Examples
ellipticNome(1.3)
ans =
0.0881 - 0.2012i
ellipticNome([2 1 -3/2])
ans =
0.0000 - 0.2079i 1.0000 + 0.0000i -0.0570 + 0.0000i
Convert numeric input to symbolic form using sym, and find the elliptic nome. For symbolic input
where m = 0, 1/2, or 1, ellipticNome returns exact symbolic output.
ans =
0 0.0432 1.0000
Show that for any other symbolic values of m, ellipticNome returns an unevaluated function call.
ellipticNome(sym(2))
ans =
ellipticNome(2)
For symbolic variables or expressions, ellipticNome returns the unevaluated function call.
7-374
ellipticNome
syms x
f = ellipticNome(x)
f =
ellipticNome(x)
Substitute values for the variables by using subs, and convert values to double by using double.
f = subs(f, x, 5)
f =
ellipticNome(5)
fVal = double(f)
fVal =
-0.1008 - 0.1992i
fVal = vpa(f)
fVal =
- 0.10080189716733475056506021415746 - 0.19922973618609837873340100821425i
Plot the real and imaginary values of the elliptic nome using fcontour. Fill plot contours by setting
Fill to on.
syms m
f = ellipticNome(m);
subplot(2,2,1)
fcontour(real(f),'Fill','on')
title('Real Values of Elliptic Nome')
xlabel('m')
subplot(2,2,2)
fcontour(imag(f),'Fill','on')
title('Imaginary Values of Elliptic Nome')
xlabel('m')
7-375
7 Functions
Input Arguments
m — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
More About
Elliptic Nome
where K is the complete elliptic integral of the first kind, implemented as ellipticK.
Version History
Introduced in R2017b
7-376
ellipticNome
See Also
ellipticK | jacobiAM | jacobiCD | jacobiCN | jacobiCS | jacobiDC | jacobiDN | jacobiDS |
jacobiNC | jacobiND | jacobiNS | jacobiSC | jacobiSD | jacobiSN
7-377
7 Functions
ellipticPi
Complete and incomplete elliptic integrals of the third kind
Syntax
ellipticPi(n,m)
ellipticPi(n,phi,m)
Description
ellipticPi(n,m) returns the complete elliptic integral of the third kind on page 7-380.
ellipticPi(n,phi,m) returns the incomplete elliptic integral of the third kind on page 7-379.
Examples
Compute the Incomplete Elliptic Integrals of Third Kind
Compute the incomplete elliptic integrals of the third kind for these numbers. Because these numbers
are not symbolic objects, you get floating-point results.
s = [ellipticPi(-2.3, pi/4, 0), ellipticPi(1/3, pi/3, 1/2),...
ellipticPi(-1, 0, 1), ellipticPi(2, pi/6, 2)]
s =
0.5877 1.2850 0 0.7507
Compute the incomplete elliptic integrals of the third kind for the same numbers converted to
symbolic objects. For most symbolic (exact) numbers, ellipticPi returns unresolved symbolic calls.
s = [ellipticPi(-2.3, sym(pi/4), 0), ellipticPi(sym(1/3), pi/3, 1/2),...
ellipticPi(-1, sym(0), 1), ellipticPi(2, pi/6, sym(2))]
s =
[ ellipticPi(-23/10, pi/4, 0), ellipticPi(1/3, pi/3, 1/2),...
0, (2^(1/2)*3^(1/2))/2 - ellipticE(pi/6, 2)]
Here, ellipticE represents the incomplete elliptic integral of the second kind.
ans =
[ 0.5876852228, 1.285032276, 0, 0.7507322117]
Differentiate these expressions involving the complete elliptic integral of the third kind:
syms n m
diff(ellipticPi(n, m), n)
diff(ellipticPi(n, m), m)
7-378
ellipticPi
ans =
ellipticK(m)/(2*n*(n - 1)) + ellipticE(m)/(2*(m - n)*(n - 1)) -...
(ellipticPi(n, m)*(- n^2 + m))/(2*n*(m - n)*(n - 1))
ans =
- ellipticPi(n, m)/(2*(m - n)) - ellipticE(m)/(2*(m - n)*(m - 1))
Here, ellipticK and ellipticE represent the complete elliptic integrals of the first and second
kinds.
Call ellipticPi for the scalar and the matrix. When one input argument is a matrix, ellipticPi
expands the scalar argument to a matrix of the same size with all its elements equal to the scalar.
ellipticPi(sym(0), sym([1/3 1; 1/2 0]))
ans =
[ ellipticK(1/3), Inf]
[ ellipticK(1/2), pi/2]
Here, ellipticK represents the complete elliptic integral of the first kind.
Input Arguments
n — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
m — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
phi — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
More About
Incomplete Elliptic Integral of the Third Kind
7-379
7 Functions
Note that some definitions use the elliptical modulus k or the modular angle α instead of the
parameter m. They are related as m = k2 = sin2α.
Note that some definitions use the elliptical modulus k or the modular angle α instead of the
parameter m. They are related as m = k2 = sin2α.
Tips
• ellipticPi returns floating-point results for numeric arguments that are not symbolic objects.
• For most symbolic (exact) numbers, ellipticPi returns unresolved symbolic calls. You can
approximate such results with floating-point numbers using vpa.
• All non-scalar arguments must have the same size. If one or two input arguments are non-scalar,
then ellipticPi expands the scalars into vectors or matrices of the same size as the non-scalar
arguments, with all elements equal to the corresponding scalar.
• ellipticPi(n, pi/2, m) = ellipticPi(n, m).
Version History
Introduced in R2013a
References
[1] Milne-Thomson, L. M. “Elliptic Integrals.” Handbook of Mathematical Functions with Formulas,
Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New York: Dover,
1972.
See Also
ellipke | ellipticCE | ellipticCK | ellipticCPi | ellipticE | ellipticF | ellipticK |
vpa
7-380
eq
eq
Define symbolic equation
Syntax
A == B
eq(A,B)
Description
A == B defines a symbolic equation. Use the equation as input to functions such as solve, assume,
fcontour, and subs.
eq(A,B) is equivalent to A == B.
Examples
Solve this trigonometric equation. Define the equation by using the == operator.
syms x
eqn = sin(x) == cos(x);
solve(eqn,x)
ans =
pi/4
Plot the equation sin(x2) = sin(y2) by using fimplicit. Define the equation by using the == operator.
syms x y
eqn = sin(x^2) == sin(y^2);
fimplicit(eqn)
7-381
7 Functions
syms x
eqn = x+1 == x+1;
isAlways(eqn)
ans =
logical
1
ans =
logical
1
7-382
eq
A = sym(hilb(3));
B = sym([1 1/2 5; 1/2 2 1/4; 1/3 1/8 1/5]);
isAlways(A == B)
ans =
3×3 logical array
1 1 0
1 0 1
1 0 1
Compare a matrix and a scalar. The == operator expands the scalar into a matrix of the same
dimensions as the input matrix.
A = sym(hilb(3));
B = sym(1/2);
isAlways(A == B)
ans =
3×3 logical array
0 1 0
1 0 0
0 0 0
Input Arguments
A — Input
number | vector | matrix | array | symbolic number | symbolic scalar variable | symbolic matrix
variable | symbolic array | symbolic function | symbolic matrix function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, scalar variable, matrix
variable, array, function, matrix function, or expression.
B — Input
number | vector | matrix | array | symbolic number | symbolic scalar variable | symbolic matrix
variable | symbolic array | symbolic function | symbolic matrix function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, scalar variable, matrix
variable, array, function, matrix function, or expression.
Tips
• Calling == or eq for nonsymbolic A and B invokes the MATLAB eq function. This function returns a
logical array with elements set to logical 1 (true) where A and B are equal; otherwise, it returns
logical 0 (false).
• If both A and B are arrays, then they must have the same dimensions. A == B returns an array of
equations A(i,j,...) == B(i,j,...).
Version History
Introduced in R2012a
7-383
7 Functions
See Also
ge | gt | isAlways | le | lt | ne | solve
Topics
“Solve Equations” on page 1-30
“Use Assumptions on Symbolic Variables” on page 1-41
7-384
equationsToMatrix
equationsToMatrix
Convert linear equations to matrix form
Syntax
[A,b] = equationsToMatrix(eqns)
[A,b] = equationsToMatrix(eqns,vars)
A = equationsToMatrix( ___ )
Description
[A,b] = equationsToMatrix(eqns) converts equations eqns to matrix form. eqns must be a
linear system of equations in all variables that symvar finds in eqns.
A = equationsToMatrix( ___ ) returns only the coefficient matrix of the system of equations.
Examples
Convert a system of linear equations to matrix form. equationsToMatrix automatically detects the
variables in the equations by using symvar. The returned coefficient matrix follows the variable order
determined by symvar.
syms x y z
eqns = [x+y-2*z == 0,
x+y+z == 1,
2*y-z == -5];
[A,b] = equationsToMatrix(eqns)
A =
1 1 −2
11 1
0 2 −1
b =
0
1
−5
vars = symvar(eqns)
vars = x y z
You can change the arrangement of the coefficient matrix by specifying other variable order.
vars = [x,z,y];
[A,b] = equationsToMatrix(eqns,vars)
7-385
7 Functions
A =
1 −2 1
1 1 1
0 −1 2
b =
0
1
−5
Convert a linear system of equations to the matrix form by specifying independent variables. This is
useful when the equations are only linear in some variables.
For this system, specify the variables as [s t] because the system is not linear in r.
syms r s t
eqns = [s-2*t+r^2 == -1
3*s-t == 10];
vars = [s t];
[A,b] = equationsToMatrix(eqns,vars)
A =
1 −2
3 −1
b =
−r 2 − 1
10
Return only the coefficient matrix of the equations by specifying a single output argument.
syms x y z
eqns = [x+y-2*z == 0,
x+y+z == 1,
2*y-z == -5];
vars = [x y z];
A = equationsToMatrix(eqns,vars)
A =
1 1 −2
11 1
0 2 −1
7-386
equationsToMatrix
Consider the following system of linear equations that are functions of time:
eqn(t) =
2x t +y t +z t = 2u t
y t −x t −z t =v t
x t + 2 y t + 3 z t = −10
Specify the independent variables x(t), y(t), and z(t) in the equations as a symbolic vector vars. Use
the equationsToMatrix function to convert the system of equations into the matrix form.
A =
2 1 1
−1 1 −1
1 2 3
b =
2u t
vt
−10
Solve the matrix form of the equations using the linsolve function.
X = linsolve(A,b)
X =
10 u t vt 20
− +
9 9 9
4u t 5v t 10
+ −
9 9 9
2u t vt 10
− − −
3 3 3
Evaluate the z(t) solution for the functions u(t) = cos(t) and v(t) = sin(2t). Plot the z(t) solution.
zSol =
sin 2 t 2 cos t 10
− − −
3 3 3
7-387
7 Functions
fplot(zSol)
Input Arguments
eqns — Linear equations
vector of symbolic equations or expressions
Linear equations, specified as a vector of symbolic equations or expressions. Symbolic equations are
defined by using the == operator, such as x + y == 1. For symbolic expressions,
equationsToMatrix assumes that the right side is 0.
Output Arguments
A — Coefficient matrix
symbolic matrix
7-388
equationsToMatrix
More About
Matrix Representation of System of Linear Equations
a11 … a1n
A= ⋮ ⋱ ⋮
am1 ⋯ amn
b1
b = ⋮
bm
Version History
Introduced in R2012b
See Also
linsolve | odeToVectorField | solve | symvar
Topics
“Solve System of Linear Equations” on page 3-30
7-389
7 Functions
erf
Error function
Syntax
erf(X)
Description
erf(X) represents the error function on page 7-393 of X. If X is a vector or a matrix, erf(X)
computes the error function of each element of X.
Examples
Error Function for Floating-Point and Symbolic Numbers
Depending on its arguments, erf can return floating-point or exact symbolic results.
Compute the error function for these numbers. Because these numbers are not symbolic objects, you
get the floating-point results:
A = [erf(1/2), erf(1.41), erf(sqrt(2))]
A =
0.5205 0.9539 0.9545
Compute the error function for the same numbers converted to symbolic objects. For most symbolic
(exact) numbers, erf returns unresolved symbolic calls:
symA = [erf(sym(1/2)), erf(sym(1.41)), erf(sqrt(sym(2)))]
symA =
[ erf(1/2), erf(141/100), erf(2^(1/2))]
Use vpa to approximate symbolic results with the required number of digits:
d = digits(10);
vpa(symA)
digits(d)
ans =
[ 0.5204998778, 0.9538524394, 0.9544997361]
For most symbolic variables and expressions, erf returns unresolved symbolic calls.
7-390
erf
ans =
erf(x)
ans =
erf(sin(x) + x*exp(x))
If the input argument is a vector or a matrix, erf returns the error function for each element of that
vector or matrix.
ans =
[ 0, 1]
[ erf(1/3), -1]
ans =
erf(1)
-Inf*1i
Compute the error function for x = 0, x = ∞, and x = –∞. Use sym to convert 0 and infinities to
symbolic objects. The error function has special values for these parameters:
[erf(sym(0)), erf(sym(Inf)), erf(sym(-Inf))]
ans =
[ 0, 1, -1]
Compute the error function for complex infinities. Use sym to convert complex infinities to symbolic
objects:
[erf(sym(i*Inf)), erf(sym(-i*Inf))]
ans =
[ Inf*1i, -Inf*1i]
Many functions, such as diff and int, can handle expressions containing erf.
ans =
(2*exp(-x^2))/pi^(1/2)
7-391
7 Functions
ans =
-(4*x*exp(-x^2))/pi^(1/2)
int(erf(x), x)
int(erf(log(x)), x)
ans =
exp(-x^2)/pi^(1/2) + x*erf(x)
ans =
x*erf(log(x)) - int((2*exp(-log(x)^2))/pi^(1/2), x)
syms x
fplot(erf(x),[-5 5])
grid on
7-392
erf
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
More About
Error Function
Tips
• Calling erf for a number that is not a symbolic object invokes the MATLAB erf function. This
function accepts real arguments only. If you want to compute the error function for a complex
number, use sym to convert that number to a symbolic object, and then call erf for that symbolic
object.
• For most symbolic (exact) numbers, erf returns unresolved symbolic calls. You can approximate
such results with floating-point numbers using vpa.
Algorithms
The toolbox can simplify expressions that contain error functions and their inverses. For real values
x, the toolbox applies these simplification rules:
• erfcinv(x) = erfinv(1 - x)
• erfinv(-x) = -erfinv(x)
• erfcinv(2 - x) = -erfcinv(x)
• erf(erfinv(x)) = erfc(erfcinv(x)) = x
• erf(erfcinv(x)) = erfc(erfinv(x)) = 1 - x
Version History
Introduced before R2006a
7-393
7 Functions
References
[1] Gautschi, W. “Error Function and Fresnel Integrals.” Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New
York: Dover, 1972.
See Also
erfc | erfcinv | erfi | erfinv
7-394
erfc
erfc
Complementary error function
Syntax
erfc(X)
erfc(K,X)
Description
erfc(X) represents the complementary error function on page 7-398 of X, that is,erfc(X) = 1 -
erf(X).
erfc(K,X) represents the iterated integral of the complementary error function on page 7-399 of X,
that is, erfc(K, X) = int(erfc(K - 1, y), y, X, inf).
Examples
Complementary Error Function for Floating-Point and Symbolic Numbers
Depending on its arguments, erfc can return floating-point or exact symbolic results.
Compute the complementary error function for these numbers. Because these numbers are not
symbolic objects, you get the floating-point results:
A =
0.4795 0.0461 0.0455
Compute the complementary error function for the same numbers converted to symbolic objects. For
most symbolic (exact) numbers, erfc returns unresolved symbolic calls:
symA =
[ erfc(1/2), erfc(141/100), erfc(2^(1/2))]
Use vpa to approximate symbolic results with the required number of digits:
d = digits(10);
vpa(symA)
digits(d)
ans =
[ 0.4795001222, 0.04614756064, 0.0455002639]
For most symbolic variables and expressions, erfc returns unresolved symbolic calls.
7-395
7 Functions
syms x
f = sin(x) + x*exp(x);
erfc(x)
erfc(f)
ans =
erfc(x)
ans =
erfc(sin(x) + x*exp(x))
If the input argument is a vector or a matrix, erfc returns the complementary error function for each
element of that vector or matrix.
Compute the complementary error function for elements of matrix M and vector V:
M = sym([0 inf; 1/3 -inf]);
V = sym([1; -i*inf]);
erfc(M)
erfc(V)
ans =
[ 1, 0]
[ erfc(1/3), 2]
ans =
erfc(1)
1 + Inf*1i
Compute the iterated integral of the complementary error function for the elements of V and M, and
the integer -1:
erfc(-1, M)
erfc(-1, V)
ans =
[ 2/pi^(1/2), 0]
[ (2*exp(-1/9))/pi^(1/2), 0]
ans =
(2*exp(-1))/pi^(1/2)
Inf
Compute the complementary error function for x = 0, x = ∞, and x = –∞. The complementary error
function has special values for these parameters:
[erfc(0), erfc(Inf), erfc(-Inf)]
ans =
1 0 2
Compute the complementary error function for complex infinities. Use sym to convert complex
infinities to symbolic objects:
7-396
erfc
[erfc(sym(i*Inf)), erfc(sym(-i*Inf))]
ans =
[ 1 - Inf*1i, 1 + Inf*1i]
Many functions, such as diff and int, can handle expressions containing erfc.
Compute the first and second derivatives of the complementary error function:
syms x
diff(erfc(x), x)
diff(erfc(x), x, 2)
ans =
-(2*exp(-x^2))/pi^(1/2)
ans =
(4*x*exp(-x^2))/pi^(1/2)
syms x
int(erfc(-1, x), x)
ans =
erf(x)
int(erfc(x), x)
ans =
x*erfc(x) - exp(-x^2)/pi^(1/2)
int(erfc(2, x), x)
ans =
(x^3*erfc(x))/6 - exp(-x^2)/(6*pi^(1/2)) +...
(x*erfc(x))/4 - (x^2*exp(-x^2))/(6*pi^(1/2))
syms x
fplot(erfc(x),[-5 5])
grid on
7-397
7 Functions
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Input representing an integer larger than -2, specified as a number, symbolic number, variable,
expression, or function. This arguments can also be a vector or matrix of numbers, symbolic numbers,
variables, expressions, or functions.
More About
Complementary Error Function
7-398
erfc
∞
er f c(x) =
2
π ∫e
x
−t2dt = 1 − er f x
The following integral is the iterated integral of the complementary error function:
∞
er f c k, x = ∫ erf c k − 1, y dy
x
Here, er f c 0, x = er f c x .
Tips
• Calling erfc for a number that is not a symbolic object invokes the MATLAB erfc function. This
function accepts real arguments only. If you want to compute the complementary error function
for a complex number, use sym to convert that number to a symbolic object, and then call erfc for
that symbolic object.
• For most symbolic (exact) numbers, erfc returns unresolved symbolic calls. You can approximate
such results with floating-point numbers using vpa.
• At least one input argument must be a scalar or both arguments must be vectors or matrices of
the same size. If one input argument is a scalar and the other one is a vector or a matrix, then
erfc expands the scalar into a vector or matrix of the same size as the other argument with all
elements equal to that scalar.
Algorithms
The toolbox can simplify expressions that contain error functions and their inverses. For real values
x, the toolbox applies these simplification rules:
• erfcinv(x) = erfinv(1 - x)
• erfinv(-x) = -erfinv(x)
• erfcinv(2 - x) = -erfcinv(x)
• erf(erfinv(x)) = erfc(erfcinv(x)) = x
• erf(erfcinv(x)) = erfc(erfinv(x)) = 1 - x
Version History
Introduced in R2011b
7-399
7 Functions
References
[1] Gautschi, W. “Error Function and Fresnel Integrals.” Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New
York: Dover, 1972.
See Also
erf | erfcinv | erfi | erfinv
7-400
erfcinv
erfcinv
Inverse complementary error function
Syntax
erfcinv(X)
Description
erfcinv(X) computes the inverse complementary error function on page 7-404 of X. If X is a vector
or a matrix, erfcinv(X) computes the inverse complementary error function of each element of X.
Examples
Inverse Complementary Error Function for Floating-Point and Symbolic Numbers
Depending on its arguments, erfcinv can return floating-point or exact symbolic results.
Compute the inverse complementary error function for these numbers. Because these numbers are
not symbolic objects, you get floating-point results:
A =
0.4769 -0.3013 -0.4769
Compute the inverse complementary error function for the same numbers converted to symbolic
objects. For most symbolic (exact) numbers, erfcinv returns unresolved symbolic calls:
symA =
[ -erfcinv(3/2), erfcinv(133/100), erfcinv(3/2)]
Use vpa to approximate symbolic results with the required number of digits:
d = digits(10);
vpa(symA)
digits(d)
ans =
[ 0.4769362762, -0.3013321461, -0.4769362762]
For most symbolic variables and expressions, erfcinv returns unresolved symbolic calls.
Compute the inverse complementary error function for x and sin(x) + x*exp(x). For most
symbolic variables and expressions, erfcinv returns unresolved symbolic calls:
syms x
f = sin(x) + x*exp(x);
7-401
7 Functions
erfcinv(x)
erfcinv(f)
ans =
erfcinv(x)
ans =
erfcinv(sin(x) + x*exp(x))
If the input argument is a vector or a matrix, erfcinv returns the inverse complementary error
function for each element of that vector or matrix.
Compute the inverse complementary error function for elements of matrix M and vector V:
ans =
[ Inf, NaN]
[ -erfcinv(5/3), 0]
ans =
-Inf
NaN
Compute the inverse complementary error function for x = 0, x = 1, and x = 2. The inverse
complementary error function has special values for these parameters:
ans =
Inf 0 -Inf
Many functions, such as diff and int, can handle expressions containing erfcinv.
Compute the first and second derivatives of the inverse complementary error function:
syms x
diff(erfcinv(x), x)
diff(erfcinv(x), x, 2)
ans =
-(pi^(1/2)*exp(erfcinv(x)^2))/2
ans =
(pi*exp(2*erfcinv(x)^2)*erfcinv(x))/2
7-402
erfcinv
int(erfcinv(x), x)
ans =
exp(-erfcinv(x)^2)/pi^(1/2)
syms x
fplot(erfcinv(x),[0 2])
grid on
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
7-403
7 Functions
More About
Inverse Complementary Error Function
The inverse complementary error function is defined as erfc-1(x), such that erfc(erfc-1(x)) = x. Here
∞
er f c(x) =
2
π ∫e
x
−t2dt = 1 − er f x
Tips
• Calling erfcinv for a number that is not a symbolic object invokes the MATLAB erfcinv
function. This function accepts real arguments only. If you want to compute the inverse
complementary error function for a complex number, use sym to convert that number to a
symbolic object, and then call erfcinv for that symbolic object.
• If x < 0 or x > 2, or if x is complex, then erfcinv(x) returns NaN.
Algorithms
The toolbox can simplify expressions that contain error functions and their inverses. For real values
x, the toolbox applies these simplification rules:
• erfcinv(x) = erfinv(1 - x)
• erfinv(-x) = -erfinv(x)
• erfcinv(2 - x) = -erfcinv(x)
• erf(erfinv(x)) = erfc(erfcinv(x)) = x
• erf(erfcinv(x)) = erfc(erfinv(x)) = 1 - x
Version History
Introduced in R2012a
References
[1] Gautschi, W. “Error Function and Fresnel Integrals.” Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New
York: Dover, 1972.
7-404
erfcinv
See Also
erf | erfc | erfi | erfinv
7-405
7 Functions
erfi
Imaginary error function
Syntax
erfi(x)
Description
erfi(x) returns the imaginary error function on page 7-409 of x. If x is a vector or a matrix,
erfi(x) returns the imaginary error function of each element of x.
Examples
Imaginary Error Function for Floating-Point and Symbolic Numbers
Depending on its arguments, erfi can return floating-point or exact symbolic results.
Compute the imaginary error function for these numbers. Because these numbers are not symbolic
objects, you get floating-point results.
s =
0.6150 3.7382 3.7731
Compute the imaginary error function for the same numbers converted to symbolic objects. For most
symbolic (exact) numbers, erfi returns unresolved symbolic calls.
s =
[ erfi(1/2), erfi(141/100), erfi(2^(1/2))]
vpa(s, 10)
ans =
[ 0.6149520947, 3.738199581, 3.773122512]
Compute the imaginary error function for x and sin(x) + x*exp(x). For most symbolic variables
and expressions, erfi returns unresolved symbolic calls.
syms x
f = sin(x) + x*exp(x);
erfi(x)
erfi(f)
ans =
erfi(x)
7-406
erfi
ans =
erfi(sin(x) + x*exp(x))
If the input argument is a vector or a matrix, erfi returns the imaginary error function for each
element of that vector or matrix.
Compute the imaginary error function for elements of matrix M and vector V:
M = sym([0 inf; 1/3 -inf]);
V = sym([1; -i*inf]);
erfi(M)
erfi(V)
ans =
[ 0, Inf]
[ erfi(1/3), -Inf]
ans =
erfi(1)
-1i
Compute the imaginary error function for x = 0, x = ∞, and x = –∞. Use sym to convert 0 and
infinities to symbolic objects. The imaginary error function has special values for these parameters:
[erfi(sym(0)), erfi(sym(inf)), erfi(sym(-inf))]
ans =
[ 0, Inf, -Inf]
Compute the imaginary error function for complex infinities. Use sym to convert complex infinities to
symbolic objects:
[erfi(sym(i*inf)), erfi(sym(-i*inf))]
ans =
[ 1i, -1i]
Many functions, such as diff and int, can handle expressions containing erfi.
Compute the first and second derivatives of the imaginary error function:
syms x
diff(erfi(x), x)
diff(erfi(x), x, 2)
ans =
(2*exp(x^2))/pi^(1/2)
ans =
(4*x*exp(x^2))/pi^(1/2)
7-407
7 Functions
int(erfi(x), x)
int(erfi(log(x)), x)
ans =
x*erfi(x) - exp(x^2)/pi^(1/2)
ans =
x*erfi(log(x)) - int((2*exp(log(x)^2))/pi^(1/2), x)
Input Arguments
x — Input
floating-point number | symbolic number | symbolic variable | symbolic expression | symbolic function
| symbolic vector | symbolic matrix
7-408
erfi
More About
Imaginary Error Function
Tips
• erfi returns special values for these parameters:
• erfi(0) = 0
• erfi(inf) = inf
• erfi(-inf) = -inf
• erfi(i*inf) = i
• erfi(-i*inf) = -i
Version History
Introduced in R2013a
See Also
erf | erfc | erfcinv | erfinv | vpa
7-409
7 Functions
erfinv
Inverse error function
Syntax
erfinv(X)
Description
erfinv(X) computes the inverse error function on page 7-413 of X. If X is a vector or a matrix,
erfinv(X) computes the inverse error function of each element of X.
Examples
Inverse Error Function for Floating-Point and Symbolic Numbers
Depending on its arguments, erfinv can return floating-point or exact symbolic results.
Compute the inverse error function for these numbers. Because these numbers are not symbolic
objects, you get floating-point results:
A =
0.4769 0.3013 -0.3046
Compute the inverse error function for the same numbers converted to symbolic objects. For most
symbolic (exact) numbers, erfinv returns unresolved symbolic calls:
symA =
[ erfinv(1/2), erfinv(33/100), -erfinv(1/3)]
Use vpa to approximate symbolic results with the required number of digits:
d = digits(10);
vpa(symA)
digits(d)
ans =
[ 0.4769362762, 0.3013321461, -0.3045701942]
For most symbolic variables and expressions, erfinv returns unresolved symbolic calls.
Compute the inverse error function for x and sin(x) + x*exp(x). For most symbolic variables and
expressions, erfinv returns unresolved symbolic calls:
syms x
f = sin(x) + x*exp(x);
7-410
erfinv
erfinv(x)
erfinv(f)
ans =
erfinv(x)
ans =
erfinv(sin(x) + x*exp(x))
If the input argument is a vector or a matrix, erfinv returns the inverse error function for each
element of that vector or matrix.
Compute the inverse error function for elements of matrix M and vector V:
ans =
[ 0, NaN]
[ erfinv(1/3), Inf]
ans =
-Inf
NaN
Compute the inverse error function for x = –1, x = 0, and x = 1. The inverse error function has
special values for these parameters:
ans =
-Inf 0 Inf
Many functions, such as diff and int, can handle expressions containing erfinv.
Compute the first and second derivatives of the inverse error function:
syms x
diff(erfinv(x), x)
diff(erfinv(x), x, 2)
ans =
(pi^(1/2)*exp(erfinv(x)^2))/2
ans =
(pi*exp(2*erfinv(x)^2)*erfinv(x))/2
7-411
7 Functions
int(erfinv(x), x)
ans =
-exp(-erfinv(x)^2)/pi^(1/2)
syms x
fplot(erfinv(x),[-1,1])
grid on
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
7-412
erfinv
More About
Inverse Error Function
The inverse error function is defined as erf -1(x), such that erf(erf -1(x)) = erf -1(erf(x)) = x. Here
x
er f (x) =
2
π ∫e
0
−t2dt
Tips
• Calling erfinv for a number that is not a symbolic object invokes the MATLAB erfinv function.
This function accepts real arguments only. If you want to compute the inverse error function for a
complex number, use sym to convert that number to a symbolic object, and then call erfinv for
that symbolic object.
• If x < –1 or x > 1, or if x is complex, then erfinv(x) returns NaN.
Algorithms
The toolbox can simplify expressions that contain error functions and their inverses. For real values
x, the toolbox applies these simplification rules:
• erfcinv(x) = erfinv(1 - x)
• erfinv(-x) = -erfinv(x)
• erfcinv(2 - x) = -erfcinv(x)
• erf(erfinv(x)) = erfc(erfcinv(x)) = x
• erf(erfcinv(x)) = erfc(erfinv(x)) = 1 - x
Version History
Introduced in R2012a
References
[1] Gautschi, W. “Error Function and Fresnel Integrals.” Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New
York: Dover, 1972.
7-413
7 Functions
See Also
erf | erfc | erfcinv | erfi
7-414
euler
euler
Euler numbers and polynomials
Syntax
euler(n)
euler(n,x)
Description
euler(n) returns the nth Euler number on page 7-418.
Examples
Euler Numbers with Odd and Even Indices
The Euler numbers with even indices alternate the signs. Any Euler number with an odd index is 0.
Compute the even-indexed Euler numbers with the indices from 0 to 10:
euler(0:2:10)
ans =
1 -1 5 -61...
1385 -50521
Compute the odd-indexed Euler numbers with the indices from 1 to 11:
euler(1:2:11)
ans =
0 0 0 0 0 0
Euler Polynomials
For the Euler polynomials, use euler with two input arguments.
Compute the first, second, and third Euler polynomials in variables x, y, and z, respectively:
syms x y z
euler(1, x)
euler(2, y)
euler(3, z)
ans =
x - 1/2
ans =
y^2 - y
7-415
7 Functions
ans =
z^3 - (3*z^2)/2 + 1/4
If the second argument is a number, euler evaluates the polynomial at that number. Here, the result
is a floating-point number because the input arguments are not symbolic numbers:
euler(2, 1/3)
ans =
-0.2222
To get the exact symbolic result, convert at least one number to a symbolic object:
euler(2, sym(1/3))
ans =
-2/9
syms x
fplot(euler(0:5, x), [-1 2])
title('Euler Polynomials')
grid on
7-416
euler
Many functions, such as diff and expand, can handle expressions containing euler.
syms n x
diff(euler(n,x^2), x)
ans =
2*n*x*euler(n - 1, x^2)
diff(euler(n,x^2), x, x)
ans =
2*n*euler(n - 1, x^2) + 4*n*x^2*euler(n - 2, x^2)*(n - 1)
expand(euler(n, 2 - x))
ans =
2*(1 - x)^n - (-1)^n*euler(n, x)
expand(euler(n, 2*x))
ans =
(2*2^n*bernoulli(n + 1, x + 1/2))/(n + 1) -...
(2*2^n*bernoulli(n + 1, x))/(n + 1)
Input Arguments
n — Index of the Euler number or polynomial
nonnegative integer | symbolic nonnegative integer | symbolic variable | symbolic expression |
symbolic function | symbolic vector | symbolic matrix
Index of the Euler number or polynomial, specified as a nonnegative integer, symbolic nonnegative
integer, variable, expression, function, vector, or matrix. If n is a vector or matrix, euler returns
Euler numbers or polynomials for each element of n. If one input argument is a scalar and the other
one is a vector or a matrix, euler(n,x) expands the scalar into a vector or matrix of the same size
as the other argument with all elements equal to that scalar.
x — Polynomial variable
symbolic variable | symbolic expression | symbolic function | symbolic vector | symbolic matrix
7-417
7 Functions
More About
Euler Polynomials
Euler Numbers
n 1
euler n = 2 euler n,
2
Tips
• For the other meaning of Euler’s number, e = 2.71828…, call exp(1) to return the double-
precision representation. For the exact representation of Euler’s number e, call exp(sym(1)).
• For the Euler-Mascheroni constant, see eulergamma.
Version History
Introduced in R2014a
See Also
bernoulli | eulergamma
7-418
eulergamma
eulergamma
Euler-Mascheroni constant
Syntax
eulergamma
Description
eulergamma represents the Euler-Mascheroni constant on page 7-420. To get a floating-point
approximation with the current precision set by digits, use vpa(eulergamma).
Examples
Represent and Numerically Approximate the Euler-Mascheroni Constant
Represent the Euler-Mascheroni constant using eulergamma, which returns the symbolic form
eulergamma.
eulergamma
ans =
eulergamma
Use eulergamma in symbolic calculations. Numerically approximate your result with vpa.
a = eulergamma;
g = a^2 + log(a)
gVpa = vpa(g)
g =
log(eulergamma) + eulergamma^2
gVpa =
-0.21636138917392614801928563244766
ans =
0.5772
Show the relations between the Euler-Mascheroni constant γ, digamma function Ψ, and gamma
function Γ.
Show that γ = − Ψ 1 .
-psi(sym(1))
ans =
eulergamma
7-419
7 Functions
Show that γ = − Γ′ x x = 1.
syms x
-subs(diff(gamma(x)),x,1)
ans =
eulergamma
More About
Euler-Mascheroni Constant
Tips
• For the value e = 2.71828…, called Euler’s number, use exp(1) to return the double-precision
representation. For the exact representation of Euler’s number e, call exp(sym(1)).
• For the other meaning of Euler’s numbers and for Euler’s polynomials, see euler.
Version History
Introduced in R2014a
See Also
coshint | euler
7-420
eulerPhi
eulerPhi
Euler phi function
Syntax
p = eulerPhi(n)
Description
p = eulerPhi(n) evaluates the Euler phi function on page 7-423 or (also known as the totient
function) for a positive integer n.
Examples
Compute the Euler phi function ϕ(n) for the integer n = 35.
p = eulerPhi(35)
p = 24
The Euler phi function satisfies the multiplicative property ϕ(xy) = ϕ(x) ϕ(y) if the two integers x and
y are relatively prime (also known as coprime). The integer factorization of 35 is 7 and 5, which are
relatively prime. Show that ϕ(35) satisfies the multiplicative property.
px = 6
py = eulerPhi(5)
py = 4
p = 24
1 1 1
ϕ(n) = n 1 − 1− … 1− .
p1 p2 pr
7-421
7 Functions
The integer n = 36 has distinct prime factors 2 and 3. Show that ϕ(36) satisfies the Euler's product
formula.
n = sym(36)
n = 36
p = eulerPhi(n)
p = 12
f_n = factor(n)
f_n = 2 2 3 3
p_product = n*(1-1/2)*(1-1/3)
p_product = 12
Euler's Theorem
Euler's theorem states that aϕ(n) ≡ 1(mod n) if and only if the two positive integers a and n are
relatively prime. Show that the Euler phi function ϕ(n) satisfies Euler's theorem for the integers
a = 15 and n = 4.
a = 15;
n = 4;
isCongruent = powermod(a,eulerPhi(n),n) == mod(1,n)
isCongruent = logical
1
g = gcd(a,n)
g = 1
Calculate the Euler phi function ϕ(n) for the integers n from 1 to 1000.
P = eulerPhi(1:1000);
Pave = mean(P./(1:1000))
7-422
eulerPhi
Pave = 0.6082
Input Arguments
n — Input
number | vector | matrix | array | symbolic number | symbolic array
Input, specified as a number, vector, matrix, array, symbolic number, or symbolic array. The elements
of n must be positive integers.
Data Types: single | double | sym
More About
Euler Phi Function
The Euler phi function ϕ(n) computes the number of integers between 1 and n that are relatively
prime (also known as coprime) to n. Two integers are relatively prime if there is no integer greater
than one that divides them both. In other words, their greatest common divisor is one.
Version History
Introduced in R2020a
References
[1] Redmond, D. Number Theory: An Introduction to Pure and Applied Mathematics. New York:
Marcel Dekker, 1996.
See Also
isprime | primes
7-423
7 Functions
evalin
(Not recommended) Evaluate MuPAD expressions without specifying their arguments
Syntax
result = evalin(symengine,MuPAD_expression)
[result,status] = evalin(symengine,MuPAD_expression)
Description
result = evalin(symengine,MuPAD_expression) evaluates the MuPAD expression
MuPAD_expression, and returns result as a symbolic object. If MuPAD_expression throws an
error in MuPAD, then this syntax throws an error in MATLAB.
Examples
Perform MuPAD Command
evalin(symengine,'linalg::eigenvalues(matrix([[x,y],[y,x]]))')
ans =
[x + y, x - y]
Input Arguments
MuPAD_expression — Input
character vector
Output Arguments
result — Computation result
character vector | symbolic object
Computation result returned as a symbolic object or character vector containing a MuPAD error
message.
7-424
evalin
Error status returned as an integer. If F with the arguments x1,...,xn executes without errors, the
error status is 0.
Tips
• Results returned by evalin can differ from the results that you get using a MuPAD notebook
directly. The reason is that evalin sets a lower level of evaluation to achieve better performance.
• evalin does not open a MuPAD notebook, and therefore, you cannot use this function to access
MuPAD graphics capabilities.
Version History
Introduced in R2008b
Symbolic Math Toolbox includes operations and functions for symbolic math expressions that parallel
MATLAB functionality for numeric values. Unlike MuPAD functionality, Symbolic Math Toolbox
functions enable you to work in familiar interfaces, such as the MATLAB Command Window or Live
Editor, which offer a smooth workflow and are optimized for usability.
Therefore, instead of passing MuPAD expressions to evalin, use the equivalent Symbolic Math
Toolbox functionality to work with symbolic math expressions. For a list of available functions, see
Symbolic Math Toolbox functions list.
To convert a MuPAD notebook file to a MATLAB live script file, see convertMuPADNotebook.
If you cannot find the Symbolic Math Toolbox equivalent for MuPAD functionality, contact MathWorks
Technical Support.
Although the use of evalin is not recommended, there are no plans to remove it at this time.
7-425
7 Functions
expand
Expand expressions and simplify inputs of functions by using identities
Syntax
expand(S)
expand(S,Name,Value)
Description
expand(S) multiplies all parentheses in S, and simplifies inputs to functions such as cos(x + y) by
applying standard identities.
Examples
syms x
p = (x - 2)*(x - 4);
expand(p)
ans =
x^2 - 6*x + 8
Expand the trigonometric expression cos(x + y). Simplify the cos function input x + y to x or y
by applying standard identities.
syms x y
expand(cos(x + y))
ans =
cos(x)*cos(y) - sin(x)*sin(y)
syms a b
f = exp((a + b)^2);
expand(f)
7-426
expand
ans =
exp(a^2)*exp(b^2)*exp(2*a*b)
Expand expressions in a vector. Simplify the inputs to functions in the expressions by applying
identities.
syms t
V = [sin(2*t), cos(2*t)];
expand(V)
ans =
[ 2*cos(t)*sin(t), 2*cos(t)^2 - 1]
By default, expand both expands terms raised to powers and expands functions by applying identities
that simplify inputs to the functions. Expand only terms raised to powers and suppress expansion of
functions by using 'ArithmeticOnly'.
Expand (sin(3*x) - 1)^2. By default, expand will expand the power ^2 and simplify the sin
input 3*x to x.
syms x
f = (sin(3*x) - 1)^2;
expand(f)
ans =
2*sin(x) + sin(x)^2 - 8*cos(x)^2*sin(x) - 8*cos(x)^2*sin(x)^2...
+ 16*cos(x)^4*sin(x)^2 + 1
ans =
sin(3*x)^2 - 2*sin(3*x) + 1
Simplify the input of log function calls. By default, expand does not simplify logarithm input because
the identities used are not valid for complex values of variables.
syms a b c
f = log((a*b/c)^2);
expand(f)
ans =
log((a^2*b^2)/c^2)
7-427
7 Functions
expand(f,'IgnoreAnalyticConstraints',true)
ans =
2*log(a) + 2*log(b) - 2*log(c)
Input Arguments
S — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: expand(S,'ArithmeticOnly',true)
Use convenient identities for simplification, specified as the comma-separated pair consisting of
'IgnoreAnalyticConstraints' and true or false.
Setting 'IgnoreAnalyticConstraints' to true can give you simpler solutions, which could lead
to results not generally valid. In other words, this option applies mathematical identities that are
convenient, but the results might not hold for all values of the variables. In some cases, this option
can let expand return simpler results that might not be equivalent to the initial expression. See
“Algorithms” on page 7-428.
Algorithms
When you use 'IgnoreAnalyticConstraints', expand applies some of these rules.
• log(a) + log(b) = log(a·b) for all values of a and b. In particular, the following equality is valid for
all values of a, b, and c:
(a·b)c = ac·bc.
• log(ab) = b·log(a) for all values of a and b. In particular, the following equality is valid for all values
of a, b, and c:
7-428
expand
(ab)c = ab·c.
• If f and g are standard mathematical functions and f(g(x)) = x for all small positive numbers,
f(g(x)) = x is assumed to be valid for all complex x.
• log(ex) = x
• asin(sin(x)) = x, acos(cos(x)) = x, atan(tan(x)) = x
• asinh(sinh(x)) = x, acosh(cosh(x)) = x, atanh(tanh(x)) = x
• Wk(x·ex) = x for all values of k
Version History
Introduced before R2006a
See Also
Functions
collect | combine | factor | horner | numden | rewrite | simplify | simplifyFraction
Topics
“Choose Function to Rearrange Expression” on page 3-119
“Simplify Symbolic Expressions” on page 3-129
“Simplify Symbolic Expressions Using Live Editor Task” on page 3-134
7-429
7 Functions
expint
Exponential integral function
Syntax
expint(x)
expint(n,x)
Description
expint(x) returns the one-argument exponential integral function defined as
∞
−t
expint x = ∫ et
x
dt .
Examples
One-Argument Exponential Integral for Floating-Point and Symbolic Numbers
Compute the exponential integrals for floating-point numbers. Because these numbers are not
symbolic objects, you get floating-point results.
s =
0.8289 + 0.0000i 0.2194 + 0.0000i -4.9542 - 3.1416i
Compute the exponential integrals for the same numbers converted to symbolic objects. For positive
values x, expint(x) returns -ei(-x). For negative values x, it returns -pi*i - ei(-x).
s =
[ -ei(-1/3), -ei(-1), - ei(2) - pi*1i]
vpa(s, 10)
ans =
[ 0.8288877453, 0.2193839344, - 4.954234356 - 3.141592654i]
When computing two-argument exponential integrals, convert the numbers to symbolic objects.
7-430
expint
s =
[ expint(2, 1/3), 0, -exp(2)/4]
vpa(s, 25)
ans =
[ 0.4402353954575937050522018, 0, -1.847264024732662556807607]
syms x
expint(0, x)
expint(-1, x)
expint(-2, x)
ans =
exp(-x)/x
ans =
exp(-x)*(1/x + 1/x^2)
ans =
exp(-x)*(1/x + 2/x^2 + 2/x^3)
Compute the first, second, and third derivatives of a one-argument exponential integral.
syms x
diff(expint(x), x)
diff(expint(x), x, 2)
diff(expint(x), x, 3)
ans =
-exp(-x)/x
ans =
exp(-x)/x + exp(-x)/x^2
ans =
- exp(-x)/x - (2*exp(-x))/x^2 - (2*exp(-x))/x^3
syms n x
diff(expint(n, x), x)
diff(expint(n, x), n)
ans =
-expint(n - 1, x)
7-431
7 Functions
ans =
- hypergeom([1 - n, 1 - n], [2 - n, 2 - n],...
-x)/(n - 1)^2 - (x^(n - 1)*pi*(psi(n) - ...
log(x) + pi*cot(pi*n)))/(sin(pi*n)*gamma(n))
Input Arguments
x — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
n — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Input specified as a symbolic number, variable, expression, function, vector, or matrix. When you
compute the two-argument exponential integral function, at least one argument must be a scalar.
Tips
• Calling expint for numbers that are not symbolic objects invokes the MATLAB expint function.
This function accepts one argument only. To compute the two-argument exponential integral, use
sym to convert the numbers to symbolic objects, and then call expint for those symbolic objects.
You can approximate the results with floating-point numbers using vpa.
• The following values of the exponential integral differ from those returned by the MATLAB
expint function: expint(sym(Inf)) = 0, expint(-sym(Inf)) = -Inf,
expint(sym(NaN)) = NaN.
• For positive real x, expint(x) = -ei(-x). For negative real x, expint(x) = -pi*i - ei(-
x).
• If one input argument is a scalar and the other argument is a vector or a matrix, then
expint(n,x) expands the scalar into a vector or matrix of the same size as the other argument
with all elements equal to that scalar.
Algorithms
The relation between expint and ei is
expint(1,-x) = ei(x) + (ln(x)-ln(1/x))/2 - ln(-x)
Both functions ei(x) and expint(1,x) have a logarithmic singularity at the origin and a branch cut
along the negative real axis. The ei function is not continuous when approached from above or below
this branch cut.
The expint function is related to the upper incomplete gamma function igamma as
expint(n,x) = (x^(n-1))*igamma(1-n,x)
Version History
Introduced in R2013a
7-432
expint
See Also
ei | expint | vpa
7-433
7 Functions
expm
Matrix exponential of symbolic matrices
Syntax
R = expm(A)
Description
R = expm(A) computes the matrix exponential on page 7-434 of the square symbolic matrix A.
Examples
Matrix Exponential
Compute the matrix exponential for the 2-by-2 matrix and simplify the result.
syms x
A = [0 x; -x 0];
simplify(expm(A))
ans =
[ cos(x), sin(x)]
[ -sin(x), cos(x)]
Input Arguments
A — Input matrix
square matrix
Output Arguments
R — Resulting matrix
symbolic matrix
More About
Matrix Exponential
7-434
expm
Version History
Introduced before R2006a
See Also
eig | funm | jordan | logm | sqrtm
7-435
7 Functions
ezcontour
(Not recommended) Contour plotter
Syntax
ezcontour(f)
ezcontour(f,domain)
ezcontour( ___ ,n)
Description
ezcontour(f) plots the contour lines of f(x,y), where f is a symbolic expression that represents a
mathematical function of two variables, such as x and y. ezcontour automatically adds a title and
axis labels.
The function f is plotted over the default domain –2π < x < 2π, –2π < y < 2π. MATLAB software
chooses the computational grid according to the amount of variation that occurs; if the function f is
not defined (singular) for points on the grid, then these points are not plotted.
ezcontour(f,domain) plots f(x,y) over the specified domain. domain can be either a 4-by-1 vector
[xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where, min < x < max, min < y < max). If f is
a function of the variables u and v (rather than x and y), then the domain endpoints umin, umax,
vmin, and vmax are sorted alphabetically. Thus, ezcontour(u^2 - v^3,[0,1],[3,6]) plots the
contour lines for u2 - v3 over 0 < u < 1, 3 < v < 6.
ezcontour( ___ ,n) plots f over the default domain using an n-by-n grid. The default value for n is
60.
Examples
Plot Contour Lines of Symbolic Expression
2 2 − (y + 1)2 x 2 2 1 2 2
f (x, y) = 3(1 − x) e−x − 10 − x3 − y5 e−x − y − e−(x + 1) − y .
5 3
ezcontour requires a sym argument that expresses this function using MATLAB syntax to represent
exponents, natural logs, etc. This function is represented by the symbolic expression
syms x y
f = 3*(1-x)^2*exp(-(x^2)-(y+1)^2)...
- 10*(x/5 - x^3 - y^5)*exp(-x^2-y^2)...
- 1/3*exp(-(x+1)^2 - y^2);
7-436
ezcontour
Pass the sym f to ezcontour along with a domain ranging from -3 to 3 and specify a computational
grid of 49-by-49.
ezcontour(f,[-3,3],49)
In this particular case, the title is too long to fit at the top of the graph so MATLAB abbreviates the
title.
Input Arguments
f — Input
symbolic function | symbolic expression
Domain to plot over, specified as a symbolic vector. domain is a 4-by-1 vector [xmin, xmax, ymin,
ymax] or a 2-by-1 vector [min, max] (where, min < x < max, min < y < max). If f is a function of the
variables u and v (rather than x and y), then the domain endpoints umin, umax, vmin, and vmax are
sorted alphabetically
n — grid points
number | symbolic number
7-437
7 Functions
Version History
Introduced before R2006a
See Also
contour | fcontour | fmesh | fplot | fplot3 | fsurf
7-438
ezcontourf
ezcontourf
(Not recommended) Filled contour plotter
Syntax
ezcontourf(f)
ezcontourf(f,domain)
ezcontourf( ___ ,n)
Description
ezcontourf(f) plots the contour lines of f(x,y), where f is a sym that represents a mathematical
function of two variables, such as x and y.
The function f is plotted over the default domain –2π < x < 2π, –2π < y < 2π. MATLAB software
chooses the computational grid according to the amount of variation that occurs; if the function f is
not defined (singular) for points on the grid, then these points are not plotted.
ezcontourf(f,domain) plots f(x,y) over the specified domain. domain can be either a 4-by-1
vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where, min < x < max, min < y <
max). If f is a function of the variables u and v (rather than x and y), then the domain endpoints umin,
umax, vmin, and vmax are sorted alphabetically. Thus, ezcontourf(u^2 - v^3,[0,1],[3,6])
plots the contour lines for u2 - v3 over 0 < u < 1, 3 < v < 6.
ezcontourf( ___ ,n) plots f over the default domain using an n-by-n grid. The default value for n is
60.
Examples
Plot Filled Contours
2 2 − (y + 1)2 x 2 2 1 2 2
f (x, y) = 3(1 − x) e−x − 10 − x3 − y5 e−x − y − e−(x + 1) − y .
5 3
ezcontourf requires a sym argument that expresses this function using MATLAB syntax to
represent exponents, natural logs, etc. This function is represented by the symbolic expression
syms x y
f = 3*(1-x)^2*exp(-(x^2)-(y+1)^2)...
- 10*(x/5 - x^3 - y^5)*exp(-x^2-y^2)...
- 1/3*exp(-(x+1)^2 - y^2);
7-439
7 Functions
Pass the sym f to ezcontourf along with a domain ranging from -3 to 3 and specify a grid of 49-
by-49.
ezcontourf(f,[-3,3],49)
In this particular case, the title is too long to fit at the top of the graph so MATLAB abbreviates the
title.
Input Arguments
f — Input
symbolic function | symbolic expression
Domain to plot over, specified as a symbolic vector. domain is a 4-by-1 vector [xmin, xmax, ymin,
ymax] or a 2-by-1 vector [min, max] (where, min < x < max, min < y < max). If f is a function of the
variables u and v (rather than x and y), then the domain endpoints umin, umax, vmin, and vmax are
sorted alphabetically
n — grid points
number | symbolic number
7-440
ezcontourf
Version History
Introduced before R2006a
See Also
contour | fcontour | fmesh | fplot | fplot3 | fsurf
7-441
7 Functions
ezmesh
(Not recommended) 3-D mesh plotter
Syntax
ezmesh(f)
ezmesh(f,domain)
ezmesh(x,y,z)
ezmesh(x,y,z,domain)
ezmesh( ___ ,n)
ezmesh( ___ ,'circ')
Description
ezmesh(f) creates a graph of f(x,y), where f is a symbolic expression that represents a
mathematical function of two variables, such as x and y.
The function f is plotted over the default domain –2π < x < 2π, –2π < y < 2π. MATLAB software
chooses the computational grid according to the amount of variation that occurs; if the function f is
not defined (singular) for points on the grid, then these points are not plotted.
ezmesh(f,domain) plots f over the specified domain. domain can be either a 4-by-1 vector [xmin,
xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where, min < x < max, min < y < max).
If f is a function of the variables u and v (rather than x and y), then the domain endpoints umin, umax,
vmin, and vmax are sorted alphabetically. Thus, ezmesh(u^2 - v^3,[0,1],[3,6]) plots u2 - v3
over 0 < u < 1, 3 < v < 6.
ezmesh(x,y,z) plots the parametric surface x = x(s,t), y = y(s,t), and z = z(s,t) over the square –
2π < s < 2π, –2π < t < 2π.
ezmesh( ___ ,n) plots f over the default domain using an n-by-n grid. The default value for n is 60.
Examples
3-D Mesh Plot of Symbolic Expression
with a mesh plot drawn on a 40-by-40 grid. The mesh lines are set to a uniform blue color by setting
the colormap to a single color.
7-442
ezmesh
syms x y
ezmesh(x*exp(-x^2-y^2),[-2.5,2.5],40)
colormap([0 0 1])
Input Arguments
f — Input
symbolic function | symbolic expression
x — Input
symbolic function | symbolic expression
y — Input
symbolic function | symbolic expression
z — Input
symbolic function | symbolic expression
7-443
7 Functions
Domain to plot over, specified as a symbolic vector. domain is a 4-by-1 vector [xmin, xmax, ymin,
ymax] or a 2-by-1 vector [min, max] (where, min < x < max, min < y < max). If f is a function of the
variables u and v (rather than x and y), then the domain endpoints umin, umax, vmin, and vmax are
sorted alphabetically.
n — grid points
number | symbolic number
Version History
Introduced before R2006a
See Also
fcontour | fmesh | fplot | fplot3 | fsurf | mesh
7-444
ezmeshc
ezmeshc
(Not recommended) Combined mesh and contour plotter
Syntax
ezmeshc(f)
ezmeshc(f,domain)
ezmeshc(x,y,z)
ezmeshc(x,y,z,domain)
ezmeshc( ___ ,n)
ezmeshc( ___ ,'circ')
Description
ezmeshc(f) creates a graph of f(x,y), where f is a symbolic expression that represents a
mathematical function of two variables, such as x and y.
The function f is plotted over the default domain –2π < x < 2π, –2π < y < 2π. MATLAB software
chooses the computational grid according to the amount of variation that occurs; if the function f is
not defined (singular) for points on the grid, then these points are not plotted.
ezmeshc(f,domain) plots f over the specified domain. domain can be either a 4-by-1 vector [xmin,
xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where, min < x < max, min < y < max).
If f is a function of the variables u and v (rather than x and y), then the domain endpoints umin, umax,
vmin, and vmax are sorted alphabetically. Thus, ezmeshc(u^2 - v^3,[0,1],[3,6]) plots u2 – v3
over 0 < u < 1, 3 < v < 6.
ezmeshc(x,y,z) plots the parametric surface x = x(s,t), y = y(s,t), and z = z(s,t) over the square –
2π < s < 2π, –2π < t < 2π.
ezmeshc( ___ ,n) plots f over the default domain using an n-by-n grid. The default value for n is 60.
Examples
3-D Mesh Plot with Contours
y
f (x, y) = ,
1 + x2 + y2
7-445
7 Functions
over the domain –5 < x < 5, –2π < y < 2π. Use the mouse to rotate the axes to better observe the
contour lines (this picture uses a view of azimuth = –65 and elevation = 26).
syms x y
ezmeshc(y/(1 + x^2 + y^2),[-5,5,-2*pi,2*pi])
Input Arguments
f — Input
symbolic function | symbolic expression
x — Input
symbolic function | symbolic expression
y — Input
symbolic function | symbolic expression
z — Input
symbolic function | symbolic expression
7-446
ezmeshc
Domain to plot over, specified as a symbolic vector. domain is a 4-by-1 vector [xmin, xmax, ymin,
ymax] or a 2-by-1 vector [min, max] (where, min < x < max, min < y < max). If f is a function of the
variables u and v (rather than x and y), then the domain endpoints umin, umax, vmin, and vmax are
sorted alphabetically.
n — grid points
number | symbolic number
Version History
Introduced before R2006a
See Also
fcontour | fmesh | fplot | fplot3 | fsurf | meshc
7-447
7 Functions
ezplot
(Not recommended) Plot symbolic expression, equation, or function
Note ezplot is not recommended. Use fplot instead. For implicit plots, use fimplicit.
Syntax
ezplot(f)
ezplot(f,[min,max])
ezplot(f,[xmin,xmax,ymin,ymax])
ezplot(x,y)
ezplot(x,y,[tmin,tmax])
ezplot(f,[min,max],fig)
ezplot(f,[xmin,xmax,ymin,ymax],fig)
ezplot(x,y,[tmin,tmax],fig)
h = ezplot( ___ )
Description
ezplot(f) plots a symbolic expression, equation, or function f. By default, ezplot plots a
univariate expression or function over the range [–2π 2π] or over a subinterval of this range. If f is an
equation or function of two variables, the default range for both variables is [–2π 2π] or over a
subinterval of this range.
ezplot(f,[xmin,xmax,ymin,ymax]) plots f over the specified ranges along the abscissa and the
ordinate.
ezplot(x,y) plots the parametrically defined planar curve x = x(t) and y = y(t) over the default
range 0 <= t <= 2π or over a subinterval of this range.
ezplot(x,y,[tmin,tmax]) plots x = x(t) and y = y(t) over the specified range tmin <= t <= tmax.
ezplot(f,[min,max],fig) plots f over the specified range in the figure with the figure number or
figure handle fig. The title of each plot window contains the word Figure and the number, for
example, Figure 1, Figure 2, and so on. If fig is already open, ezplot overwrites the content of
that figure with the new plot.
ezplot(x,y,[tmin,tmax],fig) plots x = x(t) and y = y(t) over the specified range in fig.
7-448
ezplot
h = ezplot( ___ ) returns the plot handle as either a chart line or contour object.
Examples
Plot Over Particular Range
syms x
ezplot(erf(x), [-pi, pi])
syms x y
ezplot(x^2 == y^4)
7-449
7 Functions
syms x y
f(x, y) = sin(x + y)*sin(x*y);
ezplot(f)
7-450
ezplot
syms t
x = t*sin(5*t);
y = t*cos(5*t);
ezplot(x, y)
7-451
7 Functions
Input Arguments
f — Input
symbolic expression | symbolic equation | symbolic function
Numbers specifying the plotting range, specified as a vector of length 2. For a univariate expression
or function, the plotting range applies to that variable. For an equation or function of two variables,
the plotting range applies to both variables. In this case, the range is the same for the abscissa and
the ordinate.
Numbers specifying the plotting range, specified as a numeric or symbolic vector along the abscissa
(first two numbers) and the ordinate (last two numbers).
fig — Figure
figure handle | figure window
Figure specified as a figure handle or figure window where you want to display a plot. For figure
handle, the current figure handle returned by gcf. For figure number, if no plot windows are open,
7-452
ezplot
then 1. If one plot window is open, then the number in the title of that window. If more than one plot
window is open, then the highest number in the titles of open windows.
Output Arguments
h — Chart line or contour line object
scalar
Chart line or contour line object, returned as a scalar. For details, see Chart Line and Contour.
Tips
• If you do not specify a plot range, ezplot uses the interval [–2π 2π] as a starting point. Then it
can choose to display a part of the plot over a subinterval of [–2π 2π] where the plot has
significant variation. Also, when selecting the plotting range, ezplot omits extreme values
associated with singularities.
• ezplot open a plot window and displays a plot there. If any plot windows are already open,
ezplot does not create a new window. Instead, it displays the new plot in the currently active
window. (Typically, it is the window with the highest number.) To display the new plot in a new plot
window or in an existing window other than that with highest number, use fig.
• If f is an equation or function of two variables, then the alphabetically first variable defines the
abscissa (horizontal axis) and the other variable defines the ordinate (vertical axis). Thus,
ezplot(x^2 == a^2,[-3,3,-2,2]) creates the plot of the equation x2 = a2 with –3 <= a <= 3
along the horizontal axis, and –2 <= x <= 2 along the vertical axis.
Version History
Introduced before R2006a
See Also
fcontour | fmesh | fplot | fplot3 | fsurf | plot
Topics
“Create Plots of Symbolic Expressions” on page 4-2
7-453
7 Functions
ezplot3
(Not recommended) 3-D parametric curve plotter
Syntax
ezplot3(x,y,z)
ezplot3(x,y,z,[tmin,tmax])
ezplot3( ___ ,'animate')
Description
ezplot3(x,y,z) plots the spatial curve x = x(t), y = y(t), and z = z(t) over the default domain
0 < t < 2π.
ezplot3(x,y,z,[tmin,tmax]) plots the curve x = x(t), y = y(t), and z = z(t) over the domain tmin
< t < tmax.
Examples
3-D Parametric Curve
Plot the parametric curve x = sin(t), y = cos(t), z = t over the domain [0, 6π].
syms t
ezplot3(sin(t), cos(t), t,[0,6*pi])
7-454
ezplot3
Input Arguments
x — Input
symbolic function | symbolic expression
y — Input
symbolic function | symbolic expression
z — Input
symbolic function | symbolic expression
Domain to plot over, specified as a symbolic vector. ezplot3 plots over the domain tmin < t < tmax
Version History
Introduced before R2006a
7-455
7 Functions
See Also
fcontour | fmesh | fplot | fplot3 | fsurf | plot3
7-456
ezpolar
ezpolar
Polar coordinate plotter
Syntax
ezpolar(f)
ezpolar(f, [a b])
Description
ezpolar(f) plots the polar curve r = f(θ) over the default domain 0 < θ < 2π.
Examples
Create a polar plot of the function r(t) = 1 + cos(t) over the domain 0 < t < 2π.
syms t
ezpolar(1 + cos(t))
7-457
7 Functions
Input Arguments
f — Input
symbolic function | symbolic expression
Version History
Introduced before R2006a
7-458
ezsurf
ezsurf
(Not recommended) Plot 3-D surface
Syntax
ezsurf(f)
ezsurf(f,[xmin,xmax])
ezsurf(f,[xmin,xmax,ymin,ymax])
ezsurf(x,y,z)
ezsurf(x,y,z,[smin,smax])
ezsurf(x,y,z,[smin,smax,tmin,tmax])
h = ezsurf( ___ )
Description
ezsurf(f) plots a two-variable symbolic expression or function f(x,y) over the range -2*pi < x
< 2*pi, -2*pi < y < 2*pi.
ezsurf(f,[xmin,xmax]) plots f(x,y) over the specified range xmin < x < xmax. This is the
range along the abscissa (horizontal axis).
ezsurf(f,[xmin,xmax,ymin,ymax]) plots f(x,y) over the specified ranges along the abscissa,
xmin < x < xmax, and the ordinate, ymin < y < ymax.
When determining the range values, ezsurf sorts variables alphabetically. For example,
ezsurf(x^2 - a^3, [0,1,3,6]) plots x^2 - a^3 over 0 < a < 1, 3 < x < 6.
ezsurf(x,y,z) plots the parametric surface x = x(s,t), y = y(s,t), z = z(s,t) over the
range -2*pi < s < 2*pi, -2*pi < t < 2*pi.
ezsurf( ___ ,n) specifies the grid. You can specify n after the input arguments in any of the
previous syntaxes. By default, n = 60.
ezsurf( ___ ,'circ') creates the surface plot over a disk centered on the range. You can
specify'circ' after the input arguments in any of the previous syntaxes.
7-459
7 Functions
h = ezsurf( ___ ) returns a handle h to the surface plot object. You can use the output argument h
with any of the previous syntaxes.
Examples
Plot the symbolic function f(x,y) = real(atan(x + i*y)) over the default range -2*pi < x <
2*pi, -2*pi < y < 2*pi.
Plot the symbolic expression x^2 + y^2 over the range -1 < x < 1. Because you do not specify the
range for the y-axis, ezsurf chooses it automatically.
7-460
ezsurf
syms x y
ezsurf(x^2 + y^2, [-1, 1])
7-461
7 Functions
syms s t
r = 2 + sin(7*s + 5*t);
x = r*cos(s)*sin(t);
y = r*sin(s)*sin(t);
z = r*cos(t);
7-462
ezsurf
7-463
7 Functions
First, plot the expression sin(x^2 + y^2) over the square range -pi/2 < x < pi/2, -pi/2 < y
< pi/2.
syms x y
ezsurf(sin(x^2 + y^2), [-pi/2, pi/2, -pi/2, pi/2])
7-464
ezsurf
7-465
7 Functions
Plot the symbolic expression sin(x)cos(x), and assign the result to the handle h.
syms x y
h = ezsurf(sin(x)*cos(y), [-pi, pi])
7-466
ezsurf
h =
Surface with properties:
EdgeColor: [0 0 0]
LineStyle: '-'
FaceColor: 'flat'
FaceLighting: 'flat'
FaceAlpha: 1
XData: [60x60 double]
YData: [60x60 double]
ZData: [60x60 double]
CData: [60x60 double]
You can use this handle to change properties of the plot. For example, change the color of the area
outline.
h.EdgeColor = 'red'
7-467
7 Functions
h =
Surface with properties:
EdgeColor: [1 0 0]
LineStyle: '-'
FaceColor: 'flat'
FaceLighting: 'flat'
FaceAlpha: 1
XData: [60x60 double]
YData: [60x60 double]
ZData: [60x60 double]
CData: [60x60 double]
Input Arguments
f — Function to plot
symbolic expression with two variables | symbolic function of two variables
7-468
ezsurf
Parametric function to plot, specified as three symbolic expressions or functions of two variables.
Example: ezsurf(s*cos(t), s*sin(t), t)
n — Grid value
integer
Output Arguments
h — Surface plot handle
scalar
Surface plot handle, returned as a scalar. It is a unique identifier, which you can use to query and
modify properties of the surface plot.
Tips
• ezsurf chooses the computational grid according to the amount of variation that occurs. If f is
singular for some points on the grid, then ezsurf omits these points. The value at these points is
set to NaN.
Version History
Introduced before R2006a
See Also
fcontour | fmesh | fplot | fplot3 | fsurf | surf
Topics
“Create Plots of Symbolic Expressions” on page 4-2
7-469
7 Functions
ezsurfc
(Not recommended) Combined surface and contour plotter
Syntax
ezsurfc(f)
ezsurfc(f,domain)
ezsurfc(x,y,z)
ezsurfc(x,y,z,domain)
ezsurfc( ___ ,n)
ezsurfc( ___ ,'circ')
Description
ezsurfc(f) creates a graph of f(x,y), where f is a symbolic expression that represents a
mathematical function of two variables, such as x and y. The function f is plotted over the default
domain –2π < x < 2π, –2π < y < 2π. MATLAB software chooses the computational grid according to
the amount of variation that occurs; if the function f is not defined (singular) for points on the grid,
then these points are not plotted.
ezsurfc(f,domain) plots f over the specified domain. domain can be either a 4-by-1 vector [xmin,
xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where, min < x < max, min < y < max).
If f is a function of the variables u and v (rather than x and y), then the domain endpoints umin, umax,
vmin, and vmax are sorted alphabetically. Thus, ezsurfc(u^2 - v^3,[0,1],[3,6]) plots u2 – v3
over 0 < u < 1, 3 < v < 6.
ezsurfc(x,y,z) plots the parametric surface x = x(s,t), y = y(s,t), and z = z(s,t) over the square –
2π < s < 2π, –2π < t < 2π.
ezsurfc( ___ ,n) plots f over the default domain using an n-by-n grid. The default value for n is 60.
Examples
3-D Surface Plot with Contours
y
f (x, y) = ,
1 + x2 + y2
7-470
ezsurfc
over the domain –5 < x < 5, –2π < y < 2π, with a computational grid of size 35-by-35. Use the mouse
to rotate the axes to better observe the contour lines (this picture uses a view of azimuth = -65 and
elevation = 26).
syms x y
ezsurfc(y/(1 + x^2 + y^2),[-5,5,-2*pi,2*pi],35)
Input Arguments
f — Input
symbolic function | symbolic expression
x — Input
symbolic function | symbolic expression
y — Input
symbolic function | symbolic expression
z — Input
symbolic function | symbolic expression
7-471
7 Functions
Domain to plot over, specified as a symbolic vector. domain is a 4-by-1 vector [xmin, xmax, ymin,
ymax] or a 2-by-1 vector [min, max] (where, min < x < max, min < y < max). If f is a function of the
variables u and v (rather than x and y), then the domain endpoints umin, umax, vmin, and vmax are
sorted alphabetically.
n — grid points
number | symbolic number
Version History
Introduced before R2006a
See Also
fcontour | fmesh | fplot | fplot3 | fsurf | surfc
7-472
factor
factor
Factorization
Syntax
F = factor(x)
F = factor(x,vars)
F = factor( ___ ,Name,Value)
Description
F = factor(x) returns all irreducible factors of x in vector F. If x is an integer, factor returns the
prime factorization of x. If x is a symbolic expression, factor returns the subexpressions that are
factors of x.
F = factor(x,vars) returns an array of factors F, where vars specifies the variables of interest.
All factors not containing a variable in vars are separated into the first entry F(1). The other entries
are irreducible factors of x that contain one or more variables from vars.
F = factor( ___ ,Name,Value) uses additional options specified by one or more Name,Value
pair arguments. This syntax can use any of the input arguments from the previous syntaxes.
Examples
Factor Integer Numbers
F = factor(823429252)
F =
2 2 59 283 12329
To factor integers greater than flintmax, convert the integer to a symbolic object using sym. Then
place the number in quotation marks to represent it accurately.
F = factor(sym('82342925225632328'))
F =
[ 2, 2, 2, 251, 401, 18311, 5584781]
F = factor(sym(-92465))
F =
[ -1, 5, 18493]
Perform prime factorization for 41758540882408627201. Since the integer is greater than
flintmax, convert it to a symbolic object using sym, and place the number in quotation marks to
represent it accurately.
7-473
7 Functions
n = sym('41758540882408627201');
factor(n)
ans =
[ 479001599, 87178291199]
Factor the fraction 112/81 by converting it into a symbolic object using sym.
F = factor(sym(112/81))
F =
[ 2, 2, 2, 2, 7, 1/3, 1/3, 1/3, 1/3]
Factor Polynomials
syms x
F = factor(x^6-1)
F =
[ x - 1, x + 1, x^2 + x + 1, x^2 - x + 1]
syms y
F = factor(y^6-x^6)
F =
[ -1, x - y, x + y, x^2 + x*y + y^2, x^2 - x*y + y^2]
syms x y
F = factor(y^2*x^2,x)
F =
[ y^2, x, x]
factor combines all factors without x into the first element. The remaining elements of F contain
irreducible factors that contain x.
syms a b c d
y = -a*b^5*c*d*(a^2 - 1)*(a*d - b*c);
F = factor(y,[b c])
F =
[ -a*d*(a - 1)*(a + 1), b, b, b, b, b, c, a*d - b*c]
factor combines all factors without b or c into the first element of F. The remaining elements of F
contain irreducible factors of y that contain either b or c.
7-474
factor
Factor an expression without specifying the factorization mode. By default, factor uses factorization
over rational numbers. In this mode, factor keeps rational numbers in their exact symbolic form.
syms x
factor(x^3 + 2, x)
ans =
x^3 + 2
Factor the same expression, but this time use numeric factorization over real numbers. This mode
factors the expression into linear and quadratic irreducible polynomials with real coefficients and
converts all numeric values to floating-point numbers.
ans =
[ x + 1.2599210498948731647672106072782,...
x^2 - 1.2599210498948731647672106072782*x + 1.5874010519681994747517056392723]
Factor this expression using factorization over complex numbers. In this mode, factor reduces
quadratic polynomials to linear expressions with complex coefficients. This mode converts all numeric
values to floating-point numbers.
ans =
[ x + 1.2599210498948731647672106072782,...
x - 0.62996052494743658238360530363911 + 1.0911236359717214035600726141898i,...
x - 0.62996052494743658238360530363911 - 1.0911236359717214035600726141898i]
Factor this expression using the full factorization mode. This mode factors the expression into linear
expressions, reducing quadratic polynomials to linear expressions with complex coefficients. This
mode keeps rational numbers in their exact symbolic form.
ans =
[ x + 2^(1/3),...
x - 2^(1/3)*((3^(1/2)*1i)/2 + 1/2),...
x + 2^(1/3)*((3^(1/2)*1i)/2 - 1/2)]
Approximate the result with floating-point numbers by using vpa. Because the expression does not
contain any symbolic parameters besides the variable x, the result is the same as in complex
factorization mode.
vpa(ans)
ans =
[ x + 1.2599210498948731647672106072782,...
x - 0.62996052494743658238360530363911 - 1.0911236359717214035600726141898i,...
x - 0.62996052494743658238360530363911 + 1.0911236359717214035600726141898i]
7-475
7 Functions
In the full factorization mode,factor also can return results as a symbolic sums over polynomial
roots expressed as RootOf.
syms x
s = factor(x^3 + x - 3, x, 'FactorMode','full')
s =
[ x - root(z^3 + z - 3, z, 1),...
x - root(z^3 + z - 3, z, 2),...
x - root(z^3 + z - 3, z, 3)]
vpa(s)
ans =
[ x - 1.2134116627622296341321313773815,...
x + 0.60670583138111481706606568869074 + 1.450612249188441526515442203395i,...
x + 0.60670583138111481706606568869074 - 1.450612249188441526515442203395i]
Input Arguments
x — Input to factor
number | symbolic number | symbolic expression | symbolic function
Variables of interest, specified as a symbolic variable or a vector of symbolic variables. Factors that
do not contain a variable specified in vars are grouped into the first element of F. The remaining
elements of F contain irreducible factors of x that contain a variable in vars.
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: factor(x^3 - 2,x,'FactorMode','real')
Factorization mode, specified as the comma-separated pair consisting of 'FactorMode' and one of
these character vectors.
7-476
factor
Output Arguments
F — Factors of input
symbolic vector
Tips
• To factor an integer greater than flintmax, wrap the integer with sym. Then place the integer in
quotation marks to represent it accurately, for example, sym('465971235659856452').
• To factor a negative integer, wrap the integer with sym, for example, sym(-3).
Version History
Introduced before R2006a
See Also
collect | combine | divisors | expand | horner | numden | rewrite | simplify |
simplifyFraction
Topics
“Choose Function to Rearrange Expression” on page 3-119
7-477
7 Functions
factorial
Factorial of symbolic input
Syntax
f = factorial(n)
Description
f = factorial(n) returns the factorial on page 7-480 of n. If n is an array, factorial acts
element-wise on n.
Examples
f = factorial(sym(20))
f = 2432902008176640000
Compute the factorial function for a symbolic expression. factorial returns exact symbolic output
as the function call.
syms n
expr = n^2 + 1;
f = factorial(expr)
f = n2 + 1 !
Calculate the factorial for a value of n = 3. Substitute the value of n by using subs.
fVal = subs(f,n,3)
fVal = 3628800
syms n
f = factorial(n^2 + n + 1)
7-478
factorial
f = n2 + n + 1 !
df = diff(f)
df = n2 + n + 1 ! ψ n2 + n + 2 2 n + 1
The derivative of the factorial function is expressed in terms of the psi function.
syms n
f = factorial(n^2 + n + 1);
f1 = expand(f)
f1 = n2 + n ! n2 + n + 1
Compute the limit at infinity for an expression containing the factorial function.
syms n
f = factorial(n)/exp(n);
fLim = limit(f,n,Inf)
fLim = ∞
Compute factorial for array input. factorial acts element-wise on array input.
A = sym([1 3; 4 5]);
f = factorial(A)
f =
1 6
24 120
Input Arguments
n — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
7-479
7 Functions
More About
Factorial Function
The factorial of 0 is 1.
Tips
• Calling factorial for a number that is not a symbolic object invokes the MATLAB factorial
function.
Version History
Introduced in R2012a
See Also
beta | gamma | nchoosek | psi
7-480
factorIntegerPower
factorIntegerPower
Perfect power factoring
Syntax
x = factorIntegerPower(n)
[x,k] = factorIntegerPower(n)
Description
x = factorIntegerPower(n) factors the number n into its perfect power xk and returns the base
x. If several perfect powers exist, x is returned for maximum k. The function factorIntegerPower
acts element-wise on array input.
Examples
Factor 64 into its perfect power. If several perfect powers exist for a number, the maximum k is
returned.
n = 64;
[x,k] = factorIntegerPower(n)
x =
2
k =
6
n = [7 841 2541865828329];
[x,k] = factorIntegerPower(n)
x =
7 29 3
k =
1 2 26
Reconstruct the numbers. Return exact symbolic integers instead of floating point by converting x to
symbolic form.
sym(x).^k
ans =
[ 7, 841, 2541865828329]
7-481
7 Functions
If a number is not a perfect power, factorIntegerPower returns the number itself as the base with
exponent 1. So, a number is a perfect power if it does not equal its base.
Check if 125 is a perfect power. isequal returns logical 0 (false), meaning 125 is not equal to the
returned base. Therefore, 125 is a perfect power.
n = 125;
isequal(n,factorIntegerPower(n))
ans =
logical
0
Input Arguments
n — Input
number | vector | matrix | array | symbolic number | symbolic array
Input, specified as a number, vector, matrix, array, or a symbolic number or array. n must be a
positive integer.
Output Arguments
x — Base in perfect power
number | vector | matrix | array | symbolic number | symbolic array
Base in perfect power, returned as a number, vector, matrix, array, or a symbolic number or array.
Power in perfect power, returned as a number, vector, matrix, array, or a symbolic number or array.
Version History
Introduced in R2018a
See Also
factor
7-482
fanimator
fanimator
Create stop-motion animation object
Syntax
fanimator(f)
fanimator(f,args)
Description
fanimator(f) creates a stop-motion animation object from the function f. The function f must
return graphics objects that depend on only one variable. This variable defines the time parameter of
the animation.
By default, fanimator creates stop-motion frames of f(t0), generating 10 frames per unit interval of
t0 within the range of t0 from 0 to 10.
fanimator(f,args) allows the function f to depend on multiple variables. args specifies the input
arguments of f.
By default, the variable t = sym('t') is the time parameter of the animation. This syntax creates
stop-motion frames of f(subs(args,t,t0)) within the range of t0 from 0 to 10. You can animate a
specific property of the graphics objects by setting its value to depend on t in the input argument
args.
fanimator( ___ ,Name,Value) specifies the animation properties using one or more Name,Value
pair arguments. Use this option with any of the input argument combinations in the previous
syntaxes. Name-value pair settings apply to the animation object created.
fanimator(ax, ___ ) creates a stop-motion animation object in the axis specified by ax instead of
in the current axis (gca). The option ax can precede any input argument combinations in the
previous syntaxes.
fp = fanimator( ___ ) returns an Animator object. Use fp to query and modify the properties of
a specific animation object. For a list of properties, see Animator Properties.
Examples
First, create a function to plot a point at (t,1). The variable t defines the time parameter of the
animation.
7-483
7 Functions
f = @(t) plot(t,1,'r*');
fanimator(f)
Next, create a function handle by using fplot to plot a unit circle. The circle is a function of two
variables.
Create two symbolic variables t and x. Use t to set the center of the circle at (t,1) and x to
parameterize the perimeter of the circle within the range [-pi pi]. Add the circle animation object
to the existing plot. Set the x-axis and y-axis to be equal length.
syms t x
hold on
fanimator(@fplot,cos(x)+t,sin(x)+1,[-pi pi])
axis equal
hold off
7-484
fanimator
Enter the command playAnimation to play the animation. By default, fanimator creates an
animation object, generating 10 frames per unit time within the range of t from 0 to 10.
7-485
7 Functions
Animate a line that changes vertical length and line width. You can animate a specific graphics
property by setting its value to depend on the animation time parameter. By default, the variable t is
the time parameter of the animation.
Create two symbolic variables, y and t. Plot a line with y coordinates within the interval [0 t] by
using fplot. Use the fanimator function to create the line animation object. fanimator changes
the line vertical length by increasing the value of t from 0 to 10.
syms y t
fanimator(@fplot,1,y,[0 t])
7-486
fanimator
7-487
7 Functions
Now plot a line with y coordinates within the interval [0 2] by using fplot. Set the 'LineWidth'
property value to t+1. Use the fanimator function to create the line animation object. fanimator
changes the line width by increasing the value of t from 0 to 10.
fanimator(@fplot,1,y,[0 2],'LineWidth',t+1)
7-488
fanimator
7-489
7 Functions
First, create a function that plots a unit circle and save it in a file named circ.m. The function uses
fplot to plot a unit circle centered at (t,1), and the local symbolic variable x to parameterize the
perimeter of the circle.
function C = circ(t)
x = sym('x');
C = fplot(cos(x)+t,sin(x)+1,[0 2*pi],'Color','red');
end
Use fanimator to create a unit circle animation object. Set the animation range of the time
parameter to [2 4.5] and the frame rate per unit time to 4. Set the x-axis and y-axis to be equal
length.
fanimator(@circ,'AnimationRange',[2 4.5],'FrameRate',4)
axis equal
7-490
fanimator
Next, add a timer animation object. Create a piece of text to count the elapsed time by using the
text function. Use num2str to convert the time parameter to a string. Set the animation range of
the timer to [0 4.5].
hold on
fanimator(@(t) text(4.5,2.5,"Timer: "+num2str(t,2)),'AnimationRange',[0 4.5])
hold off
7-491
7 Functions
Enter the command playAnimation to play the animation. The timer counts the elapsed time from 0
to 4.5 seconds. The moving circle starts at 2 seconds and stops at 4.5 seconds.
7-492
fanimator
Animate two cycloids in separate axes. A cycloid is the curve traced by a fixed point on a circle as the
circle moves along a straight line without slipping.
First, create two symbolic variables x and t. Create a figure with two subplots and return the first
axes object as ax1. Create a moving circle animation object in ax1 and add a fixed point on the rim of
the circle. Set the x-axis and y-axis to be equal length.
syms x t
ax1 = subplot(2,1,1);
fanimator(ax1, @fplot, cos(x)+t, sin(x)+1, [-pi pi])
axis equal
hold on
fanimator(ax1, @(t) plot(t-sin(t), 1-cos(t), 'r*'))
7-493
7 Functions
To trace the cycloid, use a time variable in the plotting interval. The fplot function plots a curve
within the interval [0 t]. Create the cycloid animation object. By default, fanimator creates stop-
motion frames within the range of t from 0 to 10 seconds. fanimator plots the first frame at t equal
to 0.
7-494
fanimator
Next, create another cycloid on the second axes object ax2. Trace the curve created by a fixed point
at a distance of 1/2 from the center of the circle. Set the x-axis and y-axis to be equal length.
ax2 = subplot(2,1,2);
fanimator(ax2, @fplot, cos(x)+t, sin(x)+1, [-pi pi])
axis equal
hold on
fanimator(ax2, @(t) plot(t-sin(t)/2, 1-cos(t)/2, 'r*'))
fanimator(ax2, @fplot, x-sin(x)/2, 1-cos(x)/2, [0 t], 'k')
hold off
7-495
7 Functions
7-496
fanimator
fig = uifigure;
ax = uiaxes(fig);
7-497
7 Functions
Add an animation object to the UI axes using fanimator. Create two symbolic variables, x and t.
Plot a curve that grows exponentially as a function of time t within the interval [0 3].
syms x t;
fanimator(ax,@fplot,exp(x),[0 t],'r','AnimationRange',[0 3])
7-498
fanimator
Play the animation in the UI figure fig by entering the command playAnimation(fig).
Alternatively, you can also use the command playAnimation(ax.Parent).
7-499
7 Functions
Input Arguments
f — Function returning graphics objects
function handle
Function returning graphics objects, specified as a function handle. For more information about
function handles, see “Create Function Handle”.
Further arguments, specified as input arguments of a function handle that returns the graphics
objects.
ax — Target axes
Axes object
Target axes, specified as an Axes object. For more information about Axes objects, see axes.
7-500
fanimator
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: 'AnimationRange',[2 8],'FrameRate',30
Range of the animation time parameter, specified as a two-element row vector. The two elements
must be real values that are increasing.
Example: [-2 4.5]
Frame rate, specified as a positive value. The frame rate defines the number of frames per unit time
for the animation object.
Example: 30
Output Arguments
fp — Animation object
scalar
Animation object, returned as a scalar. You can use this object to query and modify the properties of
the generated animation frames. For a list of properties, see Animator Properties.
Tips
• When you create a graph by using a plotting function, such as fplot, MATLAB creates a series of
graphics objects. You can then animate a specific property of the graphics objects by using the
fanimator and the playAnimation functions. Note that some functions, such as title and
xlabel, create text objects that cannot be animated. Instead, use the text function to create text
objects that can be animated.
Version History
Introduced in R2019a
See Also
animationToFrame | playAnimation | rewindAnimation | writeAnimation
7-501
7 Functions
fcontour
Plot contours of symbolic expression
Syntax
fcontour(f)
fcontour(f,[min max])
fcontour(f,[xmin xmax ymin ymax])
Description
fcontour(f) plots the contour lines of symbolic expression f(x,y) over the default interval of x and
y, which is [-5 5].
fcontour(f,[min max]) plots f over the interval min < x < max and min < y < max.
fcontour(f,[xmin xmax ymin ymax]) plots f over the interval xmin < x < xmax and ymin < y
< ymax. The fcontour function uses symvar to order the variables and assign intervals.
fcontour( ___ ,LineSpec) uses LineSpec to set the line style and color. fcontour doesn’t
support markers.
fcontour( ___ ,Name,Value) specifies line properties using one or more Name,Value pair
arguments. Use this option with any of the input argument combinations in the previous syntaxes.
Name,Value pair settings apply to all the lines plotted. To set options for individual plots, use the
objects returned by fcontour.
fcontour(ax, ___ ) plots into the axes object ax instead of the current axes object gca.
fc = fcontour( ___ ) returns a function contour object. Use the object to query and modify
properties of a specific contour plot. For details, see Function Contour.
Examples
Plot the contours of sin(x) + cos(y) over the default range of −5 < x < 5 and −5 < y < 5. Show the
colorbar. Find a contour's level by matching the contour's color with the colorbar value.
syms x y
fcontour(sin(x) + cos(y))
colorbar
7-502
fcontour
Plot the contours of f (x, y) = sin(x) + cos(y) over the default range of −5 < x < 5 and −5 < y < 5.
syms f(x,y)
f(x,y) = sin(x) + cos(y);
fcontour(f)
7-503
7 Functions
Plot sin(x) + cos(y) over −π/2 < x < π/2 and 0 < y < 5 by specifying the plotting interval as the
second argument of fcontour.
syms x y
f = sin(x) + cos(y);
fcontour(f,[-pi/2 pi/2 0 5])
7-504
fcontour
Plot the contours of x2 − y2 as blue, dashed lines by specifying the LineSpec input. Specify a
LineWidth of 2. Markers are not supported by fcontour.
syms x y
fcontour(x^2 - y^2,'--b','LineWidth',2)
7-505
7 Functions
Plot multiple contour plots either by passing the inputs as a vector or by using hold on to
successively plot on the same figure. If you specify LineStyle and Name-Value arguments, they
apply to all contour plots. You cannot specify individual LineStyle and Name-Value pair arguments
for each plot.
Divide a figure into two subplots by using subplot. On the first subplot, plot sin(x) + cos(y) and x − y
by using vector input. On the second subplot, plot the same expressions by using hold on.
syms x y
subplot(2,1,1)
fcontour([sin(x)+cos(y) x-y])
title('Multiple Contour Plots Using Vector Inputs')
subplot(2,1,2)
fcontour(sin(x)+cos(y))
hold on
fcontour(x-y)
title('Multiple Contour Plots Using Hold Command')
hold off
7-506
fcontour
2 2 2 2
Plot the contours of e−(x/3) − (y/3) + e−(x + 2) − (y + 2) . Specify an output to make fcontour return
the plot object.
syms x y
f = exp(-(x/3)^2-(y/3)^2) + exp(-(x+2)^2-(y+2)^2);
fc = fcontour(f)
7-507
7 Functions
fc =
FunctionContour with properties:
Change the LineWidth to 1 and the LineStyle to a dashed line by using dot notation to set
properties of the object fc. Visualize contours close to 0 and 1 by setting LevelList to [1 0.9 0.8
0.2 0.1].
fc.LineStyle = '--';
fc.LineWidth = 1;
fc.LevelList = [1 0.9 0.8 0.2 0.1];
colorbar
7-508
fcontour
Fill the area between contours by setting the Fill input of fcontour to 'on'. If you want
interpolated shading instead, use the fsurf function with its option 'EdgeColor' set to 'none'
followed by the command view(0,90).
3 2 2
erf((y + 2) ) − e( − 0 . 65((x − 2) + (y − 2) ) .
syms x y
f = erf((y+2)^3) - exp(-0.65*((x-2)^2+(y-2)^2));
fcontour(f,'Fill','on')
7-509
7 Functions
Set the values at which fcontour draws contours by using the 'LevelList' option.
syms x y
f = sin(x) + cos(y);
fcontour(f,'LevelList',[-1 0 1])
7-510
fcontour
Control the resolution of contour lines by using the 'MeshDensity' option. Increasing
'MeshDensity' can make smoother, more accurate plots while decreasing it can increase plotting
speed.
Divide a figure into two using subplot. In the first subplot, plot the contours of sin(x)sin(y). The
corners of the squares do not meet. To fix this issue, increase 'MeshDensity' to 200 in the second
subplot. The corners now meet, showing that by increasing 'MeshDensity' you increase the plot's
resolution.
syms x y
subplot(2,1,1)
fcontour(sin(x).*sin(y))
title('Default MeshDensity = 71')
subplot(2,1,2)
fcontour(sin(x).*sin(y),'MeshDensity',200)
title('Increased MeshDensity = 200')
7-511
7 Functions
Plot xsin(y) − ycos(x). Add a title and axis labels. Create the x-axis ticks by spanning the x-axis limits
at intervals of pi/2. Display these ticks by using the XTick property. Create x-axis labels by using
arrayfun to apply texlabel to S. Display these labels by using the XTickLabel property. Repeat
these steps for the y-axis.
syms x y
fcontour(x*sin(y)-y*cos(x), [-2*pi 2*pi])
grid on
title('xsin(y)-ycos(x) for -2\pi < x < 2\pi and -2\pi < y < 2\pi')
xlabel('x')
ylabel('y')
ax = gca;
S = sym(ax.XLim(1):pi/2:ax.XLim(2));
ax.XTick = double(S);
ax.XTickLabel = arrayfun(@texlabel, S, 'UniformOutput', false);
S = sym(ax.YLim(1):pi/2:ax.YLim(2));
ax.YTick = double(S);
ax.YTickLabel = arrayfun(@texlabel, S, 'UniformOutput', false);
7-512
fcontour
Create animation of contours by changing the displayed expression using the Function property of
the function handle, and then using drawnow to update the plot. To export to GIF, see imwrite.
syms x y
fc = fcontour(-pi/8.*sin(x)-pi/8.*cos(y));
for k = -pi/8:0.01:pi/8
fc.Function = k.*sin(x)+k.*cos(y);
drawnow
pause(0.05)
end
7-513
7 Functions
Input Arguments
f — Expression or function to be plotted
symbolic expression | symbolic function
Plotting range for x and y, specified as a vector of two numbers. The default range is [-5 5].
Plotting range for x and y, specified as a vector of four numbers. The default range is [-5 5 -5 5].
ax — Axes object
axes object
Axes object. If you do not specify an axes object, then the plot function uses the current axes.
7-514
fcontour
Line style and color, specified as a character vector or string containing a line style specifier, a color
specifier, or both.
Example: '--r' specifies red dashed lines
These two tables list the line style and color options.
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: 'MeshDensity',30
The properties listed here are only a subset. For a complete list, see Function Contour.
Number of evaluation points per direction, specified as a number. The default is 71. Because
fcontour uses adaptive evaluation, the actual number of evaluation points is greater.
Example: 30
Fill between contour lines, specified as 'on' or 'off', or as numeric or logical 1 (true) or 0
(false). A value of 'on' is equivalent to true, and 'off' is equivalent to false. Thus, you can use
the value of this property as a logical value. The value is stored as an on/off logical value of type
matlab.lang.OnOffSwitchState.
7-515
7 Functions
• A value of 'on' fill the spaces between contour lines with color.
• A value of 'off' leaves the spaces between the contour lines unfilled.
Contour levels, specified as a vector of z values. By default, the fcontour function chooses values
that span the range of values in the ZData property.
Spacing between contour lines, specified as a scalar numeric value. For example, specify a value of 2
to draw contour lines at increments of 2. By default, LevelStep is determined by using the ZData
values.
Color of contour lines, specified as 'flat', an RGB triplet, a hexadecimal color code, a color name,
or a short name. To use a different color for each contour line, specify 'flat'. The color is
determined by the contour value of the line, the colormap, and the scaling of data values into the
colormap. For more information on color scaling, see “Control Colormap Limits”.
To use the same color for all the contour lines, specify an RGB triplet, a hexadecimal color code, a
color name, or a short name.
7-516
fcontour
• An RGB triplet is a three-element row vector whose elements specify the intensities of the red,
green, and blue components of the color. The intensities must be in the range [0,1], for example,
[0.4 0.6 0.7].
• A hexadecimal color code is a string scalar or character vector that starts with a hash symbol (#)
followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case
sensitive. Therefore, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are
equivalent.
Alternatively, you can specify some common colors by name. This table lists the named color options,
the equivalent RGB triplets, and hexadecimal color codes.
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many
types of plots.
7-517
7 Functions
Line width, specified as a positive value in points, where 1 point = 1/72 of an inch. If the line has
markers, then the line width also affects the marker edges.
The line width cannot be thinner than the width of a pixel. If you set the line width to a value that is
less than the width of a pixel on your system, the line displays as one pixel wide.
Output Arguments
fc — One or more function contour objects
scalar | vector
One or more function contour objects, returned as a scalar or a vector. These objects are unique
identifiers, which you can use to query and modify the properties of a specific contour plot. For
details, see Function Contour.
Algorithms
fcontour assigns the symbolic variables in f to the x-axis, then the y-axis, and symvar determines
the order of the variables to be assigned. Therefore, variable and axis names might not correspond.
To force fcontour to assign x or y to its corresponding axis, create the symbolic function to plot,
then pass the symbolic function to fcontour.
For example, the following code plots the contour of the surface f(x,y) = sin(y) in two ways. The first
way forces the waves to oscillate with respect to the y-axis. In other words, the first plot assigns the y
variable to the corresponding y-axis. The second plot assigns y to the x-axis because it is the first (and
only) variable in the symbolic function.
syms x y;
f(x,y) = sin(y);
figure;
subplot(2,1,1)
fcontour(f);
subplot(2,1,2)
fcontour(f(x,y)); % Or fcontour(sin(y));
7-518
fcontour
Version History
Introduced in R2016a
See Also
Functions
fimplicit | fimplicit3 | fmesh | fplot | fplot3 | fsurf
Properties
Function Contour
Topics
“Create Plots of Symbolic Expressions” on page 4-2
7-519
7 Functions
feval
(Not recommended) Evaluate MuPAD expressions specifying their arguments
Syntax
result = feval(symengine,F,x1,...,xn)
[result,status] = feval(symengine,F,x1,...,xn)
Description
result = feval(symengine,F,x1,...,xn) evaluates F, which is either a MuPAD function name
or a symbolic object, with arguments x1,...,xn. Here, the returned value result is a symbolic
object. If F with the arguments x1,...,xn throws an error in MuPAD, then this syntax throws an
error in MATLAB.
Examples
Perform MuPAD Command
ans =
[x + y, x - y]
Alternatively, the same calculation based on variables not defined in the MATLAB workspace is:
feval(symengine,'linalg::eigenvalues','matrix([[x,y],[y,x]])')
ans =
[x + y, x - y]
Input Arguments
F — Input
MuPAD function name | symbolic object
7-520
feval
x1,...,xn — Arguments
symbolic expression
Output Arguments
result — Computation result
character vector | symbolic object
Computation result returned as a symbolic object or character vector containing a MuPAD error
message.
Error status returned as an integer. If F with the arguments x1,...,xn executes without errors, the
error status is 0.
Tips
• Results returned by feval can differ from the results that you get using a MuPAD notebook
directly. The reason is that feval sets a lower level of evaluation to achieve better performance.
• feval does not open a MuPAD notebook, and therefore, you cannot use this function to access
MuPAD graphics capabilities.
Version History
Introduced in R2008b
Symbolic Math Toolbox includes operations and functions for symbolic math expressions that parallel
MATLAB functionality for numeric values. Unlike MuPAD functionality, Symbolic Math Toolbox
functions enable you to work in familiar interfaces, such as the MATLAB Command Window or Live
Editor, which offer a smooth workflow and are optimized for usability.
Therefore, instead of passing MuPAD expressions to feval, use the equivalent Symbolic Math
Toolbox functionality to work with symbolic math expressions. For a list of available functions, see
Symbolic Math Toolbox functions list.
To convert a MuPAD notebook file to a MATLAB live script file, see convertMuPADNotebook.
If you cannot find the Symbolic Math Toolbox equivalent for MuPAD functionality, contact MathWorks
Technical Support.
Although the use of feval is not recommended, there are no plans to remove it at this time.
7-521
7 Functions
fibonacci
Fibonacci numbers
Syntax
fibonacci(n)
Description
fibonacci(n) returns the nth “Fibonacci Number” on page 7-525.
Examples
Find Fibonacci Numbers
fibonacci(6)
ans =
8
n = 1:10;
fibonacci(n)
ans =
1 1 2 3 5 8 13 21 34 55
The ratio of successive Fibonacci numbers converges to the golden ratio 1 . 61803 . . .. Show this
convergence by plotting this ratio against the golden ratio for the first 10 Fibonacci numbers.
n = 2:10;
ratio = fibonacci(n)./fibonacci(n-1);
plot(n,ratio,'--o')
hold on
line(xlim,[1.618 1.618])
hold off
7-522
fibonacci
Use Fibonacci numbers in symbolic calculations by representing them with symbolic input.
fibonacci returns the input.
syms n
fibonacci(n)
ans =
fibonacci(n)
Find large Fibonacci numbers by specifying the input symbolically using sym. Symbolic input returns
exact symbolic output instead of double output. Convert symbolic numbers to double by using the
double function.
num = sym(300);
fib300 = fibonacci(num)
fib300 =
222232244629420445529739893461909967206666939096499764990979600
7-523
7 Functions
ans =
2.2223e+62
For more information on symbolic and double arithmetic, see “Choose Numeric or Symbolic
Arithmetic” on page 2-32.
The Fibonacci numbers are commonly visualized by plotting the Fibonacci spiral. The Fibonacci spiral
approximates the golden spiral.
Approximate the golden spiral for the first 8 Fibonacci numbers. Define the four cases for the right,
top, left, and bottom squares in the plot by using a switch statement. Form the spiral by defining the
equations of arcs through the squares in eqnArc. Draw the squares and arcs by using rectangle
and fimplicit respectively.
x = 0;
y = 1;
syms v u
axis off
hold on
for n = 1:8
a = fibonacci(n);
% Draw square
pos = [x y a a];
rectangle('Position', pos)
7-524
fibonacci
% Draw arc
interval = [x x+a y y+a];
fimplicit(eqnArc, interval, 'b')
end
Input Arguments
n — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
Input, specified as a number, vector, matrix or multidimensional array, or a symbolic number, variable,
vector, matrix, multidimensional array, function, or expression.
More About
Fibonacci Number
Given that the first two numbers are 0 and 1, the nth Fibonacci number is
Fn = Fn–1 + Fn–2.
7-525
7 Functions
Version History
Introduced in R2017a
7-526
fimplicit
fimplicit
Plot implicit symbolic equation or function
Syntax
fimplicit(f)
fimplicit(f,[min max])
fimplicit(f,[xmin xmax ymin ymax])
Description
fimplicit(f) plots the implicit symbolic equation or function f over the default interval [-5 5]
for x and y.
fimplicit(f,[min max]) plots f over the interval min < x < max and min < y < max.
fimplicit(f,[xmin xmax ymin ymax]) plots f over the interval xmin < x < xmax and ymin < y
< ymax. The fimplicit function uses symvar to order the variables and assign intervals.
fimplicit( ___ ,LineSpec) uses LineSpec to set the line style, marker symbol, and line color.
fimplicit( ___ ,Name,Value) specifies line properties using one or more Name,Value pair
arguments. Use this option with any of the input argument combinations in the previous syntaxes.
Name,Value pair settings apply to all the lines plotted. To set options for individual lines, use the
objects returned by fimplicit.
fimplicit(ax, ___ ) plots into the axes specified by ax instead of the current axes gca.
fi = fimplicit( ___ ) returns an implicit function line object. Use the object to query and modify
properties of a specific line. For details, see Implicit Function Line.
Examples
Plot the hyperbola x2 − y2 = 1 by using fimplicit. The fimplicit function uses the default
interval of [ − 5, 5] for x and y.
syms x y
fimplicit(x^2 - y^2 == 1)
7-527
7 Functions
Plot the hyperbola described by the function f (x, y) = x2 − y2 − 1 by first declaring the symbolic
function f(x,y) using syms. The fimplicit function uses the default interval of [ − 5, 5] for x and
y.
syms f(x,y)
f(x,y) = x^2 - y^2 - 1;
fimplicit(f)
7-528
fimplicit
Plot half of the circle x2 + y2 = 3 by using the intervals −4 < x < 0 and −2 < y < 2. Specify the
plotting interval as the second argument of fimplicit.
syms x y
circle = x^2 + y^2 == 3;
fimplicit(circle, [-4 0 -2 2])
7-529
7 Functions
You can plot multiple equations either by passing the inputs as a vector or by using hold on to
successively plot on the same figure. If you specify LineSpec and Name-Value arguments, they apply
to all lines. To set options for individual plots, use the function handles returned by fimplicit.
Divide a figure into two subplots by using subplot. On the first subplot, plot x2 + y2 = = 1 and
x2 + y2 = = 3 using vector input. On the second subplot, plot the same inputs by using hold on.
syms x y
circle1 = x^2 + y^2 == 1;
circle2 = x^2 + y^2 == 3;
subplot(2,1,1)
fimplicit([circle1 circle2])
title('Multiple Equations Using Vector Input')
subplot(2,1,2)
fimplicit(circle1)
hold on
fimplicit(circle2)
title('Multiple Equations Using hold on Command')
hold off
7-530
fimplicit
Plot three concentric circles of increasing diameter. For the first line, use a linewidth of 2. For the
second, specify a dashed red line style with circle markers. For the third, specify a cyan, dash-dot line
style with asterisk markers. Display the legend.
syms x y
circle = x^2 + y^2;
fimplicit(circle == 1, 'Linewidth', 2)
hold on
fimplicit(circle == 2, '--or')
fimplicit(circle == 3, '-.*c')
legend('show','Location','best')
hold off
7-531
7 Functions
Plot ysin(x) + xcos(y) = 1. Specify an output to make fimplicit return the plot object.
syms x y
eqn = y*sin(x) + x*cos(y) == 1;
fi = fimplicit(eqn)
7-532
fimplicit
fi =
ImplicitFunctionLine with properties:
Change the plotted equation to xcos(y) + ysin(x) = 0 by using dot notation to set properties. Similarly,
change the line color to red and line style to a dash-dot line. The horizontal and vertical lines in the
output are artifacts that should be ignored.
7-533
7 Functions
Plot xcos(y) + ysin(x) = 1 over the interval −2π < x < 2π and −2π < y < 2π. Add a title and axis
labels. Create the x-axis ticks by spanning the x-axis limits at intervals of pi/2. Display these ticks by
using the XTick property. Create x-axis labels by using arrayfun to apply texlabel to S. Display
these labels by using the XTickLabel property. Repeat these steps for the y-axis.
S = sym(ax.XLim(1):pi/2:ax.XLim(2));
ax.XTick = double(S);
ax.XTickLabel = arrayfun(@texlabel, S, 'UniformOutput', false);
S = sym(ax.YLim(1):pi/2:ax.YLim(2));
ax.YTick = double(S);
ax.YTickLabel = arrayfun(@texlabel, S, 'UniformOutput', false);
7-534
fimplicit
Re-Evaluation on Zoom
When you zoom into a plot, fimplicit re-evaluates the plot automatically. This re-evaluation on
zoom can reveal hidden detail at smaller scales.
Divide a figure into two by using subplot. Plot xcos(y) + ysin(1/x) = 0 in both the first and second
subplots. Zoom into the second subplot by using zoom. The zoomed subplot shows detail that is not
visible in the first subplot.
syms x y
eqn = x*cos(y) + y*sin(1/x) == 0;
subplot(2,1,1)
fimplicit(eqn)
subplot(2,1,2)
fimplicit(eqn)
zoom(2)
7-535
7 Functions
Input Arguments
f — Implicit equation or function to plot
symbolic equation | symbolic expression | symbolic function
Implicit equation or function to plot, specified as a symbolic equation, expression, or function. If the
right-hand side is not specified, then it is assumed to be 0.
Plotting range for x and y, specified as a vector of two numbers. The default range is [-5 5].
Plotting range for x and y, specified as a vector of four numbers. The default range is [-5 5 -5 5].
ax — Axes object
axes object
Axes object. If you do not specify an axes object, then fimplicit uses the current axes gca.
7-536
fimplicit
Line style, marker, and color, specified as a string scalar or character vector containing symbols. The
symbols can appear in any order. You do not need to specify all three characteristics (line style,
marker, and color). For example, if you omit the line style and specify the marker, then the plot shows
only the marker and no line.
Example: "--or" is a red dashed line with circle markers.
"*" Asterisk
"." Point
"x" Cross
"square" Square
"diamond" Diamond
"pentagram" Pentagram
"hexagram" Hexagram
7-537
7 Functions
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
The function line properties listed here are only a subset. For a complete list, see Implicit Function
Line.
Example: 'Marker','o','MarkerFaceColor','red'
Number of evaluation points per direction, specified as a number. The default is 151.
Line color, specified as an RGB triplet, a hexadecimal color code, a color name, or a short name.
• An RGB triplet is a three-element row vector whose elements specify the intensities of the red,
green, and blue components of the color. The intensities must be in the range [0,1], for example,
[0.4 0.6 0.7].
• A hexadecimal color code is a string scalar or character vector that starts with a hash symbol (#)
followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case
sensitive. Therefore, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are
equivalent.
Alternatively, you can specify some common colors by name. This table lists the named color options,
the equivalent RGB triplets, and hexadecimal color codes.
7-538
fimplicit
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many
types of plots.
Example: 'blue'
Example: [0 0 1]
Example: '#0000FF'
Line width, specified as a positive value in points, where 1 point = 1/72 of an inch. If the line has
markers, then the line width also affects the marker edges.
7-539
7 Functions
The line width cannot be thinner than the width of a pixel. If you set the line width to a value that is
less than the width of a pixel on your system, the line displays as one pixel wide.
Marker symbol, specified as one of the values listed in this table. By default, the object does not
display markers. Specifying a marker symbol adds markers at each data point or vertex.
"*" Asterisk
"." Point
"x" Cross
"square" Square
"diamond" Diamond
"pentagram" Pentagram
"hexagram" Hexagram
Marker outline color, specified as "auto", an RGB triplet, a hexadecimal color code, a color name, or
a short name. The default value of "auto" uses the same color as the Color property.
• An RGB triplet is a three-element row vector whose elements specify the intensities of the red,
green, and blue components of the color. The intensities must be in the range [0,1], for example,
[0.4 0.6 0.7].
7-540
fimplicit
• A hexadecimal color code is a string scalar or character vector that starts with a hash symbol (#)
followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case
sensitive. Therefore, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are
equivalent.
Alternatively, you can specify some common colors by name. This table lists the named color options,
the equivalent RGB triplets, and hexadecimal color codes.
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many
types of plots.
Marker fill color, specified as 'auto', an RGB triplet, a hexadecimal color code, a color name, or a
short name. The 'auto' value uses the same color as the MarkerEdgeColor property.
• An RGB triplet is a three-element row vector whose elements specify the intensities of the red,
green, and blue components of the color. The intensities must be in the range [0,1], for example,
[0.4 0.6 0.7].
• A hexadecimal color code is a string scalar or character vector that starts with a hash symbol (#)
followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case
7-541
7 Functions
sensitive. Therefore, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are
equivalent.
Alternatively, you can specify some common colors by name. This table lists the named color options,
the equivalent RGB triplets, and hexadecimal color codes.
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many
types of plots.
Marker size, specified as a positive value in points, where 1 point = 1/72 of an inch.
Output Arguments
fi — One or more implicit function line objects
scalar | vector
7-542
fimplicit
One or more implicit function line objects, returned as a scalar or a vector. You can use these objects
to query and modify properties of a specific line. For a list of properties, see Implicit Function Line.
Algorithms
fimplicit assigns the symbolic variables in f to the x-axis, then the y-axis, and symvar determines
the order of the variables to be assigned. Therefore, variable and axis names might not correspond.
To force fimplicit to assign x or y to its corresponding axis, create the symbolic function to plot,
then pass the symbolic function to fimplicit.
For example, the following code plots the roots of the implicit function f(x,y) = sin(y) in two ways. The
first way forces the waves to oscillate with respect to the y-axis. In other words, the first plot assigns
the y variable to the corresponding y-axis. The second plot assigns y to the x-axis because it is the
first (and only) variable in the symbolic function.
syms x y;
f(x,y) = sin(y);
intvl = [-6 6]*pi;
figure;
subplot(2,1,1)
fimplicit(f,intvl);
subplot(2,1,2)
fimplicit(f(x,y),intvl); % Or fimplicit(sin(y) == 0,intvl);
7-543
7 Functions
Version History
Introduced in R2016b
See Also
Functions
fcontour | fimplicit3 | fmesh | fplot | fplot3 | fsurf
Properties
Implicit Function Line
Topics
“Create Plots of Symbolic Expressions” on page 4-2
7-544
fimplicit3
fimplicit3
Plot 3-D implicit equation or function
Syntax
fimplicit3(f)
fimplicit3(f,[min max])
fimplicit3(f,[xmin xmax ymin ymax zmin zmax])
Description
fimplicit3(f) plots the 3-D implicit equation or function f(x,y,z) over the default interval [-5
5] for x, y, and z.
fimplicit3(f,[min max]) plots f(x,y,z) over the interval [min max] for x, y, and z.
fimplicit3(f,[xmin xmax ymin ymax zmin zmax]) plots f(x,y,z) over the interval [xmin
xmax] for x, [ymin ymax] for y, and [zmin zmax] for z. The fimplicit3 function uses symvar
to order the variables and assign intervals.
fimplicit3( ___ ,LineSpec) uses LineSpec to set the line style, marker symbol, and face color.
fimplicit3( ___ ,Name,Value) specifies line properties using one or more Name,Value pair
arguments. Use this option with any of the input argument combinations in the previous syntaxes.
fimplicit3(ax, ___ ) plots into the axes with the object ax instead of the current axes object gca.
fi = fimplicit3( ___ ) returns an implicit function surface object. Use the object to query and
modify properties of a specific surface. For details, see Implicit Function Surface.
Examples
Plot the hyperboloid x2 + y2 − z2 = 0 by using fimplicit3. The fimplicit3 function plots over the
default interval of [ − 5, 5] for x, y, and z.
syms x y z
fimplicit3(x^2 + y^2 - z^2)
7-545
7 Functions
Plot the hyperboloid specified by the function f (x, y, z) = x2 + y2 − z2. The fimplicit3 function plots
over the default interval of [ − 5, 5] for x, y, and z.
syms f(x,y,z)
f(x,y,z) = x^2 + y^2 - z^2;
fimplicit3(f)
7-546
fimplicit3
Specify the plotting interval by specifying the second argument to fimplicit3. Plot the upper half
of the hyperboloid x2 + y2 − z2 = 0 by specifying the interval 0 < z < 5. For x and y, use the default
interval [ − 5, 5].
syms x y z
f = x^2 + y^2 - z^2;
interval = [-5 5 -5 5 0 5];
fimplicit3(f, interval)
7-547
7 Functions
Plot the implicit equation xsin(y) + zcos(x) = 0 over the interval ( − 2π, 2π) for all axes.
Create the x-axis ticks by spanning the x-axis limits at intervals of pi/2. Convert the axis limits to
precise multiples of pi/2 by using round and get the symbolic tick values in S. Display these ticks by
using the XTick property. Create x-axis labels by using arrayfun to apply texlabel to S. Display
these labels by using the XTickLabel property. Repeat these steps for the y-axis.
syms x y z
eqn = x*sin(y) + z*cos(x);
fimplicit3(eqn,[-2*pi 2*pi])
title('xsin(y) + zcos(x) for -2\pi < x < 2\pi and -2\pi < y < 2\pi')
xlabel('x')
ylabel('y')
ax = gca;
S = sym(ax.XLim(1):pi/2:ax.XLim(2));
S = sym(round(vpa(S/pi*2))*pi/2);
ax.XTick = double(S);
ax.XTickLabel = arrayfun(@texlabel,S,'UniformOutput',false);
7-548
fimplicit3
S = sym(ax.YLim(1):pi/2:ax.YLim(2));
S = sym(round(vpa(S/pi*2))*pi/2);
ax.YTick = double(S);
ax.YTickLabel = arrayfun(@texlabel, S, 'UniformOutput', false);
Plot the implicit surface x2 + y2 − z2 = 0 with different line styles for different values of z. For
−5 < z < − 2, use a dashed line with green dot markers. For −2 < z < 2, use a LineWidth of 1 and a
green face color. For 2 < z < 5, turn off the lines by setting EdgeColor to none.
syms x y z
f = x^2 + y^2 - z^2;
fimplicit3(f,[-5 5 -5 5 -5 -2],'--.','MarkerEdgeColor','g')
hold on
fimplicit3(f,[-5 5 -5 5 -2 2],'LineWidth',1,'FaceColor','g')
fimplicit3(f,[-5 5 -5 5 2 5],'EdgeColor','none')
7-549
7 Functions
Plot the implicit surface 1/x2 − 1/y2 + 1/z2 = 0. Specify an output to make fimplicit3 return the
plot object.
syms x y z
f = 1/x^2 - 1/y^2 + 1/z^2;
fi = fimplicit3(f)
7-550
fimplicit3
fi =
ImplicitFunctionSurface with properties:
Show only the positive x-axis by setting the XRange property of fi to [0 5]. Remove the lines by
setting the EdgeColor property to 'none'. Visualize the hidden surfaces by making the plot
transparent by setting the FaceAlpha property to 0.8.
fi.XRange = [0 5];
fi.EdgeColor = 'none';
fi.FaceAlpha = 0.8;
7-551
7 Functions
Control the resolution of an implicit surface plot by using the 'MeshDensity' option. Increasing
'MeshDensity' can make smoother, more accurate plots while decreasing 'MeshDensity' can
increase plotting speed.
Divide a figure into two by using subplot. In the first subplot, plot the implicit surface sin(1/(xyz)).
The surface has large gaps. Fix this issue by increasing the 'MeshDensity' to 40 in the second
subplot. fimplicit3 fills the gaps showing that by increasing 'MeshDensity' you increased the
resolution of the plot.
syms x y z
f = sin(1/(x*y*z));
subplot(2,1,1)
fimplicit3(f)
title('Default MeshDensity = 35')
subplot(2,1,2)
fimplicit3(f,'MeshDensity',40)
title('Increased MeshDensity = 40')
7-552
fimplicit3
where
Define the values for a and R as 1 and 5, respectively. Plot the torus using fimplicit3.
syms x y z
a = 1;
R = 4;
f(x,y,z) = (x^2+y^2+z^2+R^2-a^2)^2 - 4*R^2*(x^2+y^2);
fimplicit3(f)
hold on
Apply rotation to the torus around the x-axis. Define the rotation matrix. Rotate the torus by 90
degrees or π/2 radians. Shift the center of the torus by 5 along the x-axis.
7-553
7 Functions
alpha = pi/2;
Rx = [1 0 0;
0 cos(alpha) sin(alpha);
0 -sin(alpha) cos(alpha)];
r = [x; y; z];
r_90 = Rx*r;
g = subs(f,[x,y,z],[r_90(1)-5,r_90(2),r_90(3)]);
Add a second plot of the rotated and translated torus to the existing graph.
fimplicit3(g)
axis([-5 10 -5 10 -5 5])
hold off
Input Arguments
f — 3-D implicit equation or function to plot
symbolic equation | symbolic expression | symbolic function
3-D implicit equation or function to plot, specified as a symbolic equation, expression, or function. If
an expression or function is specified, then fimplicit3 assumes the right-hand size to be 0.
Plotting interval for x-, y- and z- axes, specified as a vector of two numbers. The default is [-5 5].
7-554
fimplicit3
[xmin xmax ymin ymax zmin zmax] — Plotting interval for x-, y- and z- axes
[–5 5 –5 5 –5 5] (default) | vector of six numbers
Plotting interval for x-, y- and z- axes, specified as a vector of six numbers. The default is [-5 5 -5
5 -5 5].
ax — Axes object
axes object
Axes object. If you do not specify an axes object, then fimplicit3 uses the current axes.
Line style, marker, and color, specified as a string scalar or character vector containing symbols. The
symbols can appear in any order. You do not need to specify all three characteristics (line style,
marker, and color). For example, if you omit the line style and specify the marker, then the plot shows
only the marker and no line.
Example: "--or" is a red dashed line with circle markers.
"*" Asterisk
"." Point
"x" Cross
"square" Square
"diamond" Diamond
7-555
7 Functions
"pentagram" Pentagram
"hexagram" Hexagram
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: 'Marker','o','MarkerFaceColor','red'
The properties listed here are only a subset. For a complete list, see Implicit Function Surface.
Number of evaluation points per direction, specified as a number. The default is 35.
Example: 100
Line color, specified as 'interp', an RGB triplet, a hexadecimal color code, a color name, or a short
name. The default RGB triplet value of [0 0 0] corresponds to black. The 'interp' value colors
the edges based on the ZData values.
7-556
fimplicit3
• An RGB triplet is a three-element row vector whose elements specify the intensities of the red,
green, and blue components of the color. The intensities must be in the range [0,1], for example,
[0.4 0.6 0.7].
• A hexadecimal color code is a string scalar or character vector that starts with a hash symbol (#)
followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case
sensitive. Therefore, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are
equivalent.
Alternatively, you can specify some common colors by name. This table lists the named color options,
the equivalent RGB triplets, and hexadecimal color codes.
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many
types of plots.
7-557
7 Functions
Line width, specified as a positive value in points, where 1 point = 1/72 of an inch. If the line has
markers, then the line width also affects the marker edges.
The line width cannot be thinner than the width of a pixel. If you set the line width to a value that is
less than the width of a pixel on your system, the line displays as one pixel wide.
Marker symbol, specified as one of the values listed in this table. By default, the object does not
display markers. Specifying a marker symbol adds markers at each data point or vertex.
"*" Asterisk
"." Point
"x" Cross
"square" Square
"diamond" Diamond
"pentagram" Pentagram
7-558
fimplicit3
Marker outline color, specified as 'auto', an RGB triplet, a hexadecimal color code, a color name, or
a short name. The default value of 'auto' uses the same color as the EdgeColor property.
• An RGB triplet is a three-element row vector whose elements specify the intensities of the red,
green, and blue components of the color. The intensities must be in the range [0,1], for example,
[0.4 0.6 0.7].
• A hexadecimal color code is a string scalar or character vector that starts with a hash symbol (#)
followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case
sensitive. Therefore, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are
equivalent.
Alternatively, you can specify some common colors by name. This table lists the named color options,
the equivalent RGB triplets, and hexadecimal color codes.
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many
types of plots.
7-559
7 Functions
Marker fill color, specified as 'auto', an RGB triplet, a hexadecimal color code, a color name, or a
short name. The 'auto' value uses the same color as the MarkerEdgeColor property.
• An RGB triplet is a three-element row vector whose elements specify the intensities of the red,
green, and blue components of the color. The intensities must be in the range [0,1], for example,
[0.4 0.6 0.7].
• A hexadecimal color code is a string scalar or character vector that starts with a hash symbol (#)
followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case
sensitive. Therefore, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are
equivalent.
Alternatively, you can specify some common colors by name. This table lists the named color options,
the equivalent RGB triplets, and hexadecimal color codes.
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many
types of plots.
7-560
fimplicit3
Marker size, specified as a positive value in points, where 1 point = 1/72 of an inch.
Output Arguments
fi — One or more objects
scalar | vector
One or more objects, returned as a scalar or a vector. The object is an implicit function surface object.
You can use these objects to query and modify properties of a specific line. For details, see Implicit
Function Surface.
Algorithms
fimplicit3 assigns the symbolic variables in f to the x axis, the y axis, then the z axis, and symvar
determines the order of the variables to be assigned. Therefore, variable and axis names might not
correspond. To force fimplicit3 to assign x, y, or z to its corresponding axis, create the symbolic
function to plot, then pass the symbolic function to fimplicit3.
For example, the following code plots the roots of the implicit function f(x,y,z) = x + z in two ways.
The first way forces fimplicit3 to assign x and z to their corresponding axes. In the second way,
fimplicit3 defers to symvar to determine variable order and axis assignment: fimplicit3
assigns x and z to the x- and y-axes, respectively.
syms x y z;
f(x,y,z) = x + z;
figure;
subplot(2,1,1)
fimplicit3(f);
view(-38,71);
subplot(2,1,2)
fimplicit3(f(x,y,z)); % Or fimplicit3(x + z);
7-561
7 Functions
Version History
Introduced in R2016b
See Also
Functions
fcontour | fimplicit | fmesh | fplot | fplot3 | fsurf
Properties
Implicit Function Surface
Topics
“Create Plots of Symbolic Expressions” on page 4-2
7-562
findDecoupledBlocks
findDecoupledBlocks
Search for decoupled blocks in systems of equations
Syntax
[eqsBlocks,varsBlocks] = findDecoupledBlocks(eqs,vars)
Description
[eqsBlocks,varsBlocks] = findDecoupledBlocks(eqs,vars) identifies subsets (blocks) of
equations that can be used to define subsets of variables. The number of variables vars must
coincide with the number of equations eqs.
The ith block is the set of equations determining the variables in vars(varsBlocks{i}). The
variables in vars([varsBlocks{1},…,varsBlocks{i-1}]) are determined recursively by the
previous blocks of equations. After you solve the first block of equations for the first block of
variables, the second block of equations, given by eqs(eqsBlocks{2}), defines a decoupled subset
of equations containing only the subset of variables given by the second block of variables,
vars(varsBlock{2}), plus the variables from the first block (these variables are known at this
time). Thus, if a nontrivial block decomposition is possible, you can split the solution process for a
large system of equations involving many variables into several steps, where each step involves a
smaller subsystem.
Examples
Create the following system of four differential algebraic equations. Here, the symbolic function calls
x1(t), x2(t), x3(t), and x4(t) represent the state variables of the system. The system also
contains symbolic parameters c1, c2, c3, c4, and functions f(t,x,y) and g(t,x,y).
syms x1(t) x2(t) x3(t) x4(t)
syms c1 c2 c3 c4
syms f(t,x,y) g(t,x,y)
eqs = [c1*diff(x1(t),t)+c2*diff(x3(t),t)==c3*f(t,x1(t),x3(t));...
c2*diff(x1(t),t)+c1*diff(x3(t),t)==c4*g(t,x3(t),x4(t));...
x1(t)==g(t,x1(t),x3(t));...
x2(t)==f(t,x3(t),x4(t))];
vars = [x1(t),x2(t),x3(t),x4(t)];
7-563
7 Functions
[eqsBlocks,varsBlocks] = findDecoupledBlocks(eqs,vars)
eqs(eqsBlocks{1})
ans =
∂ ∂
c1 x t + c2 x t = c3 f t, x1 t , x3 t
∂t 1 ∂t 3
x1 t = g t, x1 t , x3 t
vars(varsBlocks{1})
ans = x1 t x3 t
After you solve this block for the variables x1(t), x3(t), you can solve the next block of equations.
This block consists of one equation.
eqs(eqsBlocks{2})
ans =
∂ ∂
c2 x t + c1 x t = c4 g t, x3 t , x4 t
∂t 1 ∂t 3
vars(varsBlocks{2})
ans = x4 t
After you solve the equation from block 2 for the variable x4(t), the remaining block of equations,
eqs(eqsBlocks{3}), defines the remaining variable, vars(varsBlocks{3}).
eqs(eqsBlocks{3})
ans = x2 t = f t, x3 t , x4 t
vars(varsBlocks{3})
ans = x2 t
Find the permutations that convert the system to a block lower triangular form.
eqsPerm = [eqsBlocks{:}]
eqsPerm = 1×4
1 3 2 4
varsPerm = [varsBlocks{:}]
7-564
findDecoupledBlocks
varsPerm = 1×4
1 3 4 2
eqs = eqs(eqsPerm)
eqs =
∂ ∂
c1 x t + c2 x t = c3 f t, x1 t , x3 t
∂t 1 ∂t 3
x1 t = g t, x1 t , x3 t
∂ ∂
c2 x t + c1 x t = c4 g t, x3 t , x4 t
∂t 1 ∂t 3
x2 t = f t, x3 t , x4 t
vars = vars(varsPerm)
vars = x1 t x3 t x4 t x2 t
Find the incidence matrix of the resulting system. The incidence matrix shows that the system of
permuted equations has three diagonal blocks of size 2-by-2, 1-by-1, and 1-by-1.
incidenceMatrix(eqs, vars)
ans = 4×4
1 1 0 0
1 1 0 0
1 1 1 0
0 1 1 1
Find blocks of equations in a linear algebraic system, and then solve the system by sequentially
solving each block of equations starting from the first one.
syms x1 x2 x3 x4 x5 x6 c1 c2 c3
vars = [x1,x2,x3,x4,x5,x6];
Use findDecoupledBlocks to convert the system to a lower triangular form. For this system,
findDecoupledBlocks identifies three blocks of equations and corresponding variables.
7-565
7 Functions
[eqsBlocks,varsBlocks] = findDecoupledBlocks(eqs,vars)
Identify the variables in the first block. This block consists of three equations in three variables.
vars(varsBlocks{1})
ans = x1 x3 x5
Solve the first block of equations for the first block of variables assigning the solutions to the
corresponding variables.
[x1,x3,x5] = solve(eqs(eqsBlocks{1}),vars(varsBlocks{1}))
x1 = 1
x3 = c2
x5 = 1
Identify the variables in the second block. This block consists of two equations in two variables.
vars(varsBlocks{2})
ans = x4 x6
Solve this block of equations assigning the solutions to the corresponding variables.
[x4,x6] = solve(eqs(eqsBlocks{2}),vars(varsBlocks{2}))
x4 =
x3 c2
− x1 − +2
3 3
x6 =
2 c2 2 x3
− +1
3 3
Use subs to evaluate the result for the already known values of variables x1, x3, and x5.
x4 = subs(x4)
x4 = 1
x6 = subs(x6)
x6 = 1
Identify the variables in the third block. This block consists of one equation in one variable.
vars(varsBlocks{3})
ans = x2
7-566
findDecoupledBlocks
x2 = c2 − x3 − x4 − x5 + 2
Use subs to evaluate the result for the already known values of all other variables of this system.
x2 = subs(x2)
x2 = 0
Alternatively, you can rewrite this example using the for-loop. This approach lets you use the
example for larger systems of equations.
syms x1 x2 x3 x4 x5 x6 c1 c2 c3
vars = [x1,x2,x3,x4,x5,x6];
[eqsBlocks,varsBlocks] = findDecoupledBlocks(eqs,vars);
vars_sol = vars;
for i = 1:numel(eqsBlocks)
sol = solve(eqs(eqsBlocks{i}),vars(varsBlocks{i}));
vars_sol_per_block = subs(vars(varsBlocks{i}),sol);
for k=1:i-1
vars_sol_per_block = subs(vars_sol_per_block,vars(varsBlocks{k}),...
vars_sol(varsBlocks{k}));
end
vars_sol(varsBlocks{i}) = vars_sol_per_block
end
vars_sol = 1 x2 c2 x4 1 x6
vars_sol = 1 x2 c2 1 1 1
vars_sol = 1 0 c2 1 1 1
Input Arguments
eqs — System of equations
vector of symbolic equations | vector of symbolic expressions
vars — Variables
vector of symbolic variables | vector of symbolic functions | vector of symbolic function calls
Variables, specified as a vector of symbolic variables, functions, or function calls, such as x(t).
7-567
7 Functions
Output Arguments
eqsBlocks — Indices defining blocks of equations
cell array
Indices defining blocks of equations, returned as a cell array. Each block of indices is a row vector of
double-precision integer numbers. The ith block of equations consists of the equations
eqs(eqsBlocks{i}) and involves only the variables in vars(varsBlocks{1:i}).
Indices defining blocks of variables, returned as a cell array. Each block of indices is a row vector of
double-precision integer numbers. The ith block of equations consists of the equations
eqs(eqsBlocks{i}) and involves only the variables in vars(varsBlocks{1:i}).
Tips
• The implemented algorithm requires that for each variable in vars there must be at least one
matching equation in eqs involving this variable. The same equation cannot also be matched to
another variable. If the system does not satisfy this condition, then findDecoupledBlocks
throws an error. In particular, findDecoupledBlocks requires that length(eqs) =
length(vars).
• Applying the permutations e = [eqsBlocks{:}] to the vector eqs and v = [varsBlocks{:}]
to the vector vars produces an incidence matrix incidenceMatrix(eqs(e), vars(v)) that
has a block lower triangular sparsity pattern.
Version History
Introduced in R2014b
See Also
daeFunction | decic | diag | incidenceMatrix | isLowIndexDAE | massMatrixForm |
odeFunction | reduceDAEIndex | reduceDAEToODE | reduceDifferentialOrder |
reduceRedundancies | tril | triu
7-568
findSymType
findSymType
Find symbolic subobjects of specific type
Syntax
X = findSymType(symObj,type)
X = findSymType(symObj,funType,vars)
Description
X = findSymType(symObj,type) returns a vector of symbolic subobjects of type type from the
symbolic object symObj. The input type must be a case-sensitive string scalar or character vector,
and it can include a logical expression.
• If symObj does not contain a symbolic subobject of type type, then findSymType returns an
empty scalar.
• If symObj contains several subexpressions of type type, then findSymType returns the largest
matching subexpression.
You can set the function type funType to 'symfunOf' or 'symfunDependingOn'. For example,
syms f(x); findSymType(f,'symfunOf',x) returns f(x).
Examples
Find and return specific symbolic numbers and constants in a symbolic expression.
expr =
π
+ 3.1415926535897932384626433832795
2
X = findSymType(expr,'integer')
X = 12
X = findSymType(expr,'integer | real')
X =
7-569
7 Functions
1
3.1415926535897932384626433832795
2
X = findSymType(expr,'vpareal')
X = 3.1415926535897932384626433832795
X = findSymType(expr,'complex')
X =
The findSymType function returns an empty scalar since the expression expr does not contain any
complex numbers.
X = findSymType(expr,'constant')
X =
π
+ 3.1415926535897932384626433832795
2
When there are several subexpressions of type 'constant', findSymType returns the largest
matching subexpression.
syms y(t) k
eq = diff(y) + k*y == sin(y)
eq(t) =
∂
y t + k y t = sin y t
∂t
X = findSymType(eq,'variable')
X = kt
X = findSymType(eq,'symfun')
X = yt
7-570
findSymType
X = findSymType(eq,'diff')
X =
∂
yt
∂t
Find and return symbolic functions with specific variable dependencies in an expression.
expr = x + f xn + g x + y x, t
X = findSymType(expr,'symfun')
X = f xn g x y x, t
Find symbolic functions that depend on the exact sequence of variables [x t] using 'symfunOf'.
X = findSymType(expr,'symfunOf',[x t])
X = y x, t
Find symbolic functions that have a dependency on the variable x using 'symfunDependingOn'.
X = findSymType(expr,'symfunDependingOn',x)
X = g x y x, t
Input Arguments
symObj — Symbolic objects
symbolic expressions | symbolic functions | symbolic variables | symbolic numbers | symbolic units
Symbolic objects, specified as symbolic expressions, symbolic functions, symbolic variables, symbolic
numbers, or symbolic units.
Symbolic types, specified as a case-sensitive scalar string or character vector. The input type can
contain a logical expression. The value options follow.
7-571
7 Functions
7-572
findSymType
If symObj contains several subexpressions of type type, then findSymType returns the largest
matching subexpression (topmost matching node in a tree data structure).
• 'symfunOf' finds and returns the unassigned symbolic functions that depend on the exact
sequence of variables specified by the array vars. For example, syms f(x,y);
findSymType(f,'symfunOf',[x y]) returns f(x,y).
• 'symfunDependingOn' finds and returns the unassigned symbolic functions that have a
dependency on the variables specified by the array vars. For example, syms f(x,y);
findSymType(f,'symfunDependingOn',x) returns f(x,y).
Version History
Introduced in R2019a
See Also
symFunType | hasSymType | symType | sym | syms | isSymType | mapSymType
7-573
7 Functions
findUnits
Find units in input
Syntax
U = findUnits(expr)
Description
U = findUnits(expr) returns a row vector of units in the symbolic expression expr.
Examples
u = symunit;
syms x
units = findUnits(x*u.m + 2*u.N)
units = N m
Find the units in an array of equations or expressions by using findUnits. The findUnits function
concatenates all units found in the input to return a row vector of units. findUnits returns only
base units.
u = symunit;
array = [2*u.m + 3*u.K, 1*u.N == 1*u.kg/(u.m*u.s^2)];
units = findUnits(array)
units = K N kg m s
Input Arguments
expr — Input
symbolic number | symbolic variable | symbolic vector | symbolic matrix | symbolic multidimensional
array | symbolic function | symbolic expression
Input, specified as a symbolic number, variable, vector, matrix, multidimensional array, function, or a
symbolic expression.
7-574
findUnits
Version History
Introduced in R2017a
See Also
checkUnits | isUnit | newUnit | separateUnits | symunit | str2symunit | symunit2str |
unitConversionFactor
Topics
“Units of Measurement Tutorial” on page 2-47
“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)
7-575
7 Functions
finverse
Functional inverse
Syntax
g = finverse(f)
g = finverse(f,var)
Description
g = finverse(f) returns the inverse of function f, such that f(g(x)) = x. If f contains more
than one variable, use the next syntax to specify the independent variable.
g = finverse(f,var) uses the symbolic variable var as the independent variable, such that
f(g(var)) = var.
Examples
syms x
f(x) = 1/tan(x);
g = finverse(f)
g(x) =
atan(1/x)
Compute functional inverse for this exponential function by specifying the independent variable.
syms u v
finverse(exp(u-2*v), u)
ans =
2*v + log(u)
Input Arguments
f — Input
symbolic expression | symbolic function
7-576
finverse
Limitations
• finverse does not issue a warning when the functional inverse is not unique.
Version History
Introduced before R2006a
See Also
compose | syms
7-577
7 Functions
fmesh
Plot 3-D mesh
Syntax
fmesh(f)
fmesh(f,[min max])
fmesh(f,[xmin xmax ymin ymax])
fmesh(funx,funy,funz)
fmesh(funx,funy,funz,[uvmin uvmax])
fmesh(funx,funy,funz,[umin umax vmin vmax])
Description
fmesh(f) creates a mesh plot of the symbolic expression f(x,y) over the default interval [-5 5]
for x and y.
fmesh(f,[min max]) plots f(x,y) over the interval [min max] for x and y.
fmesh(f,[xmin xmax ymin ymax]) plots f(x,y) over the interval [xmin xmax] for x and
[ymin ymax] for y. The fmesh function uses symvar to order the variables and assign intervals.
fmesh( ___ ,LineSpec) uses the LineSpec to set the line style, marker symbol, and plot color.
fmesh( ___ ,Name,Value) specifies surface properties using one or more Name,Value pair
arguments. Use this option with any of the input argument combinations in the previous syntaxes.
fmesh(ax, ___ ) plots into the axes with the object ax instead of the current axes object gca.
obj = fmesh( ___ ) returns a function surface object or a parameterized function surface object.
Use the object to query and modify properties of a specific mesh.
Examples
7-578
fmesh
Plot a mesh of the input sin(x) + cos(y) over the default range −5 < x < 5 and −5 < y < 5.
syms x y
fmesh(sin(x)+cos(y))
Plot a 3-D mesh of the real part of tan−1(x + iy) over the default range −5 < x < 5 and −5 < y < 5.
syms f(x,y)
f(x,y) = real(atan(x + i*y));
fmesh(f)
7-579
7 Functions
Plot sin(x) + cos(y) over −π < x < π and −5 < y < 5 by specifying the plotting interval as the second
argument of fmesh.
syms x y
f = sin(x) + cos(y);
fmesh(f, [-pi pi -5 5])
7-580
fmesh
x = rcos(s)sin(t)
y = rsin(s)sin(t)
z = rcos(t)
where r = 8 + sin(7s + 5t)
for 0 < s < 2π and 0 < t < π. Make the aspect ratio of the axes equal using axis equal. See the
entire mesh by making the mesh partially transparent using alpha.
syms s t
r = 8 + sin(7*s + 5*t);
x = r*cos(s)*sin(t);
y = r*sin(s)*sin(t);
z = r*cos(t);
fmesh(x, y, z, [0 2*pi 0 pi], 'Linewidth', 2)
axis equal
alpha(0.8)
7-581
7 Functions
Input Arguments
f — 3-D expression or function to be plotted
symbolic expression | symbolic function
Plotting interval for x- and y-axes, specified as a vector of two numbers. The default is [-5 5].
Plotting interval for x- and y-axes, specified as a vector of four numbers. The default is [-5 5 -5 5].
7-582
fmesh
Plotting interval for u and v axes, specified as a vector of two numbers. The default is [-5 5].
Plotting interval for u and v, specified as a vector of four numbers. The default is [-5 5 -5 5].
ax — Axes object
axes object
Axes object. If you do not specify an axes object, then fmesh uses the current axes.
Line style, marker, and color, specified as a string scalar or character vector containing symbols. The
symbols can appear in any order. You do not need to specify all three characteristics (line style,
marker, and color). For example, if you omit the line style and specify the marker, then the plot shows
only the marker and no line.
Example: "--or" is a red dashed line with circle markers.
"*" Asterisk
"." Point
"x" Cross
"square" Square
"diamond" Diamond
7-583
7 Functions
"pentagram" Pentagram
"hexagram" Hexagram
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: 'Marker','o','MarkerFaceColor','red'
Number of evaluation points per direction, specified as a number. The default is 35. Because fmesh
objects use adaptive evaluation, the actual number of evaluation points is greater.
Example: 100
Display contour plot under plot, specified as 'on' or 'off', or as numeric or logical 1 (true) or 0
(false). A value of 'on' is equivalent to true, and 'off' is equivalent to false. Thus, you can use
the value of this property as a logical value. The value is stored as an on/off logical value of type
matlab.lang.OnOffSwitchState.
7-584
fmesh
Line color, specified as 'interp', an RGB triplet, a hexadecimal color code, a color name, or a short
name. The default value of 'interp' colors the edges based on the ZData property values.
• An RGB triplet is a three-element row vector whose elements specify the intensities of the red,
green, and blue components of the color. The intensities must be in the range [0,1], for example,
[0.4 0.6 0.7].
• A hexadecimal color code is a string scalar or character vector that starts with a hash symbol (#)
followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case
sensitive. Therefore, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are
equivalent.
Alternatively, you can specify some common colors by name. This table lists the named color options,
the equivalent RGB triplets, and hexadecimal color codes.
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many
types of plots.
Example: 'blue'
Example: [0 0 1]
7-585
7 Functions
Example: '#0000FF'
Line width, specified as a positive value in points, where 1 point = 1/72 of an inch. If the line has
markers, then the line width also affects the marker edges.
The line width cannot be thinner than the width of a pixel. If you set the line width to a value that is
less than the width of a pixel on your system, the line displays as one pixel wide.
Marker symbol, specified as one of the values listed in this table. By default, the object does not
display markers. Specifying a marker symbol adds markers at each data point or vertex.
"*" Asterisk
"." Point
"x" Cross
"square" Square
"diamond" Diamond
7-586
fmesh
"pentagram" Pentagram
"hexagram" Hexagram
Marker outline color, specified as 'auto', an RGB triplet, a hexadecimal color code, a color name, or
a short name. The default value of 'auto' uses the same color as the EdgeColor property.
• An RGB triplet is a three-element row vector whose elements specify the intensities of the red,
green, and blue components of the color. The intensities must be in the range [0,1], for example,
[0.4 0.6 0.7].
• A hexadecimal color code is a string scalar or character vector that starts with a hash symbol (#)
followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case
sensitive. Therefore, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are
equivalent.
Alternatively, you can specify some common colors by name. This table lists the named color options,
the equivalent RGB triplets, and hexadecimal color codes.
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many
types of plots.
7-587
7 Functions
Marker fill color, specified as 'auto', an RGB triplet, a hexadecimal color code, a color name, or a
short name. The 'auto' value uses the same color as the MarkerEdgeColor property.
• An RGB triplet is a three-element row vector whose elements specify the intensities of the red,
green, and blue components of the color. The intensities must be in the range [0,1], for example,
[0.4 0.6 0.7].
• A hexadecimal color code is a string scalar or character vector that starts with a hash symbol (#)
followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case
sensitive. Therefore, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are
equivalent.
Alternatively, you can specify some common colors by name. This table lists the named color options,
the equivalent RGB triplets, and hexadecimal color codes.
7-588
fmesh
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many
types of plots.
Marker size, specified as a positive value in points, where 1 point = 1/72 of an inch.
Output Arguments
obj — One or more objects
scalar | vector
One or more objects, returned as a scalar or a vector. The object is either a function surface object or
parameterized mesh object, depending on the type of plot. You can use these objects to query and
modify properties of a specific line. For details, see Function Surface and Parameterized Function
Surface.
Tips
• For additional examples, follow the fsurf page because fmesh and fsurf share the same syntax.
All examples on the fsurf page apply to fmesh.
Algorithms
fmesh assigns the symbolic variables in f to the x-axis, then the y-axis, and symvar determines the
order of the variables to be assigned. Therefore, variable and axis names might not correspond. To
force fmesh to assign x or y to its corresponding axis, create the symbolic function to plot, then pass
the symbolic function to fmesh.
For example, the following code plots the mesh of f(x,y) = sin(y) in two ways. The first way forces the
waves to oscillate with respect to the y-axis. In other words, the first plot assigns the y variable to the
corresponding y-axis. The second plot assigns y to the x-axis because it is the first (and only) variable
in the symbolic function.
7-589
7 Functions
syms x y;
f(x,y) = sin(y);
figure;
subplot(2,1,1)
fmesh(f);
subplot(2,1,2)
fmesh(f(x,y)); % Or fmesh(sin(y));
Version History
Introduced in R2016a
See Also
Functions
fcontour | fimplicit | fimplicit3 | fplot | fplot3 | fsurf
Properties
Function Surface | Parameterized Function Surface
Topics
“Create Plots of Symbolic Expressions” on page 4-2
7-590
fold
fold
Combine (fold) vector using function
Syntax
fold(fun,v)
fold(fun,v,defaultVal)
Description
fold(fun,v) folds v by using fun. That is, fold calls fun on the first two elements of v, and then
repeatedly calls fun on the result and the next element till the last element is combined.
Programmatically, the fold operation is fold(fun,v) = fun(fold(fun,v(1:end-1)),v(end)).
Examples
Fold Vector Using Function
Fold a vector of symbolic variables using the power function. The output shows how fold combines
elements of the vector from left to right by using the specified function.
syms a b c d e
fold(@power, [a b c d e])
ans =
(((a^b)^c)^d)^e
Assume the variable x belongs to the set of values 1, 2, ..., 10 by applying or to the conditions x ==
1, ..., x == 10 using fold. Check that the assumption is set by using assumptions.
syms x
cond = fold(@or, x == 1:10);
assume(cond)
assumptions
ans =
x == 1 | x == 2 | x == 3 | x == 4 | x == 5 |...
x == 6 | x == 7 | x == 8 | x == 9 | x == 10
Specify the default value of fold when the input is empty by specifying the third argument. If the
third argument is not specified and the input is empty, then fold throws an error.
When creating a function to sum a vector, specify a default value of 0, such that the function returns
0 when the vector is empty.
7-591
7 Functions
ans =
0
Input Arguments
fun — Function used to fold vector
function handle
v — Vector to fold
vector | symbolic vector | cell vector
Vector to fold, specified as a vector, symbolic vector, or cell vector. If an element of v is a symbolic
function, then the formula of the symbolic function is used by calling formula.
Default value of fold operation, specified as a number, vector, matrix, or multidimensional array, or a
symbolic number, variable, vector, matrix, multidimensional array, function, or expression.
Version History
Introduced in R2016b
See Also
prod | sum
7-592
formula
formula
Return body of symbolic function or matrix function
Syntax
formula(f)
Description
formula(f) returns the body, or definition, of the symbolic function or matrix function f.
Examples
syms x y
f(x,y) = x + y;
formula(f)
ans = x + y
If the symbolic function does not have a definition, formula returns the symbolic function.
syms g(x,y)
formula(g)
ans = g x, y
syms A 2 matrix
syms f(A) 2 matrix keepargs
f(A) = A*A - 3*A + 2*eye(2);
formula(f)
ans = 2 I2 − 3 A + A2
If the symbolic matrix function does not have a definition, formula returns the symbolic matrix
function.
ans = g A
7-593
7 Functions
Input Arguments
f — Input function
symbolic function | symbolic matrix function
Version History
Introduced in R2012a
The formula function accepts an input argument of type symfunmatrix. For an example, see
“Return Body of Symbolic Matrix Function” on page 7-593.
See Also
argnames | syms | symvar | symfun | symfunmatrix
7-594
fortran
fortran
Fortran representation of symbolic expression
Syntax
fortran(f)
fortran(f,Name,Value)
Description
fortran(f) returns Fortran code for the symbolic expression f.
Examples
syms x
f = log(1+x);
fortran(f)
ans =
' t0 = log(x+1.0D0)'
H = sym(hilb(3));
fortran(H)
ans =
' H(1,1) = 1.0D0
H(1,2) = 1.0D0/2.0D0
H(1,3) = 1.0D0/3.0D0
H(2,1) = 1.0D0/2.0D0
H(2,2) = 1.0D0/3.0D0
H(2,3) = 1.0D0/4.0D0
H(3,1) = 1.0D0/3.0D0
H(3,2) = 1.0D0/4.0D0
H(3,3) = 1.0D0/5.0D0'
Write generated Fortran code to a file by specifying the File option. When writing to a file, fortran
optimizes the code using intermediate variables named t0, t1, .… Include comments in the file by
using the Comments option.
7-595
7 Functions
syms x
f = diff(tan(x));
fortran(f,'File','fortrantest')
t0 = tan(x)**2+1.0D0
Include the comment Version: 1.1. Comment lines must be shorter than 71 characters to conform
with Fortran 77.
fortran(f,'File','fortrantest','Comments','Version: 1.1')
*Version: 1.1
t0 = tan(x)**2+1.0D0
Input Arguments
f — Symbolic input
symbolic expression
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: fortran(x^2,'File','fortrancode','Comments','V1.2')
File to write to, specified as a character vector or string. When writing to a file, fortran optimizes
the code using intermediate variables named t0, t1, ....
Comments to include in the file header, specified as a character vector, cell array of character
vectors, or string vector. Comment lines must be shorter than 71 characters to conform with Fortran
77.
Tips
• MATLAB is left-associative while Fortran is right-associative. If ambiguity exists in an expression,
the fortran function must follow MATLAB to create an equivalent representation. For example,
fortran represents a^b^c in MATLAB as (a**b)**c in Fortran.
Version History
Introduced before R2006a
7-596
fortran
See Also
ccode | latex | matlabFunction
7-597
7 Functions
fourier
Fourier transform
Syntax
fourier(f)
fourier(f,transVar)
fourier(f,var,transVar)
Description
fourier(f) returns the “Fourier Transform” on page 7-602 of f. By default, the function symvar
determines the independent variable, and w is the transformation variable.
fourier(f,var,transVar) uses the independent variable var and the transformation variable
transVar instead of symvar and w, respectively.
Examples
Fourier Transform of Common Inputs
Compute the Fourier transform of common inputs. By default, the transform is in terms of w.
f_FT =
1
Absolute value f = a*abs(t);
f_FT = fourier(f)
f_FT =
-(2*a)/w^2
Step (Heaviside) f = heaviside(t);
f_FT = fourier(f)
f_FT =
pi*dirac(w) - 1i/w
7-598
fourier
f_FT =
pi*dirac(1, w)*2i
Cosine f = a*cos(b*t);
f_FT = fourier(f)
f_FT =
pi*a*(dirac(b + w) + dirac(b - w))
Sine f = a*sin(b*t);
f_FT = fourier(f)
f_FT =
pi*a*(dirac(b + w) - dirac(b - w))*1i
Sign f = sign(t);
f_FT = fourier(f)
f_FT =
-2i/w
Triangle syms c
f = triangularPulse(a,b,c,t);
f_FT = fourier(f)
f_FT =
-(a*exp(-b*w*1i) - b*exp(-a*w*1i) - a*exp(-c*w*1i) + ...
c*exp(-a*w*1i) + b*exp(-c*w*1i) - c*exp(-b*w*1i))/ ...
(w^2*(a - b)*(b - c))
Right-sided exponential Also calculate transform with condition a > 0. Clear assumptions.
f = exp(-t*abs(a))*heaviside(t);
f_FT = fourier(f)
assume(a > 0)
f_FT_condition = fourier(f)
assume(a,'clear')
f_FT =
1/(abs(a) + w*1i) - (sign(abs(a))/2 - 1/2)*fourier(exp(-t*abs(a)),t,w)
f_FT_condition =
1/(a + w*1i)
assume(a > 0)
f = exp(-a*t^2);
f_FT = fourier(f)
assume(a,'clear')
f_FT =
(pi^(1/2)*exp(-w^2/(4*a)))/a^(1/2)
7-599
7 Functions
assume([b c],'real')
f = a*exp(-(t-b)^2/(2*c^2));
f_FT = fourier(f)
f_FT_simplify = simplify(f_FT)
assume([b c],'clear')
f_FT =
(a*pi^(1/2)*exp(- (c^2*(w + (b*1i)/c^2)^2)/2 - b^2/(2*c^2)))/ ...
(1/(2*c^2))^(1/2)
f_FT_simplify =
2^(1/2)*a*pi^(1/2)*exp(-(w*(w*c^2 + b*2i))/2)*abs(c)
syms x
f = besselj(1,x);
f_FT = fourier(f);
f_FT = simplify(f_FT)
f_FT =
(2*w*(heaviside(w - 1)*1i - heaviside(w + 1)*1i))/(1 - w^2)^(1/2)
Compute the Fourier transform of exp(-t^2-x^2). By default, symvar determines the independent
variable, and w is the transformation variable. Here, symvar chooses x.
syms t x
f = exp(-t^2-x^2);
fourier(f)
ans =
pi^(1/2)*exp(- t^2 - w^2/4)
Specify the transformation variable as y. If you specify only one variable, that variable is the
transformation variable. symvar still determines the independent variable.
syms y
fourier(f,y)
ans =
pi^(1/2)*exp(- t^2 - y^2/4)
Specify both the independent and transformation variables as t and y in the second and third
arguments, respectively.
fourier(f,t,y)
ans =
pi^(1/2)*exp(- x^2 - y^2/4)
Compute the following Fourier transforms. The results are in terms of the Dirac and Heaviside
functions.
7-600
fourier
syms t w
fourier(t^3, t, w)
ans =
-pi*dirac(3, w)*2i
syms t0
fourier(heaviside(t - t0),t,w)
ans =
exp(-t0*w*1i)*(pi*dirac(w) - 1i/w)
Compute the Fourier transform of f using the default values of the Fourier parameters c = 1, s =
-1. For details, see “Fourier Transform” on page 7-602.
syms t w
f = t*exp(-t^2);
fourier(f,t,w)
ans =
-(w*pi^(1/2)*exp(-w^2/4)*1i)/2
Change the Fourier parameters to c = 1, s = 1 by using sympref, and compute the transform
again. The result changes.
sympref('FourierParameters',[1 1]);
fourier(f,t,w)
ans =
(w*pi^(1/2)*exp(-w^2/4)*1i)/2
ans =
(w*exp(-w^2/4)*1i)/(4*pi^(1/2))
Preferences set by sympref persist through your current and future MATLAB sessions. Restore the
default values of c and s by setting FourierParameters to 'default'.
sympref('FourierParameters','default');
Find the Fourier transform of the matrix M. Specify the independent and transformation variables for
each matrix entry by using matrices of the same size. When the arguments are nonscalars, fourier
acts on them element-wise.
syms a b c d w x y z
M = [exp(x) 1; sin(y) i*z];
vars = [w x; y z];
transVars = [a b; c d];
fourier(M,vars,transVars)
7-601
7 Functions
ans =
[ 2*pi*exp(x)*dirac(a), 2*pi*dirac(b)]
[ -pi*(dirac(c - 1) - dirac(c + 1))*1i, -2*pi*dirac(1, d)]
If fourier is called with both scalar and nonscalar arguments, then it expands the scalars to match
the nonscalars by using scalar expansion. Nonscalar arguments must be the same size.
fourier(x,vars,transVars)
ans =
[ 2*pi*x*dirac(a), pi*dirac(1, b)*2i]
[ 2*pi*x*dirac(c), 2*pi*x*dirac(d)]
syms f(t) w
F = fourier(f,t,w)
F =
fourier(f(t), t, w)
ifourier(F,w,t)
ans =
f(t)
Input Arguments
f — Input
symbolic expression | symbolic function | symbolic vector | symbolic matrix
Independent variable, specified as a symbolic variable. This variable is often called the "time
variable" or the "space variable." If you do not specify the variable, then fourier uses the function
symvar to determine the independent variable.
Transformation variable, specified as a symbolic variable, expression, vector, or matrix. This variable
is often called the "frequency variable." By default, fourier uses w. If w is the independent variable
of f, then fourier uses v.
More About
Fourier Transform
The Fourier transform of the expression f = f(x) with respect to the variable x at the point w is
7-602
fourier
∞
F w =c ∫f xe
−∞
iswxdx .
c and s are parameters of the Fourier transform. The fourier function uses c = 1, s = –1.
Tips
• If any argument is an array, then fourier acts element-wise on all elements of the array.
• If the first argument contains a symbolic function, then the second argument must be a scalar.
• To compute the inverse Fourier transform, use ifourier.
• fourier does not transform piecewise. Instead, try to rewrite piecewise by using the
functions heaviside, rectangularPulse, or triangularPulse.
Version History
Introduced before R2006a
References
[1] Oberhettinger F., "Tables of Fourier Transforms and Fourier Transforms of Distributions."
Springer, 1990.
See Also
ifourier | ilaplace | iztrans | laplace | sympref | ztrans
Topics
“Fourier and Inverse Fourier Transforms” on page 3-184
External Websites
Fourier Analysis (MathWorks Teaching Resources)
7-603
7 Functions
fplot
Plot symbolic expression or function
Syntax
fplot(f)
fplot(f,[xmin xmax])
fplot(xt,yt)
fplot(xt,yt,[tmin tmax])
Description
fplot(f) plots symbolic input f over the default interval [-5 5].
fplot(xt,yt) plots xt = x(t) and yt = y(t) over the default range of t, which is [–5 5].
fplot(xt,yt,[tmin tmax]) plots xt = x(t) and yt = y(t) over the specified range [tmin
tmax].
fplot( ___ ,LineSpec) uses LineSpec to set the line style, marker symbol, and line color.
fplot( ___ ,Name,Value) specifies line properties using one or more Name,Value pair arguments.
Use this option with any of the input argument combinations in the previous syntaxes. Name,Value
pair settings apply to all the lines plotted. To set options for individual lines, use the objects returned
by fplot.
fplot(ax, ___ ) plots into the axes specified by ax instead of the current axes gca.
fp = fplot( ___ ) returns a function line object or parameterized line object, depending on the
type of plot. Use the object to query and modify properties of a specific line. For details, see Function
Line and Parameterized Function Line.
Examples
Plot tan(x) over the default range [-5 5]. fplot shows poles by default. For details, see the
ShowPoles argument in “Name-Value Arguments” on page 7-620.
syms x
fplot(tan(x))
7-604
fplot
Plot the symbolic function f(x) = cos(x) over the default range [-5 5].
syms f(x)
f(x) = cos(x);
fplot(f)
7-605
7 Functions
syms t
x = cos(3*t);
y = sin(2*t);
fplot(x,y)
7-606
fplot
Plot sin(x) over [-pi/2 pi/2] by specifying the plotting interval as the second input to fplot.
syms x
fplot(sin(x),[-pi/2 pi/2])
7-607
7 Functions
You can plot multiple lines either by passing the inputs as a vector or by using hold on to
successively plot on the same figure. If you specify LineSpec and Name-Value arguments, they apply
to all lines. To set options for individual plots, use the function handles returned by fplot.
Divide a figure into two subplots using subplot. On the first subplot, plot sin(x) and cos(x) using
vector input. On the second subplot, plot sin(x) and cos(x) using hold on.
syms x
subplot(2,1,1)
fplot([sin(x) cos(x)])
title('Multiple Lines Using Vector Inputs')
subplot(2,1,2)
fplot(sin(x))
hold on
fplot(cos(x))
title('Multiple Lines Using hold on Command')
hold off
7-608
fplot
Plot three sine curves with a phase shift between each line. For the first line, use a linewidth of 2. For
the second, specify a dashed red line style with circle markers. For the third, specify a cyan, dash-dot
line style with asterisk markers. Display the legend.
syms x
fplot(sin(x+pi/5),'Linewidth',2)
hold on
fplot(sin(x-pi/5),'--or')
fplot(sin(x),'-.*c')
legend('show','Location','best')
hold off
7-609
7 Functions
Control the resolution of a plot by using the MeshDensity option. Increasing MeshDensity can
make smoother, more accurate plots, while decreasing it can increase plotting speed.
Divide a figure into two by using subplot. In the first subplot, plot a step function from x = 2.1 to
x = 2.15. The plot's resolution is too low to detect the step function. Fix this issue by increasing
MeshDensity to 39 in the second subplot. The plot now detects the step function and shows that by
increasing MeshDensity you increased the plot's resolution.
syms x
stepFn = rectangularPulse(2.1, 2.15, x);
subplot(2,1,1)
fplot(stepFn);
title('Default MeshDensity = 23')
subplot(2,1,2)
fplot(stepFn,'MeshDensity',39);
title('Increased MeshDensity = 39')
7-610
fplot
Plot sin(x). Specify an output to make fplot return the plot object.
syms x
h = fplot(sin(x))
7-611
7 Functions
h =
FunctionLine with properties:
Function: sin(x)
Color: [0 0.4470 0.7410]
LineStyle: '-'
LineWidth: 0.5000
Change the default blue line to a dashed red line by using dot notation to set properties. Similarly,
add 'x' markers and set the marker color to blue.
h.LineStyle = '--';
h.Color = 'r';
h.Marker = 'x';
h.MarkerEdgeColor = 'b';
7-612
fplot
Plot sin(x) over the interval [-2*pi 2*pi]. Add a title and axis labels. Create the x-axis ticks by
spanning the x-axis limits at intervals of pi/2. Display these ticks by using the XTick property.
Create x-axis labels by using arrayfun to apply texlabel to S. Display these labels by using the
XTickLabel property.
syms x
fplot(sin(x),[-2*pi 2*pi])
grid on
title('sin(x) from -2\pi to 2\pi')
xlabel('x')
ylabel('y')
ax = gca;
S = sym(ax.XLim(1):pi/2:ax.XLim(2));
ax.XTick = double(S);
ax.XTickLabel = arrayfun(@texlabel,S,'UniformOutput',false);
7-613
7 Functions
When you zoom into a plot, fplot reevaluates the plot automatically. The reevaluation when zooming
reveals more details at smaller scales.
Plot the curve for and . Zoom into the plot using zoom
and redraw the plot using drawnow. Because of reevaluation on zoom, fplot reveals more details.
Repeat the zoom 6 times to view smaller-scale details.
syms x
fplot(x^3*sin(1/x));
axis([-2 2 -0.02 0.02]);
for i=1:6
zoom(1.7)
pause(0.5)
end
7-614
fplot
Create an animation of a parametric curve where one of the parameters changes with time. The -
and -coordinates of the parametric curve are given by
Create two symbolic variables k and t. Use the variable k to parameterize the curve within the range
[-5 5] and use the variable t to animate the curve as the time proceeds from 0.1 to 3. Create a
stop-motion animation object of the time snapshots by using fanimator. Set the -axis and -axis to
be equal length.
syms k t
fanimator(@fplot,k*t*sin(k*t),k*t*cos(k*t),[-5 5],AnimationRange = [0.1 3])
axis equal
7-615
7 Functions
playAnimation
7-616
fplot
You can also save the animation as a GIF file by using writeAnimation.
writeAnimation("parametricCurve.gif")
7-617
7 Functions
Input Arguments
f — Expression or function to plot
symbolic expression | symbolic function
Plotting interval for x-coordinates, specified as a vector of two numbers. The default range is [-5 5].
However, if fplot detects a finite number of discontinuities in f, then fplot expands the range to
show them.
Parametric input for x-coordinates, specified as a symbolic expression or function. fplot uses
symvar to find the parameter.
Parametric input for y-axis, specified as a symbolic expression or function. fplot uses symvar to find
the parameter.
7-618
fplot
Range of values of parameter t, specified as a vector of two numbers. The default range is [-5 5].
ax — Axes object
axes object
Axes object. If you do not specify an axes object, then fplot uses the current axes gca.
Line style, marker, and color, specified as a string scalar or character vector containing symbols. The
symbols can appear in any order. You do not need to specify all three characteristics (line style,
marker, and color). For example, if you omit the line style and specify the marker, then the plot shows
only the marker and no line.
Example: "--or" is a red dashed line with circle markers.
"*" Asterisk
"." Point
"x" Cross
"square" Square
"diamond" Diamond
7-619
7 Functions
"pentagram" Pentagram
"hexagram" Hexagram
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
The function line properties listed here are only a subset. For a complete list, see Function Line.
Example: 'Marker','o','MarkerFaceColor','red'
Number of evaluation points, specified as a number. The default is 23. Because fplot uses adaptive
evaluation, the actual number of evaluation points is greater.
The asymptotes display as gray, dashed vertical lines. fplot displays asymptotes only with the
fplot(f) syntax or variants, and not with the fplot(xt,yt) syntax.
7-620
fplot
Line color, specified as an RGB triplet, a hexadecimal color code, a color name, or a short name.
• An RGB triplet is a three-element row vector whose elements specify the intensities of the red,
green, and blue components of the color. The intensities must be in the range [0,1], for example,
[0.4 0.6 0.7].
• A hexadecimal color code is a string scalar or character vector that starts with a hash symbol (#)
followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case
sensitive. Therefore, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are
equivalent.
Alternatively, you can specify some common colors by name. This table lists the named color options,
the equivalent RGB triplets, and hexadecimal color codes.
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many
types of plots.
Example: 'blue'
Example: [0 0 1]
Example: '#0000FF'
7-621
7 Functions
Line width, specified as a positive value in points, where 1 point = 1/72 of an inch. If the line has
markers, then the line width also affects the marker edges.
The line width cannot be thinner than the width of a pixel. If you set the line width to a value that is
less than the width of a pixel on your system, the line displays as one pixel wide.
Marker symbol, specified as one of the values listed in this table. By default, the object does not
display markers. Specifying a marker symbol adds markers at each data point or vertex.
"*" Asterisk
"." Point
"x" Cross
"square" Square
"diamond" Diamond
7-622
fplot
"pentagram" Pentagram
"hexagram" Hexagram
Marker outline color, specified as "auto", an RGB triplet, a hexadecimal color code, a color name, or
a short name. The default value of "auto" uses the same color as the Color property.
• An RGB triplet is a three-element row vector whose elements specify the intensities of the red,
green, and blue components of the color. The intensities must be in the range [0,1], for example,
[0.4 0.6 0.7].
• A hexadecimal color code is a string scalar or character vector that starts with a hash symbol (#)
followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case
sensitive. Therefore, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are
equivalent.
Alternatively, you can specify some common colors by name. This table lists the named color options,
the equivalent RGB triplets, and hexadecimal color codes.
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many
types of plots.
7-623
7 Functions
Marker fill color, specified as 'auto', an RGB triplet, a hexadecimal color code, a color name, or a
short name. The 'auto' value uses the same color as the MarkerEdgeColor property.
• An RGB triplet is a three-element row vector whose elements specify the intensities of the red,
green, and blue components of the color. The intensities must be in the range [0,1], for example,
[0.4 0.6 0.7].
• A hexadecimal color code is a string scalar or character vector that starts with a hash symbol (#)
followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case
sensitive. Therefore, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are
equivalent.
Alternatively, you can specify some common colors by name. This table lists the named color options,
the equivalent RGB triplets, and hexadecimal color codes.
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many
types of plots.
7-624
fplot
Marker size, specified as a positive value in points, where 1 point = 1/72 of an inch.
Output Arguments
fp — One or more function or parameterized line objects
scalar | vector
One or more function or parameterized function line objects, returned as a scalar or a vector.
• If you use the fplot(f) syntax or a variation of this syntax, then fplot returns function line
objects.
• If you use the fplot(xt,yt) syntax or a variation of this syntax, then fplot returns
parameterized line objects.
You can use these objects to query and modify properties of a specific line. For a list of properties, see
Function Line and Parameterized Function Line.
Tips
• If fplot detects a finite number of discontinuities in f, then fplot expands the range to show
them.
• If fplot is used with a function handle to a named or anonymous function (that is not a symbolic
expression or function), then the MATLAB fplot function is called. In this case, the function
handle must accept a vector input argument and return a vector output argument of the same
size. Use array operators instead of matrix operators for the best performance. For example,
use .* (times) instead of * (mtimes) in the code fplot(@(x) x.*sin(2*pi*x)).
Version History
Introduced in R2016a
7-625
7 Functions
See Also
Functions
fcontour | fimplicit | fimplicit3 | fmesh | fplot3 | fsurf
Properties
Function Line | Parameterized Function Line
Topics
“Create Plots of Symbolic Expressions” on page 4-2
7-626
fplot3
fplot3
Plot 3-D parametric curve
Syntax
fplot3(xt,yt,zt)
fplot3(xt,yt,zt,[tmin tmax])
Description
fplot3(xt,yt,zt) plots the parametric curve xt = x(t), yt = y(t), and zt = z(t) over the default
interval –5 < t < 5.
fplot3(xt,yt,zt,[tmin tmax]) plots xt = x(t), yt = y(t), and zt = z(t) over the interval tmin < t
< tmax.
fplot3( ___ ,LineSpec) uses LineSpec to set the line style, marker symbol, and line color.
fplot3( ___ ,Name,Value) specifies line properties using one or more Name,Value pair
arguments. Use this option with any of the input argument combinations in the previous syntaxes.
Name,Value pair settings apply to all the lines plotted. To set options for individual lines, use the
objects returned by fplot3.
fplot3(ax, ___ ) plots into the axes object ax instead of the current axes gca.
fp = fplot3( ___ ) returns a parameterized function line object. Use the object to query and
modify properties of a specific parameterized line. For details, see Parameterized Function Line.
Examples
x = sin(t)
y = cos(t)
z=t
syms t
xt = sin(t);
yt = cos(t);
7-627
7 Functions
zt = t;
fplot3(xt,yt,zt)
x = e−t/10sin(5t)
y = e−t/10cos(5t)
z=t
over the parameter range [-10 10] by specifying the fourth argument of fplot3.
syms t
xt = exp(-t/10).*sin(5*t);
yt = exp(-t/10).*cos(5*t);
zt = t;
fplot3(xt,yt,zt,[-10 10])
7-628
fplot3
Plot the same 3-D parametric curve three times over different intervals of the parameter. For the first
curve, use a linewidth of 2. For the second, specify a dashed red line style with circle markers. For
the third, specify a cyan, dash-dot line style with asterisk markers.
syms t
fplot3(sin(t), cos(t), t, [0 2*pi], 'LineWidth', 2)
hold on
fplot3(sin(t), cos(t), t, [2*pi 4*pi], '--or')
fplot3(sin(t), cos(t), t, [4*pi 6*pi], '-.*c')
7-629
7 Functions
x(t) = sin(t)
y(t) = cos(t)
z(t) = cos(2t) .
7-630
fplot3
Plot multiple lines either by passing the inputs as a vector or by using hold on to successively plot
on the same figure. If you specify LineSpec and Name-Value arguments, they apply to all lines. To
set options for individual lines, use the function handles returned by fplot3.
Divide a figure into two subplots using subplot. On the first subplot, plot two parameterized lines
using vector input. On the second subplot, plot the same lines using hold on.
syms t
subplot(2,1,1)
fplot3([t -t], t, [t -t])
title('Multiple Lines Using Vector Inputs')
subplot(2,1,2)
fplot3(t, t, t)
hold on
fplot3(-t, t, -t)
title('Multiple Lines Using Hold On Command')
hold off
7-631
7 Functions
x = e− | t | /10sin(5 | t | )
y = e− | t | /10cos(5 | t | )
z = t.
syms t
xt = exp(-abs(t)/10).*sin(5*abs(t));
yt = exp(-abs(t)/10).*cos(5*abs(t));
zt = t;
fp = fplot3(xt,yt,zt)
7-632
fplot3
fp =
ParameterizedFunctionLine with properties:
XFunction: exp(-abs(t)/10)*sin(5*abs(t))
YFunction: exp(-abs(t)/10)*cos(5*abs(t))
ZFunction: t
Color: [0 0.4470 0.7410]
LineStyle: '-'
LineWidth: 0.5000
Change the range of parameter values to [-10 10] and the line color to red by using the TRange
and Color properties of fp respectively.
7-633
7 Functions
For t values in the range −2π to 2π, plot the parametric line
x=t
y = t/2
z = sin(6t) .
Add a title and axis labels. Create the x-axis ticks by spanning the x-axis limits at intervals of pi/2.
Display these ticks by using the XTick property. Create x-axis labels by using arrayfun to apply
texlabel to S. Display these labels by using the XTickLabel property. Repeat these steps for the y-
axis.
7-634
fplot3
ax = gca;
S = sym(ax.XLim(1):pi/2:ax.XLim(2));
ax.XTick = double(S);
ax.XTickLabel = arrayfun(@texlabel, S, 'UniformOutput', false);
S = sym(ax.YLim(1):pi/2:ax.YLim(2));
ax.YTick = double(S);
ax.YTickLabel = arrayfun(@texlabel, S, 'UniformOutput', false);
Create an animation by changing the displayed expression using the XFunction, YFunction, and
ZFunction properties, and then use drawnow to update the plot. To export to GIF, see imwrite.
syms t
fp = fplot3(t+sin(40*t),-t+cos(40*t), sin(t));
7-635
7 Functions
for i=0:pi/10:4*pi
fp.ZFunction = sin(t+i);
drawnow
end
Input Arguments
xt — Parametric input for x-axis
symbolic expression | symbolic function
Parametric input for x-axis, specified as a symbolic expression or function. fplot3 uses symvar to
find the parameter.
Parametric input for y-axis, specified as a symbolic expression or function. fplot3 uses symvar to
find the parameter.
Parametric input for z-axis, specified as a symbolic expression or function. fplot3 uses symvar to
find the parameter.
7-636
fplot3
Range of values of parameter, specified as a vector of two numbers. The default range is [-5 5].
ax — Axes object
axes object
Axes object. If you do not specify an axes object, then fplot3 uses the current axes.
Line style, marker, and color, specified as a string scalar or character vector containing symbols. The
symbols can appear in any order. You do not need to specify all three characteristics (line style,
marker, and color). For example, if you omit the line style and specify the marker, then the plot shows
only the marker and no line.
Example: "--or" is a red dashed line with circle markers.
"*" Asterisk
"." Point
"x" Cross
"square" Square
"diamond" Diamond
7-637
7 Functions
"pentagram" Pentagram
"hexagram" Hexagram
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: 'Marker','o','MarkerFaceColor','red'
The properties listed here are only a subset. For a complete list, see Parameterized Function Line.
Number of evaluation points, specified as a number. The default is 23. Because fplot3 uses adaptive
evaluation, the actual number of evaluation points is greater.
Line color, specified as an RGB triplet, a hexadecimal color code, a color name, or a short name.
• An RGB triplet is a three-element row vector whose elements specify the intensities of the red,
green, and blue components of the color. The intensities must be in the range [0,1], for example,
[0.4 0.6 0.7].
7-638
fplot3
• A hexadecimal color code is a string scalar or character vector that starts with a hash symbol (#)
followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case
sensitive. Therefore, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are
equivalent.
Alternatively, you can specify some common colors by name. This table lists the named color options,
the equivalent RGB triplets, and hexadecimal color codes.
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many
types of plots.
Example: 'blue'
Example: [0 0 1]
Example: '#0000FF'
7-639
7 Functions
Line width, specified as a positive value in points, where 1 point = 1/72 of an inch. If the line has
markers, then the line width also affects the marker edges.
The line width cannot be thinner than the width of a pixel. If you set the line width to a value that is
less than the width of a pixel on your system, the line displays as one pixel wide.
Marker symbol, specified as one of the values listed in this table. By default, the object does not
display markers. Specifying a marker symbol adds markers at each data point or vertex.
"*" Asterisk
"." Point
"x" Cross
"square" Square
"diamond" Diamond
"pentagram" Pentagram
7-640
fplot3
Marker outline color, specified as "auto", an RGB triplet, a hexadecimal color code, a color name, or
a short name. The default value of "auto" uses the same color as the Color property.
• An RGB triplet is a three-element row vector whose elements specify the intensities of the red,
green, and blue components of the color. The intensities must be in the range [0,1], for example,
[0.4 0.6 0.7].
• A hexadecimal color code is a string scalar or character vector that starts with a hash symbol (#)
followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case
sensitive. Therefore, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are
equivalent.
Alternatively, you can specify some common colors by name. This table lists the named color options,
the equivalent RGB triplets, and hexadecimal color codes.
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many
types of plots.
7-641
7 Functions
Marker fill color, specified as 'auto', an RGB triplet, a hexadecimal color code, a color name, or a
short name. The 'auto' value uses the same color as the MarkerEdgeColor property.
• An RGB triplet is a three-element row vector whose elements specify the intensities of the red,
green, and blue components of the color. The intensities must be in the range [0,1], for example,
[0.4 0.6 0.7].
• A hexadecimal color code is a string scalar or character vector that starts with a hash symbol (#)
followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case
sensitive. Therefore, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are
equivalent.
Alternatively, you can specify some common colors by name. This table lists the named color options,
the equivalent RGB triplets, and hexadecimal color codes.
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many
types of plots.
7-642
fplot3
Marker size, specified as a positive value in points, where 1 point = 1/72 of an inch.
Output Arguments
fp — One or more parameterized function line objects
scalar | vector
One or more parameterized line objects, returned as a scalar or a vector. You can use these objects to
query and modify properties of a specific parameterized line. For details, see Parameterized Function
Line.
Version History
Introduced in R2016a
See Also
Functions
fcontour | fimplicit | fimplicit3 | fmesh | fplot | fsurf
Properties
Parameterized Function Line
Topics
“Create Plots of Symbolic Expressions” on page 4-2
7-643
7 Functions
fresnelc
Fresnel cosine integral function
Syntax
fresnelc(z)
Description
fresnelc(z) returns the Fresnel cosine integral on page 7-647 of z.
Examples
Fresnel Cosine Integral Function for Numeric and Symbolic Input Arguments
Find the Fresnel cosine integral function for these numbers. Since these are not symbolic objects, you
receive floating-point results.
ans =
-0.4883 + 0.0000i 0.0010 + 0.0000i 0.8617 - 0.2524i
Find the Fresnel cosine integral function symbolically by converting the numbers to symbolic objects:
y =
[ -fresnelc(2), fresnelc(1/1000), fresnelc(61/50 + 31i/100)]
vpa(y)
ans =
[ -0.48825340607534075450022350335726, 0.00099999999999975325988997279422003,...
0.86166573430841730950055370401908 - 0.25236540291386150167658349493972i]
ans =
0.0000 + 0.0000i 0.5000 + 0.0000i -0.5000 + 0.0000i...
0.0000 + 0.5000i 0.0000 - 0.5000i
Find the Fresnel cosine integral for the function exp(x) + 2*x:
7-644
fresnelc
syms f(x)
f = exp(x)+2*x;
fresnelc(f)
ans =
fresnelc(2*x + exp(x))
Find the Fresnel cosine integral for elements of vector V and matrix M:
syms x
V = [sin(x) 2i -7];
M = [0 2; i exp(x)];
fresnelc(V)
fresnelc(M)
ans =
[ fresnelc(sin(x)), fresnelc(2i), -fresnelc(7)]
ans =
[ 0, fresnelc(2)]
[ fresnelc(1i), fresnelc(exp(x))]
syms x
fplot(fresnelc(x),[-5 5])
grid on
7-645
7 Functions
syms x
diff(fresnelc(x),x,3)
ans =
- pi*sin((pi*x^2)/2) - x^2*pi^2*cos((pi*x^2)/2)
Find the limit of the Fresnel cosine integral function as x tends to infinity:
syms x
limit(fresnelc(x),Inf)
ans =
1/2
Use taylor to expand the Fresnel cosine integral in terms of the Taylor series:
syms x
taylor(fresnelc(x))
7-646
fresnelc
ans =
x - (x^5*pi^2)/40
syms x
simplify(3*fresnelc(x)+2*fresnelc(-x))
ans =
fresnelc(x)
Input Arguments
z — Upper limit on Fresnel cosine integral
numeric value | vector | matrix | multidimensional array | symbolic variable | symbolic expression |
symbolic vector | symbolic matrix | symbolic function
Upper limit on the Fresnel cosine integral, specified as a numeric value, vector, matrix, or as a
multidimensional array, or a symbolic variable, expression, vector, matrix, or function.
More About
Fresnel Cosine Integral
πt2
∫
z
fresnelc z = cos dt .
0 2
Algorithms
fresnelc is analytic throughout the complex plane. It satisfies fresnelc(-z) = -fresnelc(z),
conj(fresnelc(z)) = fresnelc(conj(z)), and fresnelc(i*z) = i*fresnelc(z) for all complex values of z.
fresnelc returns special values for z = 0, z = ±∞, and z = ±i∞ which are 0, ±5, and ±0.5i.
fresnelc(z) returns symbolic function calls for all other symbolic values of z.
Version History
Introduced in R2014a
See Also
fresnels | erf
7-647
7 Functions
fresnels
Fresnel sine integral function
Syntax
fresnels(z)
Description
fresnels(z) returns the Fresnel sine integral on page 7-650 of z.
Examples
Fresnel Sine Integral Function for Numeric and Symbolic Arguments
Find the Fresnel sine integral function for these numbers. Since these are not symbolic objects, you
receive floating-point results.
fresnels([-2 0.001 1.22+0.31i])
ans =
-0.3434 + 0.0000i 0.0000 + 0.0000i 0.7697 + 0.2945i
Find the Fresnel sine integral function symbolically by converting the numbers to symbolic objects:
y = fresnels(sym([-2 0.001 1.22+0.31i]))
y =
[ -fresnels(2), fresnels(1/1000), fresnels(61/50 + 31i/100)]
Find the Fresnel sine integral for the function exp(x) + 2*x:
syms x
f = symfun(exp(x)+2*x,x);
fresnels(f)
7-648
fresnels
ans(x) =
fresnels(2*x + exp(x))
Find the Fresnel sine integral for elements of vector V and matrix M:
syms x
V = [sin(x) 2i -7];
M = [0 2; i exp(x)];
fresnels(V)
fresnels(M)
ans =
[ fresnels(sin(x)), fresnels(2i), -fresnels(7)]
ans =
[ 0, fresnels(2)]
[ fresnels(1i), fresnels(exp(x))]
syms x
fplot(fresnels(x),[-5 5])
grid on
7-649
7 Functions
ans =
- 3*x*pi^2*sin((pi*x^2)/2) - x^3*pi^3*cos((pi*x^2)/2)
Find the limit of the Fresnel sine integral function as x tends to infinity:
syms x
limit(fresnels(x),Inf)
ans =
1/2
Use taylor to expand the Fresnel sine integral in terms of the Taylor series:
syms x
taylor(fresnels(x))
ans =
(pi*x^3)/6
ans =
fresnels(x)
Input Arguments
z — Upper limit on the Fresnel sine integral
numeric value | vector | matrix | multidimensional array | symbolic variable | symbolic expression |
symbolic vector | symbolic matrix | symbolic function
Upper limit on the Fresnel sine integral, specified as a numeric value, vector, matrix, or a
multidimensional array or as a symbolic variable, expression, vector, matrix, or function.
More About
Fresnel Sine Integral
7-650
fresnels
Algorithms
The fresnels(z) function is analytic throughout the complex plane. It satisfies fresnels(-z) = -
fresnels(z), conj(fresnels(z)) = fresnels(conj(z)), and fresnels(i*z) = -i*fresnels(z) for all complex
values of z.
fresnels(z) returns special values for z = 0, z = ±∞, and z = ±i∞ which are 0, ±5, and ∓0.5i.
fresnels(z) returns symbolic function calls for all other symbolic values of z.
Version History
Introduced in R2014a
See Also
fresnelc | erf
7-651
7 Functions
fsurf
Plot 3-D surface
Syntax
fsurf(f)
fsurf(f,[min max])
fsurf(f,[xmin xmax ymin ymax])
fsurf(funx,funy,funz)
fsurf(funx,funy,funz,[uvmin uvmax])
fsurf(funx,funy,funz,[umin umax vmin vmax])
Description
fsurf(f) creates a surface plot of the symbolic expression f(x,y) over the default interval [-5 5]
for x and y.
fsurf(f,[min max]) plots f(x,y) over the interval [min max] for x and y.
fsurf(f,[xmin xmax ymin ymax]) plots f(x,y) over the interval [xmin xmax] for x and
[ymin ymax] for y. The fsurf function uses symvar to order the variables and assign intervals.
fsurf( ___ ,LineSpec) uses LineSpec to set the line style, marker symbol, and face color. Use
this option after any of the previous input argument combinations.
fsurf( ___ ,Name,Value) specifies line properties using one or more Name,Value pair arguments.
Use this option after any of the input argument combinations in the previous syntaxes.
fsurf(ax, ___ ) plots into the axes with the object ax instead of the current axes object gca.
fs = fsurf( ___ ) returns a function surface object or parameterized function surface object,
depending on the type of surface. Use the object to query and modify properties of a specific surface.
For details, see Function Surface and Parameterized Function Surface.
7-652
fsurf
Examples
Plot the input sin(x) + cos(y) over the default range −5 < x < 5 and −5 < y < 5.
syms x y
fsurf(sin(x)+cos(y))
Plot the real part of tan−1(x + iy) over the default range −5 < x < 5 and −5 < y < 5.
syms f(x,y)
f(x,y) = real(atan(x + i*y));
fsurf(f)
7-653
7 Functions
Plot sin(x) + cos(y) over −π < x < π and −5 < y < 5 by specifying the plotting interval as the second
argument of fsurf.
syms x y
f = sin(x) + cos(y);
fsurf(f, [-pi pi -5 5])
7-654
fsurf
x = rcos(s)sin(t)
y = rsin(s)sin(t)
z = rcos(t)
where r = 2 + sin(7s + 5t)
syms s t
r = 2 + sin(7*s + 5*t);
x = r*cos(s)*sin(t);
y = r*sin(s)*sin(t);
z = r*cos(t);
fsurf(x, y, z, [0 2*pi 0 pi])
camlight
view(46,52)
7-655
7 Functions
7-656
fsurf
For x and y from −2π to 2π, plot the 3-D surface ysin(x) − xcos(y). Add a title and axis labels.
Create the x-axis ticks by spanning the x-axis limits at intervals of pi/2. Convert the axis limits to
precise multiples of pi/2 by using round and get the symbolic tick values in S. Display these ticks by
using the XTick property. Create x-axis labels by using arrayfun to apply texlabel to S. Display
these labels by using the XTickLabel property. Repeat these steps for the y-axis.
syms x y
fsurf(y.*sin(x)-x.*cos(y), [-2*pi 2*pi])
title('ysin(x) - xcos(y) for x and y in [-2\pi,2\pi]')
xlabel('x')
ylabel('y')
zlabel('z')
ax = gca;
S = sym(ax.XLim(1):pi/2:ax.XLim(2));
S = sym(round(vpa(S/pi*2))*pi/2);
ax.XTick = double(S);
ax.XTickLabel = arrayfun(@texlabel,S,'UniformOutput',false);
7-657
7 Functions
S = sym(ax.YLim(1):pi/2:ax.YLim(2));
S = sym(round(vpa(S/pi*2))*pi/2);
ax.YTick = double(S);
ax.YTickLabel = arrayfun(@texlabel,S,'UniformOutput',false);
Plot the parametric surface x = ssin(t), y = − scos(t), z = t with different line styles for different
values of t. For −5 < t < − 2, use a dashed line with green dot markers. For −2 < t < 2, use a
LineWidth of 1 and a green face color. For 2 < t < 5, turn off the lines by setting EdgeColor to
none.
syms s t
fsurf(s*sin(t),-s*cos(t),t,[-5 5 -5 -2],'--.','MarkerEdgeColor','g')
hold on
fsurf(s*sin(t),-s*cos(t),t,[-5 5 -2 2],'LineWidth',1,'FaceColor','g')
fsurf(s*sin(t),-s*cos(t),t,[-5 5 2 5],'EdgeColor','none')
7-658
fsurf
x = e− | u | /10sin(5 | v | )
y = e− | u | /10cos(5 | v | )
z = u.
syms u v
x = exp(-abs(u)/10).*sin(5*abs(v));
y = exp(-abs(u)/10).*cos(5*abs(v));
z = u;
fs = fsurf(x,y,z)
7-659
7 Functions
fs =
ParameterizedFunctionSurface with properties:
XFunction: exp(-abs(u)/10)*sin(5*abs(v))
YFunction: exp(-abs(u)/10)*cos(5*abs(v))
ZFunction: u
EdgeColor: [0 0 0]
LineStyle: '-'
FaceColor: 'interp'
Change the range of u to [-30 30] by using the URange property of fs. Set the line color to blue by
using the EdgeColor property and specify white, dot markers by using the Marker and
MarkerEdgeColor properties.
7-660
fsurf
Plot multiple surfaces using vector input to fsurf. Alternatively, use hold on to plot successively on
the same figure. When displaying multiple surfaces on the same figure, transparency is useful. Adjust
the transparency of surface plots by using the FaceAlpha property. FaceAlpha varies from 0 to 1,
where 0 is full transparency and 1 is no transparency.
Plot the planes x + y and x − y using vector input to fsurf. Show both planes by making them half
transparent using FaceAlpha.
syms x y
h = fsurf([x+y x-y]);
h(1).FaceAlpha = 0.5;
h(2).FaceAlpha = 0.5;
title('Planes (x+y) and (x-y) at half transparency')
7-661
7 Functions
Control the resolution of a surface plot using the 'MeshDensity' option. Increasing
'MeshDensity' can make smoother, more accurate plots while decreasing it can increase plotting
speed.
Divide a figure into two using subplot. In the first subplot, plot the parametric surface x = sin(s),
y = cos(s), and z = (t/10)sin(1/s). The surface has a large gap. Fix this issue by increasing the
'MeshDensity' to 40 in the second subplot. fsurf fills the gap showing that by increasing
'MeshDensity' you increased the plot's resolution.
syms s t
subplot(2,1,1)
fsurf(sin(s), cos(s), t/10.*sin(1./s))
view(-172,25)
title('Default MeshDensity = 35')
subplot(2,1,2)
fsurf(sin(s), cos(s), t/10.*sin(1./s),'MeshDensity',40)
view(-172,25)
title('Increased MeshDensity = 40')
7-662
fsurf
Show contours for the surface plot of the expression f by setting the 'ShowContours' option to
'on'.
syms x y
f = 3*(1-x)^2*exp(-(x^2)-(y+1)^2)...
- 10*(x/5 - x^3 - y^5)*exp(-x^2-y^2)...
- 1/3*exp(-(x+1)^2 - y^2);
fsurf(f,[-3 3],'ShowContours','on')
7-663
7 Functions
Create an animation of surface plots by changing the displayed expression using the Function,
XFunction, YFunction, and ZFunction properties, and then use drawnow to update the plot. To
export to GIF, see imwrite.
syms s t
h = fsurf(t.*sin(s), cos(s), sin(1./s), [-0.1 0.1 0 1]);
h.MeshDensity = 9;
for i=1:0.1:3
h.ZFunction = sin(i./s);
drawnow
end
7-664
fsurf
Plot the expression f as a surface. Improve the appearance of the surface plot by using the properties
of the handle returned by fsurf, the lighting properties, and the colormap.
Create a light by using camlight. Increase brightness by using brighten. Remove the lines by
setting EdgeColor to 'none'. Increase the ambient light using AmbientStrength. For details, see
“Lighting, Transparency, and Shading”. Turn the axes box on. For the title, convert f to LaTeX using
latex. Finally, to improve the appearance of the axes ticks, axes labels, and title, set
'Interpreter' to 'latex'.
syms x y
f = 3*(1-x)^2*exp(-(x^2)-(y+1)^2)...
- 10*(x/5 - x^3 - y^5)*exp(-x^2-y^2)...
- 1/3*exp(-(x+1)^2 - y^2);
h = fsurf(f,[-3 3]);
camlight(110,70)
brighten(0.6)
h.EdgeColor = 'none';
h.AmbientStrength = 0.4;
7-665
7 Functions
a = gca;
a.TickLabelInterpreter = 'latex';
a.Box = 'on';
a.BoxStyle = 'full';
xlabel('$x$','Interpreter','latex')
ylabel('$y$','Interpreter','latex')
zlabel('$z$','Interpreter','latex')
title_latex = ['$' latex(f) '$'];
title(title_latex,'Interpreter','latex')
Plot a cylindrical shell bounded below by the x − y plane and above by the plane z = x + 2.
syms r t u
fsurf(cos(t),sin(t),u*(cos(t)+2),[0 2*pi 0 1])
hold on;
fsurf(r*cos(t),r*sin(t),r*cos(t)+2,[0 1 0 2*pi])
7-666
fsurf
x θ , φ = R + a cos θ cos φ
y θ , φ = R + a cos θ sin φ
z θ , φ = a sin φ
where
Define the values for a and R as 1 and 5, respectively. Plot the torus using fsurf.
syms theta phi
a = 1;
R = 4;
x = (R + a*cos(theta))*cos(phi);
y = (R + a*cos(theta))*sin(phi);
7-667
7 Functions
z = a*sin(theta);
fsurf(x,y,z,[0 2*pi 0 2*pi])
hold on
Apply rotation to the torus around the x-axis. Define the rotation matrix. Rotate the torus by 90
degrees or π/2 radians.
alpha = pi/2;
Rx = [1 0 0;
0 cos(alpha) -sin(alpha);
0 sin(alpha) cos(alpha)];
r = [x; y; z];
r_90 = Rx*r;
Shift the center of the torus by 5 along the x-axis. Add a second plot of the rotated and translated
torus to the existing graph.
fsurf(r_90(1)+5,r_90(2),r_90(3))
axis([-5 10 -5 10 -5 5])
hold off
Input Arguments
f — 3-D expression or function to be plotted
symbolic expression | symbolic function
7-668
fsurf
Plotting interval for x- and y-axes, specified as a vector of two numbers. The default is [-5 5].
Plotting interval for x- and y-axes, specified as a vector of four numbers. The default is [-5 5 -5 5].
Plotting interval for u and v axes, specified as a vector of two numbers. The default is [-5 5].
Plotting interval for u and v, specified as a vector of four numbers. The default is [-5 5 -5 5].
ax — Axes object
axes object
Axes object. If you do not specify an axes object, then fsurf uses the current axes.
Line style, marker, and color, specified as a string scalar or character vector containing symbols. The
symbols can appear in any order. You do not need to specify all three characteristics (line style,
marker, and color). For example, if you omit the line style and specify the marker, then the plot shows
only the marker and no line.
Example: "--or" is a red dashed line with circle markers.
7-669
7 Functions
"*" Asterisk
"." Point
"x" Cross
"square" Square
"diamond" Diamond
"pentagram" Pentagram
"hexagram" Hexagram
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
7-670
fsurf
Example: 'Marker','o','MarkerFaceColor','red'
The properties listed here are only a subset. For a complete list, see Function Surface.
Number of evaluation points per direction, specified as a number. The default is 35. Because fsurf
objects use adaptive evaluation, the actual number of evaluation points is greater.
Example: 100
Display contour plot under plot, specified as 'on' or 'off', or as numeric or logical 1 (true) or 0
(false). A value of 'on' is equivalent to true, and 'off' is equivalent to false. Thus, you can use
the value of this property as a logical value. The value is stored as an on/off logical value of type
matlab.lang.OnOffSwitchState.
Line color, specified as 'interp', an RGB triplet, a hexadecimal color code, a color name, or a short
name. The default RGB triplet value of [0 0 0] corresponds to black. The 'interp' value colors
the edges based on the ZData values.
• An RGB triplet is a three-element row vector whose elements specify the intensities of the red,
green, and blue components of the color. The intensities must be in the range [0,1], for example,
[0.4 0.6 0.7].
• A hexadecimal color code is a string scalar or character vector that starts with a hash symbol (#)
followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case
sensitive. Therefore, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are
equivalent.
Alternatively, you can specify some common colors by name. This table lists the named color options,
the equivalent RGB triplets, and hexadecimal color codes.
7-671
7 Functions
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many
types of plots.
Line width, specified as a positive value in points, where 1 point = 1/72 of an inch. If the line has
markers, then the line width also affects the marker edges.
The line width cannot be thinner than the width of a pixel. If you set the line width to a value that is
less than the width of a pixel on your system, the line displays as one pixel wide.
Marker symbol, specified as one of the values listed in this table. By default, the object does not
display markers. Specifying a marker symbol adds markers at each data point or vertex.
7-672
fsurf
"*" Asterisk
"." Point
"x" Cross
"square" Square
"diamond" Diamond
"pentagram" Pentagram
"hexagram" Hexagram
Marker outline color, specified as 'auto', an RGB triplet, a hexadecimal color code, a color name, or
a short name. The default value of 'auto' uses the same color as the EdgeColor property.
• An RGB triplet is a three-element row vector whose elements specify the intensities of the red,
green, and blue components of the color. The intensities must be in the range [0,1], for example,
[0.4 0.6 0.7].
• A hexadecimal color code is a string scalar or character vector that starts with a hash symbol (#)
followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case
sensitive. Therefore, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are
equivalent.
Alternatively, you can specify some common colors by name. This table lists the named color options,
the equivalent RGB triplets, and hexadecimal color codes.
7-673
7 Functions
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many
types of plots.
Marker fill color, specified as 'auto', an RGB triplet, a hexadecimal color code, a color name, or a
short name. The 'auto' value uses the same color as the MarkerEdgeColor property.
• An RGB triplet is a three-element row vector whose elements specify the intensities of the red,
green, and blue components of the color. The intensities must be in the range [0,1], for example,
[0.4 0.6 0.7].
• A hexadecimal color code is a string scalar or character vector that starts with a hash symbol (#)
followed by three or six hexadecimal digits, which can range from 0 to F. The values are not case
sensitive. Therefore, the color codes "#FF8800", "#ff8800", "#F80", and "#f80" are
equivalent.
7-674
fsurf
Alternatively, you can specify some common colors by name. This table lists the named color options,
the equivalent RGB triplets, and hexadecimal color codes.
Here are the RGB triplets and hexadecimal color codes for the default colors MATLAB uses in many
types of plots.
Marker size, specified as a positive value in points, where 1 point = 1/72 of an inch.
Output Arguments
fs — One or more objects
scalar | vector
One or more objects, returned as a scalar or a vector. The object is either a function surface object or
parameterized surface object, depending on the type of plot. You can use these objects to query and
modify properties of a specific line. For details, see Function Surface and Parameterized Function
Surface.
7-675
7 Functions
Algorithms
fsurf assigns the symbolic variables in f to the x-axis, then the y-axis, and symvar determines the
order of the variables to be assigned. Therefore, variable and axis names might not correspond. To
force fsurf to assign x or y to its corresponding axis, create the symbolic function to plot, then pass
the symbolic function to fsurf.
For example, the following code plots f(x,y) = sin(y) in two ways. The first way forces the waves to
oscillate with respect to the y-axis. In other words, the first plot assigns the y variable to the
corresponding y-axis. The second plot assigns y to the x-axis because it is the first (and only) variable
in the symbolic function.
syms x y;
f(x,y) = sin(y);
figure;
subplot(2,1,1)
fsurf(f);
subplot(2,1,2)
fsurf(f(x,y)); % Or fsurf(sin(y));
Version History
Introduced in R2016a
7-676
fsurf
See Also
Functions
fcontour | fimplicit | fimplicit3 | fmesh | fplot | fplot3
Properties
Function Surface | Parameterized Function Surface
Topics
“Create Plots of Symbolic Expressions” on page 4-2
7-677
7 Functions
functionalDerivative
Functional derivative (variational derivative)
Syntax
G = functionalDerivative(f,y)
Description
δS
G = functionalDerivative(f,y) returns the functional derivative on page 7-683 x of the
δy
∫
b
functional S y = f x, y x , y′ x , ... dx with respect to the function y = y(x), where x represents one
a
or more independent variables. The functional derivative relates the change in the functional S[y]
with respect to a small variation in y(x).The functional derivative is also known as the variational
derivative.
Examples
Declare y(x) as a symbolic function and define f as the integrand of S. Use f and y as the
parameters of functionalDerivative.
syms y(x)
f = y*sin(y);
G = functionalDerivative(f,y)
2
∫
a dv(x) d u(x)
Find the functional derivative of the functional S[u, v] = u2(x) + v(x) dx with respect
b dx dx2
2
dv d u
to the functions u and v, where the integrand is f [u(x), v(x), u′′(x), v′(x)] = u2 + v 2.
dx dx
Declare u(x) and v(x) as symbolic functions, and define f as the integrand of S.
7-678
functionalDerivative
G = functionalDerivative(f,[u v])
G(x) =
∂2 ∂
v x +2u x vx
∂x2 ∂x
∂2 ∂
u x −2u x ux
∂x 2 ∂x
Find the Euler–Lagrange equation of a mass m that is connected to a spring with spring constant k.
Define the kinetic energy T, potential energy V, and Lagrangian L of the system. The Lagrangian is
the difference between the kinetic and potential energy.
syms m k x(t)
T = 1/2*m*diff(x,t)^2;
V = 1/2*k*x^2;
L = T - V
L(t) =
∂ 2
m ∂t x t kx t
2
−
2 2
In Lagrangian mechanics, the action functional of the system is equal to the integral of the
t2
Lagrangian over time, or S[x] = ∫
t1
L[t, x(t), ẋ(t)] dt. The Euler–Lagrange equation describes the
motion of the system for which S[x(t)] is stationary.
Find the Euler–Lagrange equation by taking the functional derivative of the integrand L and setting it
equal to 0.
eqn = functionalDerivative(L,x) == 0
eqn(t) =
∂2
−m x t −kx t = 0
∂t2
Solve eqn using dsolve. Assume the mass m and spring constant k are positive. Set the initial
conditions for the oscillation amplitude as x(0) = 10 and the initial velocity of the mass as ẋ(0) = 0.
7-679
7 Functions
assume(m,'positive')
assume(k,'positive')
Dx(t) = diff(x(t),t);
xSol = dsolve(eqn,[x(0) == 10, Dx(0) == 0])
xSol =
kt
10 cos
m
assume([k m],'clear')
The Brachistochrone problem is to find the quickest path of descent of a particle under gravity
without friction. The motion is confined to a vertical plane. The time for a body to move along a curve
y(x) from point a to b under gravity g is given by
1 + y′2
∫
b
t= dx .
a 2gy
Find the quickest path by minimizing the change in t with respect to small variations in the path y.
δt
The condition for a minimum is (x) = 0.
δy
Compute the functional derivative to obtain the differential equation that describes the
Brachistochrone problem. Use simplify to simplify the equation to its expected form.
syms g y(x)
assume(g,'positive')
f = sqrt((1 + diff(y)^2)/(2*g*y));
eqn = functionalDerivative(f,y) == 0;
eqn = simplify(eqn)
eqn(x) =
∂2 ∂ 2
2y x yx + y x = −1
∂x 2 ∂x
This equation is the standard differential equation of the Brachistochrone problem. To find the
solutions of the differential equation, use dsolve. Specify the 'Implicit' option to true to return
implicit solutions, which have the form F(y(x)) = g(x).
sols = dsolve(eqn,'Implicit',true)
sols =
7-680
functionalDerivative
y x = C2 − x i
y x = C3 + x i
σ1 = C4 + x
σ1 = C5 − x
C1 + y x
=0
yx
where
C1 C1
σ1 = C1 atan − −1 −y x − −1
yx yx
The symbolic solver dsolve returns general solutions in the complex space. Symbolic Math Toolbox™
does not accept the assumption that the symbolic function y(x) is real.
Depending on the boundary conditions, there are two real-space solutions to the Brachistochrone
problem. One of the two solutions below describes a cycloid curve in real space.
solCycloid1 = sols(3)
solCycloid1 =
C1 C1
C1 atan − −1 −y x − − 1 = C4 + x
yx yx
solCycloid2 = sols(4)
solCycloid2 =
C1 C1
C1 atan − −1 −y x − − 1 = C5 − x
yx yx
solStraight = simplify(sols(5))
solStraight = C1 + y x = 0
To illustrate the cycloid solution, consider an example with boundary conditions y(0) = 5 and y(4) = 1.
In this case, the equation that can satisfy the given boundary conditions is solCycloid2. Substitute
the two boundary conditions into solCycloid2.
The two equations, eq1 and eq2, have two unknown coefficients, C1 and C5. Use vpasolve to find
numerical solutions for the coefficients. Substitute these solutions into solCycloid2.
eqCycloid =
6.4199192418473511250705556729108
−6.4199192418473511250705556729108 atan −1
yx
6.4199192418473511250705556729108
−y x − 1 = −x − 5.8078336827583088482183433150164
yx
7-681
7 Functions
The implicit equation eqCycloid describes the cycloid solution of the Brachistochrone problem in
terms of x and y(x).
You can then use fimplicit to plot eqCycloid. Since fimplicit only accepts implicit symbolic
equations that contain symbolic variables x and y, convert the symbolic function y(x) to a symbolic
variable y. Use mapSymType to convert y(x) to x. Plot the cycloid solution within the boundary
conditions 0 < x < 4 and 1 < y < 5.
For a function u(x, y) that describes a surface in 3-D space, the surface area can be determined by the
functional
y2 x2 y2 x2
F[u] = ∫ ∫
y1 x1
f [x, y(x), u(x, y), ux, uy] dx dy = ∫ ∫
y1 x1
1 + ux2 + uy2 dx dy
7-682
functionalDerivative
syms u(x,y)
f = sqrt(1 + diff(u,x)^2 + diff(u,y)^2);
G = functionalDerivative(f,u)
G(x, y) =
∂ 2 ∂2 ∂2 ∂2 ∂ ∂ ∂2
∂y
u x, y 2
u x, y + 2 u x, y + σ12 2 u x, y − 2 ∂y σ1 ∂y u x, y σ1 + 2 u x, y
∂x ∂x ∂y ∂y
− 3/2
2 ∂ 2
σ1 + ∂y u x, y + 1
where
∂
σ1 = u x, y
∂x
The result is the equation G that describes the minimal surface of a 3-D surface defined by u(x,y).
The solutions to this equation describe minimal surfaces in 3-D space, such as soap bubbles.
Input Arguments
f — Integrand of functional
symbolic variable | symbolic function | symbolic expression
y — Differentiation function
unassigned symbolic function | vector of unassigned symbolic functions | matrix of unassigned
symbolic functions | multidimensional array of unassigned symbolic functions
Output Arguments
G — Functional derivative
symbolic function | vector of symbolic functions
More About
Functional Derivative
Consider a functional
∫
b
Sy = f x, y x , y′ x , ..., y(n) x dx,
a
7-683
7 Functions
For a small variation in the path y(x), define the change as δy(x) = εϕ(x) in which ϕ(x) is an arbitrary
test function. The change in the functional S is
∫
S y + εϕ − S y b δS
DS y = lim = x ϕ(x)dx.
ε 0 ε a δy
δS
The expression x is the functional derivative of S with respect to y. The linear functional DS[y] is
δy
also known as the first variation or the Gateaux differential of the functional S.
One method to calculate the functional derivative is to apply Taylor expansion to the expression S[y +
εϕ] with respect to ε. By keeping the first order terms in ε, performing integration by parts, and
choosing the boundary conditions ϕ(a) = ϕ(b) = ϕ'(a) = ϕ'(b) = ... = 0, the functional derivative
becomes
2 n
δS ∂f d ∂f d ∂f n d ∂f
x = − + − ... + −1
δy ∂y dx ∂y′ dx2 ∂y′′ dxn ∂y(n)
n i
i d ∂f
= ∑ −1 .
i=0 dxi ∂y(i)
Version History
Introduced in R2015a
See Also
diff | dsolve | int
Topics
“Functional Derivatives Tutorial” on page 3-217
7-684
funm
funm
General matrix function
Syntax
F = funm(A,f)
Description
F = funm(A,f) computes the function f(A) for the square matrix A. For details, see “Matrix
Function” on page 7-688.
Examples
Matrix Cube Root
To solve B3 = A, compute the cube root of the matrix A using the funm function. Create the symbolic
function f(x) = x^(1/3) and use it as the second argument for funm. The cube root of an identity
matrix is the identity matrix itself.
A = sym(eye(3))
syms f(x)
f(x) = x^(1/3);
B = funm(A,f)
A =
[ 1, 0, 0]
[ 0, 1, 0]
[ 0, 0, 1]
B =
[ 1, 0, 0]
[ 0, 1, 0]
[ 0, 0, 1]
Replace one of the 0 elements of matrix A with 1 and compute the matrix cube root again.
A(1,2) = 1
B = funm(A,f)
A =
[ 1, 1, 0]
[ 0, 1, 0]
[ 0, 0, 1]
B =
[ 1, 1/3, 0]
[ 0, 1, 0]
[ 0, 0, 1]
7-685
7 Functions
A(1:2,2:3) = 1
B = funm(A,f)
A =
[ 1, 1, 1]
[ 0, 1, 1]
[ 0, 0, 1]
B =
[ 1, 1/3, 2/9]
[ 0, 1, 1/3]
[ 0, 0, 1]
Verify that B3 = A.
B^3
ans =
[ 1, 1, 1]
[ 0, 1, 1]
[ 0, 0, 1]
First, create a 3-by-3 matrix A using variable-precision arithmetic with five digit accuracy. In this
example, using variable-precision arithmetic instead of exact symbolic numbers lets you speed up
computations and decrease memory usage. Using only five digits helps the result to fit on screen.
savedefault = digits(5);
A = vpa(magic(3))
A =
[ 8.0, 1.0, 6.0]
[ 3.0, 5.0, 7.0]
[ 4.0, 9.0, 2.0]
syms f(x)
f(x) = lambertw(x);
To find the Lambert W function (W0 branch) in a matrix sense, callfunm using f(x) as its second
argument.
W0 = funm(A,f)
W0 =
[ 1.5335 + 0.053465i, 0.11432 + 0.47579i, 0.36208 - 0.52925i]
[ 0.21343 + 0.073771i, 1.3849 + 0.65649i, 0.41164 - 0.73026i]
[ 0.26298 - 0.12724i, 0.51074 - 1.1323i, 1.2362 + 1.2595i]
Verify that this result is a solution of the matrix equation A = W0·eW0 within the specified accuracy.
W0*expm(W0)
7-686
funm
ans =
[ 8.0, 1.0 - 5.6843e-13i, 6.0 + 1.1369e-13i]
[ 3.0 - 2.2737e-13i, 5.0 - 2.8422e-14i, 7.0 - 4.1211e-13i]
[ 4.0 - 2.2737e-13i, 9.0 - 9.9476e-14i, 2.0 + 1.4779e-12i]
Now, create the symbolic function f(x) representing the branch W-1 of the Lambert W function.
f(x) = lambertw(-1,x);
Wm1 = funm(A,f)
Wm1 =
[ 0.40925 - 4.7154i, 0.54204 + 0.5947i, 0.13764 - 0.80906i]
[ 0.38028 + 0.033194i, 0.65189 - 3.8732i, 0.056763 - 1.0898i]
[ 0.2994 - 0.24756i, - 0.105 - 1.6513i, 0.89453 - 3.0309i]
Verify that this result is the solution of the matrix equation A = Wm1·eWm1 within the specified
accuracy.
Wm1*expm(Wm1)
ans =
[ 8.0 - 8.3844e-13i, 1.0 - 3.979e-13i, 6.0 - 9.0949e-13i]
[ 3.0 - 9.6634e-13i, 5.0 + 1.684e-12i, 7.0 + 4.5475e-13i]
[ 4.0 - 1.3642e-12i, 9.0 + 1.6698e-12i, 2.0 + 1.7053e-13i]
You can use funm with appropriate second arguments to find matrix exponential, logarithm, and
square root. However, the more efficient approach is to use the functions expm, logm, and sqrtm for
this task.
Create this square matrix and find its exponential, logarithm, and square root.
syms x
A = [1 -1; 0 x]
expA = expm(A)
logA = logm(A)
sqrtA = sqrtm(A)
A =
[ 1, -1]
[ 0, x]
expA =
[ exp(1), (exp(1) - exp(x))/(x - 1)]
[ 0, exp(x)]
logA =
[ 0, -log(x)/(x - 1)]
[ 0, log(x)]
sqrtA =
[ 1, 1/(x - 1) - x^(1/2)/(x - 1)]
[ 0, x^(1/2)]
7-687
7 Functions
Find the matrix exponential, logarithm, and square root of A using funm. Use the symbolic
expressions exp(x), log(x), and sqrt(x) as the second argument of funm. The results are
identical.
expA = funm(A,exp(x))
logA = funm(A,log(x))
sqrtA = funm(A,sqrt(x))
expA =
[ exp(1), exp(1)/(x - 1) - exp(x)/(x - 1)]
[ 0, exp(x)]
logA =
[ 0, -log(x)/(x - 1)]
[ 0, log(x)]
sqrtA =
[ 1, 1/(x - 1) - x^(1/2)/(x - 1)]
[ 0, x^(1/2)]
Input Arguments
A — Input matrix
square matrix
f — Function
symbolic function | symbolic expression
Output Arguments
F — Resulting matrix
symbolic matrix
More About
Matrix Function
Suppose, f(x), where x is a scalar, has a Taylor series expansion. Then the matrix function f(A),
where A is a matrix, is defined by the Taylor series of f(A), with addition and multiplication
performed in the matrix sense.
d1 ⋯ 0
D= ⋮ ⋱ ⋮
0 ⋯ dn
7-688
funm
f d1 ⋯ 0
−1
f A =P⋅ ⋮ ⋱ ⋮ ⋅P
0 ⋯ f dn
Tips
• For compatibility with the MATLAB funm function, funm accepts the following arguments:
• Function handles such as @exp and @sin, as its second input argument.
• The options input argument, such as funm(A,f,options).
• Additional input arguments of the function f, such as funm(A,f,options,p1,p2,...)
• The exitflag output argument, such as [F,exitflag] = funm(A,f). Here, exitflag is 1
only if the funm function call errors, for example, if it encounters a division by zero. Otherwise,
exitflag is 0.
For more details and a list of all acceptable function handles, see the MATLAB funm function.
• If the input matrix A is numeric (not a symbolic object) and the second argument f is a function
handle, then the funm call invokes the MATLAB funm function.
Version History
Introduced in R2014b
See Also
eig | expm | jordan | logm | sqrtm
7-689
7 Functions
funtool
Function calculator
Description
The funtool app is a visual function calculator that manipulates and displays functions of one
variable. At the click of a button, for example, funtool draws a graph representing the sum,
product, difference, or ratio of two functions that you specify. funtool includes a function memory
that allows you to store functions for later retrieval.
The top of the control panel contains a group of editable text fields.
7-690
funtool
x= Displays the domain used to plot f and g. Edit this field to specify a different
domain.
a= Displays a constant factor used to modify f (see button descriptions in the
next section). Edit this field to change the value of the constant factor.
funtool redraws f and g to reflect any changes you make to the contents of the control panel's text
fields.
The bottom part of the control panel contains an array of buttons that transform f and perform other
operations.
df/dx Derivative of f
int f Integral of f
simplify f Simplified form of f, if possible
num f Numerator of f
den f Denominator of f
1/f Reciprocal of f
7-691
7 Functions
finv Inverse of f
The operators int f and finv can fail if the corresponding symbolic
expressions do not exist in closed form.
The second row of buttons translates and scales f and the domain of f by a
constant factor. To specify the factor, enter its value in the field labeled a=
on the calculator control panel. The operations are
The first four buttons of the third row replace f with a combination of f and
g.
The first three buttons in the fourth row allow you to store and retrieve
functions from the calculator's function memory.
The other four buttons on the fourth row perform miscellaneous functions:
Examples
7-692
funtool
Display a quadratic function by editing the text field f = x^2 + 2*x + 1. Plot the quadratic
function within the interval x = [-5 5].
7-693
7 Functions
7-694
funtool
7-695
7 Functions
Version History
Introduced before R2006a
See Also
fplot | syms | taylortool | rsums
7-696
gamma
gamma
Gamma function
Syntax
gamma(X)
Description
gamma(X) returns the gamma function on page 7-699 of a symbolic variable or symbolic expression
X.
Examples
Gamma Function for Numeric and Symbolic Arguments
Compute the gamma function for these numbers. Because these numbers are not symbolic objects,
you get floating-point results.
A =
0.2466 2.6593 -3.5449 2.6789 1.0000 6.0000
Compute the gamma function for the numbers converted to symbolic objects. For many symbolic
(exact) numbers, gamma returns unresolved symbolic calls.
symA =
[ (27*pi*3^(1/2))/(440*gamma(2/3)), gamma(-7/5),...
-2*pi^(1/2), (2*pi*3^(1/2))/(3*gamma(2/3)), 1, 6]
vpa(symA)
ans =
[ 0.24658411512650858900694446388517,...
2.6592718728800305399898810505738,...
-3.5449077018110320545963349666823,...
2.6789385347077476336556929409747,...
1.0, 6.0]
7-697
7 Functions
syms x
fplot(gamma(x))
grid on
Many functions, such as diff, limit, and simplify, can handle expressions containing gamma.
Differentiate the gamma function, and then substitute the variable t with the value 1:
syms t
u = diff(gamma(t^3 + 1))
u1 = subs(u, t, 1)
u =
3*t^2*gamma(t^3 + 1)*psi(t^3 + 1)
u1 =
3 - 3*eulergamma
ans =
1.2683530052954014181804637297528
Compute the limit of the following expression that involves the gamma function:
7-698
gamma
syms x
limit(x/gamma(x), x, inf)
ans =
0
syms x
simplify(gamma(x)*gamma(1 - x))
ans =
pi/sin(pi*x)
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
More About
Gamma Function
Version History
Introduced before R2006a
See Also
beta | factorial | igamma | gammaln | nchoosek | pochhammer | psi
7-699
7 Functions
gammaln
Logarithmic gamma function
Syntax
gammaln(X)
Description
gammaln(X) returns the logarithmic gamma function for each element of X.
Examples
Logarithmic Gamma Function for Numeric and Symbolic Arguments
Compute the logarithmic gamma function for these numbers. Because these numbers are not
symbolic objects, you get floating-point results.
A = gammaln([1/5, 1/2, 2/3, 8/7, 3])
A =
1.5241 0.5724 0.3032 -0.0667 0.6931
Compute the logarithmic gamma function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, gammaln returns results in terms of the gammaln, log, and gamma
functions.
symA = gammaln(sym([1/5, 1/2, 2/3, 8/7, 3]))
symA =
[ gammaln(1/5), log(pi^(1/2)), gammaln(2/3),...
log(gamma(1/7)/7), log(2)]
ans =
[ 1.5240638224307845248810564939263,...
0.57236494292470008707171367567653,...
0.30315027514752356867586281737201,...
-0.066740877459477468649396334098109,...
0.69314718055994530941723212145818]
Compute the logarithmic gamma function for positive integer arguments. For such arguments, the
logarithmic gamma function is defined as the natural logarithm of the gamma function, gammaln(x)
= log(gamma(x)).
7-700
gammaln
pos =
[ log((pi*2^(1/2))/gamma(3/4)), log((2*pi*3^(1/2))/(3*gamma(2/3))), 0, log(24), Inf]
Compute the logarithmic gamma function for nonpositive integer arguments. For nonpositive
integers, gammaln returns Inf.
nonposint =
[ Inf, Inf, Inf, Inf, Inf]
Compute the logarithmic gamma function for complex and negative rational arguments. For these
arguments, gammaln returns unresolved symbolic calls.
complex =
[ gammaln(1i), gammaln(- 1 + 2i), gammaln(-2/3), gammaln(-10/3)]
vpa(complex)
ans =
[ - 0.65092319930185633888521683150395 - 1.8724366472624298171188533494366i,...
- 3.3739449232079248379476073664725 - 3.4755939462808110432931921583558i,...
1.3908857550359314511651871524423 - 3.1415926535897932384626433832795i,...
- 0.93719017334928727370096467598178 - 12.566370614359172953850573533118i]
gammaln(sym(-Inf))
ans =
NaN
syms x
fplot(gammaln(x),[0 10])
grid on
7-701
7 Functions
To see the negative values better, plot the same function on the interval from 1 to 2.
fplot(gammaln(x),[1 2])
grid on
7-702
gammaln
Many functions, such as diff and limit, can handle expressions containing lngamma.
syms x
diff(gammaln(x), x)
ans =
psi(x)
Compute the limits of these expressions containing the logarithmic gamma function:
syms x
limit(1/gammaln(x), x, Inf)
ans =
0
ans =
log(2) + pi*1i
7-703
7 Functions
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Algorithms
For single or double input to gammaln(x), x must be real and positive.
• gammaln(x) is defined for all complex x except the singular points 0, -1, -2, ... .
• For positive real x, gammaln(x) represents the logarithmic gamma function log(gamma(x)).
• For negative real x or for complex x, gammaln(x) = log(gamma(x)) + f(x)2πi where f(x) is some
integer valued function. The integer multiples of 2πi are chosen such that gammaln(x) is analytic
throughout the complex plane with a branch cut along the negative real semi axis.
• For negative real x, gammaln(x) is equal to the limit of log(gamma(x)) from ‘above’.
Version History
Introduced in R2014a
See Also
beta | gamma | log | nchoosek | psi
7-704
gcd
gcd
GCD of numbers and polynomials
Syntax
G = gcd(A)
G = gcd(A,B)
[G,M] = gcd(A)
[G,C,D] = gcd(A,B,X)
Description
G = gcd(A) finds the greatest common divisor of all elements of A.
[G,M] = gcd(A) returns the GCD G of all elements of A, and returns in M the linear combination of
A that equals G.
[G,C,D] = gcd(A,B,X) finds the greatest common divisor of A and B, and also returns the Bézout
coefficients, C and D, such that G = A*C + B*D. For multivariate expressions, specify the polynomial
variable X such that it does not appear in the denominator of C and D. If you do not specify X, then
gcd uses the default variable determined by symvar.
Examples
Greatest Common Divisor of Four Integers
To find the greatest common divisor of three or more values, specify those values as a symbolic vector
or matrix.
Find the greatest common divisor of these four integers, specified as elements of a symbolic vector.
A =
[ 4420, -128, 8984, -488]
ans =
4
A =
[ 4420, -128]
[ 8984, -488]
7-705
7 Functions
ans =
4
syms x
gcd(x^3 - 3*x^2 + 3*x - 1, x^2 - 5*x + 4)
ans =
x - 1
Find the greatest common divisor of these multivariate polynomials. Because there are more than two
polynomials, specify them as elements of a symbolic vector.
syms x y
gcd([x^2*y + x^3, (x + y)^2, x^2 + x*y^2 + x*y + x + y^3 + y])
ans =
x + y
The greatest common divisor of rational numbers a1,a2,... is a number g, such that g/a1,g/
a2,... are integers, and gcd(g/a1,g/a2,...) = 1.
Find the greatest common divisor of these rational numbers, specified as elements of a symbolic
vector.
ans =
1/12
gcd computes the greatest common divisor of complex numbers over the Gaussian integers (complex
numbers with integer real and imaginary parts). It returns a complex number with a positive real part
and a nonnegative imaginary part.
ans =
5 + 10i
For vectors and matrices, gcd finds the greatest common divisors element-wise. Nonscalar
arguments must be the same size.
Find the greatest common divisors for the elements of these two matrices.
7-706
gcd
ans =
[ 3, 6]
[ 2, 32]
Find the greatest common divisors for the elements of matrix A and the value 200. Here, gcd
expands 200 into the 2-by-2 matrix with all elements equal to 200.
gcd(A,200)
ans =
[ 1, 2]
[ 2, 8]
A theorem in number theory states that the GCD of two numbers is the smallest positive linear
combination of those numbers. Show that the GCD is a positive linear combination for 64 and 44.
A = sym([64 44]);
[G,M] = gcd(A)
G =
4
M =
[ -2, 3]
isequal(G,sum(M.*A))
ans =
logical
1
Bézout Coefficients
Find the greatest common divisor and the Bézout coefficients of these polynomials. For multivariate
expressions, use the third input argument to specify the polynomial variable. When computing Bézout
coefficients, gcd ensures that the polynomial variable does not appear in their denominators.
Find the greatest common divisor and the Bézout coefficients of these polynomials with respect to
variable x.
G =
x + y
C =
1/y^2
D =
1/y - x/y^2
Find the greatest common divisor and the Bézout coefficients of the same polynomials with respect to
variable y.
7-707
7 Functions
G =
x + y
C =
1/x^2
D =
0
If you do not specify the polynomial variable, then the toolbox uses symvar to determine the variable.
G =
x + y
C =
1/y^2
D =
1/y - x/y^2
Find the greatest common divisor and a pair of Bézout coefficients for 30 and 56.
[G,C,D] = gcd(sym(30),56)
G =
2
C =
-13
D =
7
Rewrite Bézout's identity so that it looks more like the original equation. Do this by multiplying by 4.
Use == to verify that both sides of the equation are equal.
ans =
logical
1
x = C*4
y = D*4
x =
-52
7-708
gcd
y =
28
Input Arguments
A — Input value
number | symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic
vector | symbolic matrix
Input value, specified as a number, symbolic number, variable, expression, function, or a vector or
matrix of numbers, symbolic numbers, variables, expressions, or functions.
B — Input value
number | symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic
vector | symbolic matrix
Input value, specified as a number, symbolic number, variable, expression, function, or a vector or
matrix of numbers, symbolic numbers, variables, expressions, or functions.
X — Polynomial variable
symbolic variable
Output Arguments
G — Greatest common divisor
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Greatest common divisor, returned as a symbolic number, variable, expression, function, or a vector
or matrix of symbolic numbers, variables, expressions, or functions.
Linear combination of input that equals GCD of input, returned as a symbolic vector, matrix, or array.
Tips
• Calling gcd for numbers that are not symbolic objects invokes the MATLAB gcd function.
• The MATLAB gcd function does not accept rational or complex arguments. To find the greatest
common divisor of rational or complex numbers, convert these numbers to symbolic objects by
using sym, and then use gcd.
7-709
7 Functions
• Nonscalar arguments must be the same size. If one input argument is nonscalar, then gcd expands
the scalar into a vector or matrix of the same size as the nonscalar argument, with all elements
equal to the corresponding scalar.
Version History
Introduced in R2014b
See Also
lcm
7-710
ge
ge
Define greater than or equal to condition
Syntax
A >= B
ge(A,B)
Description
A >= B creates the condition greater than or equal.
Examples
Solve this equation involving x. The solver only returns solutions that are valid under the assumption
on x.
eqn = (x-1)*(x-2)*(x-3)*(x-4) == 0;
solve(eqn,x)
ans =
3
4
Find multiples of π/24 that satisfy the condition by using a for loop from 0 to π.
for i = 0:sym(pi/12):sym(pi)
if subs(cond,x,i)
disp(i)
end
end
pi/6
pi/4
pi/3
(5*pi)/12
7-711
7 Functions
pi/2
(7*pi)/12
(2*pi)/3
(3*pi)/4
(5*pi)/6
Input Arguments
A — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
B — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
Tips
• Calling >= or ge for non-symbolic A and B invokes the MATLAB ge function. This function returns
a logical array with elements set to logical 1 (true) where A is greater than or equal to B;
otherwise, it returns logical 0 (false).
• If both A and B are arrays, then these arrays must have the same dimensions. A >= B returns an
array of relations A(i,j,...) >= B(i,j,...)
• If one input is scalar and the other an array, then the scalar input is expanded into an array of the
same dimensions as the other array.
• The field of complex numbers is not an ordered field. MATLAB projects complex numbers in
relations to a real axis. For example, x >= i becomes x >= 0, and x >= 3+2*i becomes x >=
3.
Version History
Introduced in R2012a
See Also
eq | gt | isAlways | le | lt | ne
Topics
“Use Assumptions on Symbolic Variables” on page 1-41
7-712
gegenbauerC
gegenbauerC
Gegenbauer polynomials
Syntax
gegenbauerC(n,a,x)
Description
gegenbauerC(n,a,x) represents the nth-degree Gegenbauer (ultraspherical) polynomial on page 7-
716 with parameter a at the point x.
Examples
First Four Gegenbauer Polynomials
Find the first four Gegenbauer polynomials for the parameter a and variable x.
syms a x
gegenbauerC([0, 1, 2, 3], a, x)
ans =
[ 1, 2*a*x, (2*a^2 + 2*a)*x^2 - a,...
((4*a^3)/3 + 4*a^2 + (8*a)/3)*x^3 + (- 2*a^2 - 2*a)*x]
Find the value of the fifth-degree Gegenbauer polynomial for the parameter a = 1/3 at these points.
Because these numbers are not symbolic objects, gegenbauerC returns floating-point results.
gegenbauerC(5, 1/3, [1/6, 1/4, 1/3, 1/2, 2/3, 3/4])
ans =
0.1520 0.1911 0.1914 0.0672 -0.1483 -0.2188
Find the value of the fifth-degree Gegenbauer polynomial for the same numbers converted to
symbolic objects. For symbolic numbers, gegenbauerC returns exact symbolic results.
gegenbauerC(5, 1/3, sym([1/6, 1/4, 1/3, 1/2, 2/3, 3/4]))
ans =
[ 26929/177147, 4459/23328, 33908/177147, 49/729, -26264/177147, -7/32]
Find the value of the 500th-degree Gegenbauer polynomial for the parameter 4 at 1/3 and
vpa(1/3). Floating-point evaluation is numerically stable.
7-713
7 Functions
gegenbauerC(500, 4, 1/3)
gegenbauerC(500, 4, vpa(1/3))
ans =
-1.9161e+05
ans =
-191609.10250897532784888518393655
Now, find the symbolic polynomial C500 = gegenbauerC(500, 4, x), and substitute x =
vpa(1/3) into the result. This approach is numerically unstable.
syms x
C500 = gegenbauerC(500, 4, x);
subs(C500, x, vpa(1/3))
ans =
-8.0178726380235741521208852037291e+35
Approximate the polynomial coefficients by using vpa, and then substitute x = sym(1/3) into the
result. This approach is also numerically unstable.
subs(vpa(C500), x, sym(1/3))
ans =
-8.1125412405858470246887213923167e+36
syms x y
fplot(gegenbauerC(0:4,3,x))
axis([-1 1 -10 10])
grid on
ylabel('G_n^3(x)')
title('Gegenbauer polynomials')
legend('G_0^3(x)', 'G_1^3(x)', 'G_2^3(x)', 'G_3^3(x)', 'G_4^3(x)',...
'Location', 'Best')
7-714
gegenbauerC
Input Arguments
n — Degree of polynomial
nonnegative integer | symbolic variable | symbolic expression | symbolic function | vector | matrix
a — Parameter
number | symbolic number | symbolic variable | symbolic expression | symbolic function | vector |
matrix
x — Evaluation point
number | symbolic number | symbolic variable | symbolic expression | symbolic function | vector |
matrix
7-715
7 Functions
More About
Gegenbauer Polynomials
2x n + a − 1 n + 2a − 2
G 0, a, x = 1, G 1, a, x = 2ax, G n, a, x = G n − 1, a, x − G n − 2, a, x
n n
• For all real a > -1/2, Gegenbauer polynomials are orthogonal on the interval -1 ≤ x ≤ 1 with
1
a−
respect to the weight function w x = 1 − x2 2.
1 0 if n ≠ m
∫ G(n, a, x)G(m, a, x)
−1
1 − x2
a − 1/2
dx = π 21 − 2a Γ n + 2a
2
if n = m .
n! n + a Γ a
• Chebyshev polynomials of the first and second kinds are special cases of the Gegenbauer
polynomials.
1 n+a
lim G n, a, x if n ≠ 0
2a 0 a
T n, x =
lim G 0, a, x = 1 if n = 0
a 0
U n, x = G n, 1, x
• Legendre polynomials are also a special case of the Gegenbauer polynomials.
1
P n, x = G n, , x
2
Tips
• gegenbauerC returns floating-point results for numeric arguments that are not symbolic objects.
• gegenbauerC acts element-wise on nonscalar inputs.
• All nonscalar arguments must have the same size. If one or two input arguments are nonscalar,
then gegenbauerC expands the scalars into vectors or matrices of the same size as the nonscalar
arguments, with all elements equal to the corresponding scalar.
Version History
Introduced in R2014b
References
[1] Hochstrasser, U. W. “Orthogonal Polynomials.” Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New
York: Dover, 1972.
[2] Cohl, Howard S., and Connor MacKenzie. “Generalizations and Specializations of Generating
Functions for Jacobi, Gegenbauer, Chebyshev and Legendre Polynomials with Definite
Integrals.” Journal of Classical Analysis, no. 1 (2013): 17–33. https://doi.org/10.7153/
jca-03-02.
7-716
gegenbauerC
See Also
chebyshevT | chebyshevU | hermiteH | jacobiP | laguerreL | legendreP
7-717
7 Functions
gradient
Gradient vector of symbolic scalar field
Syntax
g = gradient(f,v)
g = gradient(f)
Description
g = gradient(f,v) returns the gradient vector on page 7-722 of symbolic scalar field f with
respect to vector v in Cartesian coordinates.
g = gradient(f) returns the gradient vector of the scalar field f with respect to a default vector
constructed from the symbolic variables in f.
Examples
The gradient of a scalar function f with respect to the vector v is the vector of the first partial
derivatives of f with respect to each element of v.
Find the gradient vector of f(x,y,z) with respect to vector [x,y,z]. The gradient is a vector with
these components.
syms x y z
f(x,y,z) = 2*y*z*sin(x) + 3*x*sin(z)*cos(y);
v = [x,y,z];
gradient(f,v)
ans(x, y, z) =
3 cos y sin z + 2 y z cos x
2 z sin x − 3 x sin y sin z
2 y sin x + 3 x cos y cos z
Find the gradient of a function f(x,y), and plot it as a quiver (velocity) plot.
Find the gradient vector of f(x,y) with respect to vector [x,y]. The gradient is vector g with these
components.
syms x y
f = -(sin(x) + sin(y))^2;
v = [x y];
g = gradient(f,v)
7-718
gradient
g =
−2 cos x sin x + sin y
−2 cos y sin x + sin y
Now plot the vector field defined by these components. MATLAB® provides the quiver plotting
function for this task. The function does not accept symbolic arguments. First, replace symbolic
variables in expressions for components of g with numeric values. Then use quiver.
[X,Y] = meshgrid(-1:.1:1,-1:.1:1);
G1 = subs(g(1),v,{X,Y});
G2 = subs(g(2),v,{X,Y});
quiver(X,Y,G1,G2)
Use symbolic matrix variables to define a matrix multiplication that returns a scalar.
syms X Y [3 1] matrix
A = Y.'*X
A = YT X
7-719
7 Functions
gX = Y
gY = gradient(A,Y)
gY = X
2 2 2
f (x) = sin (x1, 1) + sin (x1, 2) + sin (x1, 3)
Use a symbolic matrix variable to express the function f and its gradient in terms of the vector x.
syms x [1 3] matrix
f = sin(x)*sin(x).'
T
f = sin x sin x
g = gradient(f,x)
T
g = 2 cos x ⊙ I3 sin x
To express the gradient in terms of the elements of x, convert the result to a vector of symbolic scalar
variables using symmatrix2sym.
g = symmatrix2sym(g)
g =
2 cos x1, 1 sin x1, 1
2 cos x1, 2 sin x1, 2
2 cos x1, 3 sin x1, 3
Alternatively, you can convert f and x to symbolic expressions of scalar variables and use them as
inputs to the gradient function.
g = gradient(symmatrix2sym(f),symmatrix2sym(x))
g =
2 cos x1, 1 sin x1, 1
2 cos x1, 2 sin x1, 2
2 cos x1, 3 sin x1, 3
7-720
gradient
Create a 3-by-1 vector as a symbolic matrix variable X. Create a scalar field that is a function of X as
a symbolic matrix function A X , keeping the existing definition of X.
syms X [3 1] matrix
syms A(X) [1 1] matrix keepargs
Find the gradient of A X with respect to X. The gradient function returns an unevaluated formula.
gradA = gradient(A,X)
gradA(X) = ∇ X A X
Show that the divergence of the gradient of A X is equal to the Laplacian of A X , that is
∇ X ⋅ ∇ X A X = ΔX A X .
divOfGradA = divergence(gradA,X)
divOfGradA(X) = ΔX A X
lapA = laplacian(A,X)
lapA(X) = ΔX A X
curlOfGradA = curl(gradA,X)
curlOfGradA(X) = 03, 1
Input Arguments
f — Symbolic scalar field
symbolic expression | symbolic function | symbolic matrix variable | symbolic matrix function
Symbolic scalar field, specified as a symbolic expression, symbolic function, symbolic matrix variable,
or symbolic matrix function.
• If f is a function of symbolic scalar variables, where f is of type sym or symfun, then the vector v
must be of type sym or symfun.
• If f is a function of symbolic matrix variables, where f is of type symmatrix or symfunmatrix,
then the vector v must be of type symmatrix or symfunmatrix.
Vector with respect to which you find the gradient, specified as a vector of symbolic scalar variables,
symbolic function, symbolic matrix variable, or symbolic matrix function.
7-721
7 Functions
• If you do not specify v and f is a function of symbolic scalar variables, then, by default, gradient
constructs vector v from the symbolic scalar variables in f with the order of variables as defined
by symvar(f).
• If v is a symbolic matrix variable of type symmatrix, then v must have a size of 1-by-N or N-by-1.
• If v is scalar, then gradient(f,v) = diff(f,v).
• If v is an empty symbolic object, such as sym([]), then gradient returns an empty symbolic
object.
Limitations
• The gradient function does not support tensor derivatives. If the gradient is a tensor field or a
matrix rather than a vector, then the gradient function returns an error.
• Symbolic Math Toolbox currently does not support the dot or cross functions for symbolic matrix
variables and functions of type symmatrix and symfunmatrix. If vector calculus identities
involve dot or cross products, then the toolbox displays those identities in terms of other
supported functions instead. To see a list of all the functions that support symbolic matrix
variables and functions, use the commands methods symmatrix and methods symfunmatrix.
More About
Gradient Vector
The gradient vector of f(x) with respect to the vector x = x1, x2, …, xn is the vector of the first partial
derivatives of f.
∂f ∂f ∂f
∇x f (x) = , , …,
∂x1 ∂x2 ∂xn
Version History
Introduced in R2011b
The gradient function accepts symbolic matrix functions of type symfunmatrix as input
arguments. For example, see “Find Vector Calculus Identities Involving Gradients” on page 7-720.
The gradient function accepts symbolic matrix variables of type symmatrix as input arguments.
For examples, see “Gradient of Matrix Multiplication” on page 7-719 and “Gradient of Multivariable
Function” on page 7-720.
See Also
curl | divergence | diff | hessian | jacobian | laplacian | potential | quiver |
vectorPotential
7-722
gbasis
gbasis
Reduced Groebner basis
Syntax
gbasis(poly)
gbasis(poly,vars)
gbasis( ___ ,'MonomialOrder',MonomialOrder)
Description
gbasis(poly) returns the Groebner basis of the vector of polynomials poly. By default, gbasis
finds independent variables in poly by using symvar, and uses the monomial ordering
degreeInverseLexicographic.
Examples
Calculate the Groebner basis of the polynomials x^2-y^2 and x^2+y. By default, gbasis finds the
independent variables by using symvar.
syms x y
p = [x^2-y^2, x^2+y];
gbasis(p)
ans =
[ x^2 + y, y^2 + y]
Compute the Groebner basis of the polynomials a*y+x^2*y+a and a*x^2+y with the independent
variables [x y].
syms x y a
p = [a*y + x^2*y + a, a*x^2 + y];
vars = [x y];
grobnerBasis = gbasis(p,vars)
7-723
7 Functions
grobnerBasis =
[ a*x^2 + y, - y^2/a + a*y + a]
Find the Groebner basis of the polynomials y*z^2+1 and y^2*x^2-y-z^3 with lexicographic
monomial order.
syms x y z
p = [y*z^2 + 1, y^2*x^2 - y - z^3];
grobnerBasis = gbasis(p,'MonomialOrder','lexicographic')
grobnerBasis =
[ x^2 - z^7 + z^2, y*z^2 + 1]
grobnerBasis =
[ x^2*y^2 - y - z^3, y*z^2 + 1, x^2*y^3 - y^2 + z]
Input Arguments
poly — Polynomials
vector of symbolic expressions
Monomial order, specified as the comma-separated pair of 'MonomialOrder' and one of the values
'degreeInverseLexicographic', 'degreeLexicographic', or 'lexicographic'. If vars is
specified, then monomials are sorted with respect to the order of variables in vars.
7-724
gbasis
Version History
Introduced in R2018a
See Also
eliminate | solve
Topics
“Solve Algebraic Equations” on page 3-3
“Solve System of Linear Equations” on page 3-30
7-725
7 Functions
gt
Define greater than relation
Syntax
A > B
gt(A,B)
Description
A > B creates a greater than relation.
Examples
Set and Use Assumption Using Greater Than
Use assume and the relational operator > to set the assumption that x is greater than 3:
syms x
assume(x > 3)
Solve this equation. The solver takes into account the assumption on variable x, and therefore returns
this solution.
ans =
4
syms x
cond = abs(sin(x)) + abs(cos(x)) > 7/5;
for i = 0:sym(pi/24):sym(pi)
if subs(cond, x, i)
disp(i)
end
end
Use the for loop with step π/24 to find angles from 0 to π that satisfy that condition:
(5*pi)/24
pi/4
(7*pi)/24
(17*pi)/24
(3*pi)/4
(19*pi)/24
7-726
gt
Input Arguments
A — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
B — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
Tips
• Calling > or gt for non-symbolic A and B invokes the MATLAB gt function. This function returns a
logical array with elements set to logical 1 (true) where A is greater than B; otherwise, it
returns logical 0 (false).
• If both A and B are arrays, then these arrays must have the same dimensions. A > B returns an
array of relations A(i,j,...) > B(i,j,...)
• If one input is scalar and the other an array, then the scalar input is expanded into an array of the
same dimensions as the other array. In other words, if A is a variable (for example, x), and B is an
m-by-n matrix, then A is expanded into m-by-n matrix of elements, each set to x.
• The field of complex numbers is not an ordered field. MATLAB projects complex numbers in
relations to a real axis. For example, x > i becomes x > 0, and x > 3 + 2*i becomes x > 3.
Version History
Introduced in R2012a
See Also
eq | ge | isAlways | le | lt | ne
Topics
“Use Assumptions on Symbolic Variables” on page 1-41
7-727
7 Functions
harmonic
Harmonic function (harmonic number)
Syntax
harmonic(x)
Description
harmonic(x) returns the harmonic function on page 7-731 of x. For integer values of x,
harmonic(x) generates harmonic numbers.
Examples
Generate Harmonic Numbers
ans =
[ 1, 3/2, 11/6, 25/12, 137/60, 49/20, 363/140, 761/280, 7129/2520, 7381/2520]
Find the harmonic function for these numbers. Since these are not symbolic objects, you get floating-
point results.
harmonic([2 i 13/3])
ans =
1.5000 + 0.0000i 0.6719 + 1.0767i 2.1545 + 0.0000i
Find the harmonic function symbolically by converting the numbers to symbolic objects.
y = harmonic(sym([2 i 13/3]))
y =
[ 3/2, harmonic(1i), 8571/1820 - (pi*3^(1/2))/6 - (3*log(3))/2]
If the denominator of x is 2, 3, 4, or 6, and |x| < 500, then the result is expressed in terms of pi and
log.
ans =
[ 1.5, 0.67186598552400983787839057280431...
+ 1.07667404746858117413405079475i,...
2.1545225442213858782694336751358]
For |x| > 1000, harmonic returns the function call as it is. Use vpa to force harmonic to evaluate
the function call.
7-728
harmonic
harmonic(sym(1001))
vpa(harmonic(sym(1001)))
ans =
harmonic(1001)
ans =
7.4864698615493459116575172053329
ans =
0 1 Inf Inf NaN
syms f(x)
f(x) = exp(x) + tan(x);
y = harmonic(f)
y(x) =
harmonic(exp(x) + tan(x))
syms x
V = [x sin(x) 3*i];
M = [exp(i*x) 2; -6 Inf];
harmonic(V)
harmonic(M)
ans =
[ harmonic(x), harmonic(sin(x)), harmonic(3i)]
ans =
[ harmonic(exp(x*1i)), 3/2]
[ Inf, Inf]
syms x
fplot(harmonic(x),[-5 5])
grid on
7-729
7 Functions
syms x
diff(harmonic(x^2+1),x,2)
ans =
2*psi(1, x^2 + 2) + 4*x^2*psi(2, x^2 + 2)
syms x
limit(harmonic(x),Inf)
limit((x+1)*harmonic(x),-1)
ans =
Inf
ans =
-1
Use taylor to expand the harmonic function in terms of the Taylor series.
7-730
harmonic
syms x
taylor(harmonic(x))
ans =
(pi^6*x^5)/945 - zeta(5)*x^4 + (pi^4*x^3)/90...
- zeta(3)*x^2 + (pi^2*x)/6
syms x
expand(harmonic(2*x+3))
ans =
harmonic(x + 1/2)/2 + log(2) + harmonic(x)/2 - 1/(2*(x + 1/2))...
+ 1/(2*x + 1) + 1/(2*x + 2) + 1/(2*x + 3)
Input Arguments
x — Input
number | vector | matrix | multidimensional array | symbolic variable | symbolic expression | symbolic
function | symbolic vector | symbolic matrix | symbolic N-D array
More About
Harmonic Function
x 1
harmonic x = Σ
k = 1k
It is also defined as
harmonic x = Ψ x + 1 + γ
Algorithms
The harmonic function is defined for all complex arguments z except for negative integers -1, -2,...
where a singularity occurs.
If x has denominator 1, 2, 3, 4, or 6, then an explicit result is computed and returned. For other
1
rational numbers, harmonic uses the functional equation harmonic x + 1 = harmonic x + to
x
obtain a result with an argument x from the interval [0, 1].
7-731
7 Functions
1
expand expands harmonic using the equations harmonic x + 1 = harmonic x + ,
x
1
harmonic −x = harmonic x − + πcot πx , and the Gauss multiplication formula for
x
harmonic(kx), where k is an integer.
−1
harmonic = − 2ln 2
2
2 3 3
harmonic − = − ln 3 − π
3 2 6
1 3 3
harmonic − = − ln 3 + π
3 2 6
−3 π
harmonic = − 3ln 2 −
4 2
−1 π
harmonic = − 3ln 2 +
4 2
−5 3 3
harmonic = − 2ln 2 − ln 3 − π
6 2 2
−1 3 3
harmonic = − 2ln 2 − ln 3 + π
6 2 2
harmonic 0 = 0
1
harmonic = 2 − 2ln 2
2
1 3 3
harmonic = 3 − ln 3 − π
3 2 6
2 3 3 3
harmonic = − ln 3 + π
3 2 2 6
1 π
harmonic = 4 − 3ln 2 −
4 2
3 4 π
harmonic = − 3ln 2 +
4 3 2
1 3 3
harmonic = 6 − 2ln 2 − ln 3 − π
6 2 2
5 6 3 3
harmonic = − 2ln 2 − ln 3 + π
6 5 2 2
harmonic 1 = 1
harmonic ∞ = ∞
harmonic −∞ = NaN
7-732
harmonic
Version History
Introduced in R2014a
See Also
beta | nchoosek | factorial | gamma | gammaln | zeta
7-733
7 Functions
has
Check if expression contains particular subexpression
Syntax
has(expr,subexpr)
Description
has(expr,subexpr) returns logical 1 (true) if expr contains subexpr. Otherwise, it returns logical
0 (false).
• If expr is an array, has(expr,subexpr) returns an array of the same size as expr. The returned
array contains logical 1s (true) where the elements of expr contain subexpr, and logical 0s
(false) where they do not.
• If subexpr is an array, has(expr,subexpr) checks if expr contains any element of subexpr.
Examples
Check If Expression Contains Particular Subexpression
Use the has function to check if an expression contains a particular variable or subexpression.
syms x y z
has(x + y + z, z)
ans =
logical
1
has(x + y, z)
ans =
logical
0
Check if x + y + z contains the following subexpressions. Note that has finds the subexpression x
+ z even though the terms x and z do not appear next to each other in the expression.
has(x + y + z, x + y)
has(x + y + z, y + z)
has(x + y + z, x + z)
ans =
logical
1
ans =
logical
1
ans =
7-734
has
logical
1
Check if the expression (x + 1)^2 contains x^2. Although (x + 1)^2 is mathematically equivalent
to the expression x^2 + 2*x + 1, the result is a logical 0 because has typically does not transform
expressions to different forms when testing for subexpressions.
ans =
logical
0
Expand the expression and then call has to check if the result contains x^2. Because expand((x +
1)^2) transforms the original expression to x^2 + 2*x + 1, the has function finds the
subexpression x^2 and returns logical 1.
ans =
logical
1
If an expression contains one or more of the specified subexpressions, has returns logical 1.
syms x
has(sin(x) + cos(x) + x^2, [tan(x), cot(x), sin(x), exp(x)])
ans =
logical
1
If an expression does not contain any of the specified subexpressions, has returns logical 0.
syms x
has(sin(x) + cos(x) + x^2, [tan(x), cot(x), exp(x)])
ans =
logical
0
Using has, find those elements of a symbolic matrix that contain a particular subexpression.
syms x y
M = [sin(x)*sin(y), cos(x*y) + 1; cos(x)*tan(x), 2*sin(x)^2]
M =
[ sin(x)*sin(y), cos(x*y) + 1]
[ cos(x)*tan(x), 2*sin(x)^2]
7-735
7 Functions
Use has to check which elements of M contain sin(x). The result is a matrix of the same size as M,
with 1s and 0s as its elements. For the elements of M containing the specified expression, has
returns logical 1s. For the elements that do not contain that subexpression, has returns logical 0s.
T = has(M, sin(x))
T =
2×2 logical array
1 0
0 1
Return only the elements that contain sin(x) and replace all other elements with 0 by multiplying M
by T elementwise.
M.*T
ans =
[ sin(x)*sin(y), 0]
[ 0, 2*sin(x)^2]
any(has(M(:), sin(x)))
ans =
logical
1
any(has(M(:), cos(y)))
ans =
logical
0
Using has, find those elements of a symbolic vector that contain any of the specified subexpressions.
syms x y z
T = has([x + 1, cos(y) + 1, y + z, 2*x*cos(y)], [x, cos(y)])
T =
1×4 logical array
1 1 0 1
Return only the elements of the original vector that contain x or cos(y) or both, and replace all
other elements with 0 by multiplying the original vector by T elementwise.
[x + 1, cos(y) + 1, y + z, 2*x*cos(y)].*T
ans =
[ x + 1, cos(y) + 1, 0, 2*x*cos(y)]
7-736
has
ans =
cos(x) + sin(x)
Check if f and f(x) contain sin(x). In both cases has checks if the expression sin(x) + cos(x)
contains sin(x).
has(f, sin(x))
has(f(x), sin(x))
ans =
logical
1
ans =
logical
1
Check if f(x^2) contains f. For these arguments, has returns logical 0 (false) because it does not
check if the expression f(x^2) contains the letter f. This call is equivalent to has(f(x^2),
formula(f)), which, in turn, resolves to has(cos(x^2) + sin(x^2), cos(x) + sin(x)).
has(f(x^2), f)
ans =
logical
0
Check for calls to a particular function by specifying the function name as the second argument.
Check for calls to any one of multiple functions by specifying the multiple functions as a cell array of
character vectors.
Integrate tan(x^7). Determine if the integration is successful by checking the result for calls to int.
Because has finds the int function and returns logical 1 (true), the integration is not successful.
syms x
f = int(tan(x^7), x);
has(f, 'int')
ans =
logical
1
Check if the solution to a differential equation contains calls to either sin or cos by specifying the
second argument as {'sin','cos'}. The has function returns logical 0 (false), which means the
solution does not contain calls to either sin or cos.
syms y(x) a
sol = dsolve(diff(y,x) == a*y);
has(sol, {'sin' 'cos'})
7-737
7 Functions
ans =
logical
0
Input Arguments
expr — Expression to test
symbolic expression | symbolic function | symbolic equation | symbolic inequality | symbolic vector |
symbolic matrix | symbolic array
Expression to test, specified as a symbolic expression, function, equation, or inequality. Also it can be
a vector, matrix, or array of symbolic expressions, functions, equations, and inequalities.
Tips
• has does not transform or simplify expressions. This is why it does not find subexpressions like
x^2 in expressions like (x + 1)^2. However, in some cases has might find that an expression or
subexpression can be represented in a form other than its original form. For example, has finds
that the expression -x - 1 can be represented as -(x + 1). Thus, the call has(-x - 1, x +
1) returns 1.
• If expr is an empty symbolic array, has returns an empty logical array of the same size as expr.
Version History
Introduced in R2015b
See Also
subs | subexpr | times
7-738
hasSymType
hasSymType
Determine whether symbolic object contains specific type
Syntax
TF = hasSymType(symObj,type)
TF = hasSymType(symObj,funType,vars)
Description
TF = hasSymType(symObj,type) returns logical 1 (true) if the symbolic object symObj contains
a subobject of type type, and logical 0 (false) otherwise. The input type must be a case-sensitive
string scalar or character vector, and it can include a logical expression.
You can set the function type funType to 'symfunOf' or 'symfunDependingOn'. For example,
syms f(x); hasSymType(f,'symfunOf',x) returns logical 1.
Examples
syms x;
expr = sym('1/2') + 2*pi + x
expr =
1
x+2π+
2
TF = hasSymType(expr,'variable')
TF = logical
1
TF = hasSymType(expr,'constant')
TF = logical
1
7-739
7 Functions
TF = hasSymType(expr,'integer')
TF = logical
1
TF = hasSymType(expr,'integer | real')
TF = logical
1
TF = hasSymType(expr,'complex')
TF = logical
0
Determine whether a symbolic equation contains a symbolic function or operator of a specific type.
syms f(x) n
eq = f(x^n) + int(f(x),x) + vpa(2.7) == 1i
eq =
f xn + ∫f x dx + 2.7 = i
TF = hasSymType(eq,'f')
TF = logical
1
TF = hasSymType(eq,'symfun')
TF = logical
1
TF = hasSymType(eq,'int')
7-740
hasSymType
TF = logical
1
TF = logical
1
g(x, y, z) = π + x y + f x, y, z
TF = logical
0
TF = logical
1
TF = logical
1
Input Arguments
symObj — Symbolic objects
symbolic expressions | symbolic functions | symbolic variables | symbolic numbers | symbolic units
Symbolic objects, specified as symbolic expressions, symbolic functions, symbolic variables, symbolic
numbers, or symbolic units.
7-741
7 Functions
Symbolic types, specified as a case-sensitive scalar string or character vector. The input type can
contain a logical expression. The value options follow.
7-742
hasSymType
• 'symfunOf' checks whether symObj contains an unassigned symbolic function that depends on
the exact sequence of variables specified by the array vars. For example, syms f(x,y);
hasSymType(f,'symfunOf',[x y]) returns logical 1.
• 'symfunDependingOn' checks whether symObj contains an unassigned symbolic function that
has a dependency on the variables specified by the array vars. For example, syms f(x,y);
hasSymType(f,'symfunDependingOn',[y x]) returns logical 1.
7-743
7 Functions
Tips
• To check whether a symbolic expression contains a particular subexpression, use the has
function.
Version History
Introduced in R2019a
See Also
has | symFunType | isSymType | symType | sym | syms | mapSymType | findSymType
7-744
heaviside
heaviside
Heaviside step function
Syntax
H = heaviside(x)
Description
H = heaviside(x) evaluates the Heaviside step function (also known as the unit step function) at
x. The Heaviside function is a discontinuous function that returns 0 for x < 0, 1/2 for x = 0, and 1
for x > 0.
Examples
The heaviside function returns 0, 1/2, or 1 depending on the argument value. If the argument is a
floating-point number (not a symbolic object), then heaviside returns floating-point results.
Evaluate the Heaviside step function for a symbolic input sym(-3). The function heaviside(x)
returns 0 for x < 0.
H = heaviside(sym(-3))
H = 0
Evaluate the Heaviside step function for a symbolic input sym(3). The function heaviside(x)
returns 1 for x > 0.
H = heaviside(sym(3))
H = 1
Evaluate the Heaviside step function for a symbolic input sym(0). The function heaviside(x)
returns 1/2 for x = 0.
H = heaviside(sym(0))
H =
1
2
H = heaviside(0)
H = 0.5000
7-745
7 Functions
syms x
assume(x < 0)
H = heaviside(x)
H = 0
syms x
syms x
fplot(heaviside(x), [-2, 2])
7-746
heaviside
Evaluate the Heaviside function for a symbolic matrix. When the input argument is a matrix,
heaviside computes the Heaviside function for each element.
syms x
H = heaviside(sym([-1 0; 1/2 x]))
H =
1
0
2
1 heaviside x
Find the first derivative of the Heaviside function. The first derivative of the Heaviside function is the
Dirac delta function.
7-747
7 Functions
syms x
diff_H = diff(heaviside(x),x)
diff_H = δ x
∞
Evaluate the integral ∫−∞ e−xH x dx.
syms x
int_H = int(exp(-x)*heaviside(x),x,-Inf,Inf)
int_H = 1
syms x
F = fourier(heaviside(x))
F =
i
πδ w −
w
syms x
L = laplace(heaviside(x))
L =
1
s
H = heaviside(sym(0))
H =
1
2
Other common values for the Heaviside function at the origin are 0 and 1. To change the value of
heaviside at the origin, use sympref to set the value of the 'HeavisideAtOrigin' preference.
Store the previous parameter value returned by sympref, so that you can restore it later.
oldparam = sympref('HeavisideAtOrigin',1);
H = heaviside(sym(0))
H = 1
7-748
heaviside
The preferences set by sympref persist throughout your current and future MATLAB® sessions. To
restore the previous value of heaviside at the origin, use the value stored in oldparam.
sympref('HeavisideAtOrigin',oldparam);
Alternatively, you can restore the default value of 'HeavisideAtOrigin' by using the 'default'
setting.
sympref('HeavisideAtOrigin','default');
Input Arguments
x — Input
number | symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic
vector | symbolic matrix
Input, specified as a number, symbolic number, variable, expression, function, vector, or matrix.
Version History
Introduced before R2006a
See Also
dirac | laplace | sympref
7-749
7 Functions
hermiteForm
Hermite form of matrix
Syntax
H = hermiteForm(A)
[U,H] = hermiteForm(A)
___ = hermiteForm(A,var)
Description
H = hermiteForm(A) returns the Hermite normal form on page 7-753 of a matrix A. The elements
of A must be integers or polynomials in a variable determined by symvar(A,1). The Hermite form H
is an upper triangular matrix.
[U,H] = hermiteForm(A) returns the Hermite normal form of A and a unimodular transformation
matrix U, such that H = U*A.
___ = hermiteForm(A,var) assumes that the elements of A are univariate polynomials in the
specified variable var. If A contains other variables, hermiteForm treats those variables as symbolic
parameters.
You can use the input argument var in any of the previous syntaxes.
If A does not contain var, then hermiteForm(A) and hermiteForm(A,var) return different
results.
Examples
Hermite Form for Matrix of Integers
A = sym(invhilb(5))
H = hermiteForm(A)
A =
[ 25, -300, 1050, -1400, 630]
[ -300, 4800, -18900, 26880, -12600]
[ 1050, -18900, 79380, -117600, 56700]
[ -1400, 26880, -117600, 179200, -88200]
[ 630, -12600, 56700, -88200, 44100]
H =
[ 5, 0, -210, -280, 630]
[ 0, 60, 0, 0, 0]
[ 0, 0, 420, 0, 0]
[ 0, 0, 0, 840, 0]
[ 0, 0, 0, 0, 2520]
7-750
hermiteForm
Create a 2-by-2 matrix, the elements of which are polynomials in the variable x.
syms x
A = [x^2 + 3, (2*x - 1)^2; (x + 2)^2, 3*x^2 + 5]
A =
[ x^2 + 3, (2*x - 1)^2]
[ (x + 2)^2, 3*x^2 + 5]
H = hermiteForm(A)
H =
[ 1, (4*x^3)/49 + (47*x^2)/49 - (76*x)/49 + 20/49]
[ 0, x^4 + 12*x^3 - 13*x^2 - 12*x - 11]
syms x y
A = [2/x + y, x^2 - y^2; 3*sin(x) + y, x]
A =
[ y + 2/x, x^2 - y^2]
[ y + 3*sin(x), x]
Find the Hermite form of this matrix. If you do not specify the polynomial variable, hermiteForm
uses symvar(A,1) and thus determines that the polynomial variable is x. Because 3*sin(x) + y is
not a polynomial in x, hermiteForm throws an error.
H = hermiteForm(A)
Find the Hermite form of A specifying that all elements of A are polynomials in the variable y.
H = hermiteForm(A,y)
H =
[ 1, (x*y^2)/(3*x*sin(x) - 2) + (x*(x - x^2))/(3*x*sin(x) - 2)]
[ 0, 3*y^2*sin(x) - 3*x^2*sin(x) + y^3 + y*(- x^2 + x) + 2]
Find the Hermite form and the corresponding transformation matrix for an inverse Hilbert matrix.
A = sym(invhilb(3));
[U,H] = hermiteForm(A)
U =
[ 13, 9, 7]
[ 6, 4, 3]
[ 20, 15, 12]
7-751
7 Functions
H =
[ 3, 0, 30]
[ 0, 12, 0]
[ 0, 0, 60]
ans =
3×3 logical array
1 1 1
1 1 1
1 1 1
Find the Hermite form and the corresponding transformation matrix for a matrix of polynomials.
syms x y
A = [2*(x - y), 3*(x^2 - y^2);
4*(x^3 - y^3), 5*(x^4 - y^4)];
[U,H] = hermiteForm(A,x)
U =
[ 1/2, 0]
[ 2*x^2 + 2*x*y + 2*y^2, -1]
H =
[ x - y, (3*x^2)/2 - (3*y^2)/2]
[ 0, x^4 + 6*x^3*y - 6*x*y^3 - y^4]
ans =
2×2 logical array
1 1
1 1
If a matrix does not contain a particular variable, and you call hermiteForm specifying that variable
as the second argument, then the result differs from what you get without specifying that variable.
For example, create a matrix that does not contain any variables.
A = [9 -36 30; -36 192 -180; 30 -180 180]
A =
9 -36 30
-36 192 -180
30 -180 180
ans =
1 0 0
7-752
hermiteForm
0 1 0
0 0 1
Call hermiteForm without specifying variables. In this case, hermiteForm treats A as a matrix of
integers.
hermiteForm(A)
ans =
3 0 30
0 12 0
0 0 60
Input Arguments
A — Input matrix
symbolic matrix
Input matrix, specified as a symbolic matrix, the elements of which are integers or univariate
polynomials. If the elements of A contain more than one variable, use the var argument to specify a
polynomial variable, and treat all other variables as symbolic parameters. If A is multivariate, and you
do not specify var, then hermiteForm uses symvar(A,1) to determine a polynomial variable.
Output Arguments
H — Hermite normal form of input matrix
symbolic matrix
Hermite normal form of input matrix, returned as a symbolic matrix. The Hermite form of a matrix is
an upper triangular matrix.
U — Transformation matrix
unimodular symbolic matrix
Transformation matrix, returned as a unimodular symbolic matrix. If elements of A are integers, then
elements of U are also integers, and det(U) = 1 or det(U) = -1. If elements of A are polynomials,
then elements of U are univariate polynomials, and det(U) is a constant.
More About
Hermite Normal Form
For any square n-by-n matrix A with integer coefficients, there exists an n-by-n matrix H and an n-by-
n unimodular matrix U, such that A*U = H, where H is the Hermite normal form of A. A unimodular
matrix is a real square matrix, such that its determinant equals 1 or -1. If A is a matrix of
polynomials, then the determinant of U is a constant.
7-753
7 Functions
hermiteForm returns the Hermite normal form of a nonsingular integer square matrix A as an upper
Hjj Hjj
triangular matrix H, such that H j j ≥ 0 and − < Hi j ≤ for j > i. If A is not a square matrix or a
2 2
singular matrix, the matrix H is simply an upper triangular matrix.
Version History
Introduced in R2015b
See Also
jordan | smithForm
7-754
hermiteH
hermiteH
Hermite polynomials
Syntax
hermiteH(n,x)
Description
hermiteH(n,x) represents the nth-degree Hermite polynomial at the point x.
Examples
ans =
[ 1, 2*x, 4*x^2 - 2, 8*x^3 - 12*x, 16*x^4 - 48*x^2 + 12]
Depending on whether the input is numeric or symbolic, hermiteH returns numeric or exact
symbolic results.
Find the value of the fifth-degree Hermite polynomial at 1/3. Because the input is numeric,
hermiteH returns numeric results.
hermiteH(5,1/3)
ans =
34.2058
Find the same result for exact symbolic input. hermiteH returns an exact symbolic result.
hermiteH(5,sym(1/3))
ans =
8312/243
7-755
7 Functions
ylabel('H_n(x)')
legend('H_0(x)', 'H_1(x)', 'H_2(x)', 'H_3(x)', 'H_4(x)', 'Location', 'Best')
title('Hermite polynomials')
Input Arguments
n — Degree of polynomial
nonnegative integer | symbolic variable | symbolic expression | symbolic function | vector | matrix
x — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
7-756
hermiteH
More About
Hermite Polynomials
H 0, x = 1, H 1, x = 2x, H n, x = 2xH n − 1, x − 2 n − 1 H n − 2, x
∫
∞ 2 2 n
Hn(x) e−x dx = 2 πn!
−∞
Tips
• hermiteH returns floating-point results for numeric arguments that are not symbolic objects.
• hermiteH acts element-wise on nonscalar inputs.
• At least one input argument must be a scalar or both arguments must be vectors or matrices of
the same size. If one input argument is a scalar and the other one is a vector or a matrix, then
hermiteH expands the scalar into a vector or matrix of the same size as the other argument with
all elements equal to that scalar.
Version History
Introduced in R2014b
References
[1] Hochstrasser, U. W. “Orthogonal Polynomials.” Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New
York: Dover, 1972.
See Also
chebyshevT | chebyshevU | gegenbauerC | jacobiP | laguerreL | legendreP
7-757
7 Functions
hessian
Hessian matrix of symbolic scalar function
Syntax
hessian(f,v)
Description
hessian(f,v) finds the Hessian matrix on page 7-759 of the symbolic scalar function f with
respect to vector v in Cartesian coordinates.
If you do not specify v, then hessian(f) finds the Hessian matrix of the scalar function f with
respect to a vector constructed from all symbolic variables found in f. The order of variables in this
vector is defined by symvar.
Examples
Find Hessian Matrix of Scalar Function
Find the Hessian matrix of a function by using hessian. Then find the Hessian matrix of the same
function as the Jacobian of the gradient of the function.
syms x y z
f = x*y + 2*z*x;
hessian(f,[x,y,z])
ans =
[ 0, 1, 2]
[ 1, 0, 0]
[ 2, 0, 0]
Alternatively, compute the Hessian matrix of this function as the Jacobian of the gradient of that
function:
jacobian(gradient(f))
ans =
[ 0, 1, 2]
[ 1, 0, 0]
[ 2, 0, 0]
Input Arguments
f — Scalar function
symbolic expression | symbolic function
7-758
hessian
Vector with respect to which you find Hessian matrix, specified as a symbolic vector. By default, v is a
vector constructed from all symbolic variables found in f. The order of variables in this vector is
defined by symvar.
If v is an empty symbolic object, such as sym([]), then hessian returns an empty symbolic object.
More About
Hessian Matrix
The Hessian matrix of f(x) is the square matrix of the second partial derivatives of f(x).
∂2 f ∂2 f ∂2 f
⋯
∂x12 ∂x1 ∂x2 ∂x1 ∂xn
∂2 f ∂2 f ∂2 f
⋯
H(f ) = ∂x2 ∂x1 ∂x22 ∂x2 ∂xn
⋮ ⋮ ⋱ ⋮
∂2 f ∂2 f ∂2 f
⋯
∂xn ∂x1 ∂xn ∂x2 ∂xn2
Version History
Introduced in R2011b
See Also
curl | divergence | diff | gradient | jacobian | laplacian | potential | vectorPotential
7-759
7 Functions
horner
Horner nested polynomial representation
Syntax
horner(p)
horner(p,var)
Description
horner(p) returns the Horner form of the polynomial p.
Examples
ans =
x*(x*(x - 6) + 11) - 6
ans =
2 - x*(11*b*y + x*(y - a*x*y))
horner(p,y)
ans =
2 - y*(- a*x^3 + x^2 + 11*b*x)
Input Arguments
p — Polynomial
symbolic expression | symbolic function | array of symbolic expressions | array of symbolic functions
var — Variable
symbolic variable | array of symbolic variables
7-760
horner
Version History
Introduced before R2006a
See Also
collect | combine | expand | factor | numden | rewrite | simplify | simplifyFraction
7-761
7 Functions
horzcat
Concatenate symbolic arrays horizontally
Syntax
horzcat(A1,...,AN)
[A1 ... AN]
Description
horzcat(A1,...,AN) horizontally concatenates the symbolic arrays A1,...,AN. For vectors and
matrices, all inputs must have the same number of rows. For multidimensional arrays, horzcat
concatenates inputs along the second dimension. The remaining dimensions must match.
Examples
Concatenate Two Symbolic Matrices Horizontally
A = sym('a%d%d',[2 2])
B = sym('b%d%d',[2 2])
A =
[ a11, a12]
[ a21, a22]
B =
[ b11, b12]
[ b21, b22]
Concatenate A and B.
horzcat(A,B)
ans =
[ a11, a12, b11, b12]
[ a21, a22, b21, b22]
[A B]
ans =
[ a11, a12, b11, b12]
[ a21, a22, b21, b22]
A = sym('a%d',[3 1]);
B = sym('b%d%d',[3 3]);
7-762
horzcat
C = sym('c%d%d',[3 2]);
horzcat(C,A,B)
ans =
[ c11, c12, a1, b11, b12, b13]
[ c21, c22, a2, b21, b22, b23]
[ c31, c32, a3, b31, b32, b33]
[C A B]
ans =
[ c11, c12, a1, b11, b12, b13]
[ c21, c22, a2, b21, b22, b23]
[ c31, c32, a3, b31, b32, b33]
A = sym('a%d%d',[2 3]);
A(:,:,2) = -A
B = sym('b%d%d', [2 2]);
B(:,:,2) = -B
A(:,:,1) =
[ a11, a12, a13]
[ a21, a22, a23]
A(:,:,2) =
[ -a11, -a12, -a13]
[ -a21, -a22, -a23]
B(:,:,1) =
[ b11, b12]
[ b21, b22]
B(:,:,2) =
[ -b11, -b12]
[ -b21, -b22]
horzcat(A,B)
ans(:,:,1) =
[ a11, a12, a13, b11, b12]
[ a21, a22, a23, b21, b22]
ans(:,:,2) =
[ -a11, -a12, -a13, -b11, -b12]
[ -a21, -a22, -a23, -b21, -b22]
[A B]
ans(:,:,1) =
[ a11, a12, a13, b11, b12]
[ a21, a22, a23, b21, b22]
ans(:,:,2) =
7-763
7 Functions
Input Arguments
A1,...,AN — Input arrays
symbolic scalar variable | symbolic matrix variable | symbolic matrix function | symbolic vector |
symbolic matrix | symbolic multidimensional array
Input arrays, specified as symbolic scalar variables, matrix variables, matrix functions, or vectors,
matrices, or multidimensional arrays of symbolic scalar variables.
Version History
Introduced before R2006a
See Also
cat | vertcat
7-764
htrans
htrans
Hilbert transform
Syntax
H = htrans(f)
H = htrans(f,transVar)
H = htrans(f,var,transVar)
Description
H = htrans(f) returns the Hilbert transform of symbolic function f. By default, the independent
variable is t and the transformation variable is x.
H = htrans(f,var,transVar) uses the independent variable var and the transformation variable
transVar instead of t and x, respectively.
• If all input arguments are arrays of the same size, then htrans acts element-wise.
• If one input is a scalar and the others are arrays of the same size, then htrans expands the scalar
into an array of the same size.
• If f is an array of symbolic expressions with different independent variables, then var must be a
symbolic array with elements corresponding to the independent variables.
Examples
Compute the Hilbert transform of sin(t). By default, the transform returns a function of x.
syms t;
f = sin(t);
H = htrans(f)
H = −cos x
Compute the Hilbert transform of the sinc(x) function, which is equal to sin(pi*x)/(pi*x).
Express the result as a function of u.
H(u) =
7-765
7 Functions
cos π u 1
u
−u
−
π
fplot(f(x),[0 6])
hold on
fplot(H(u),[0 6])
legend('sinc(x)','H(u)')
syms A x t u;
assume([x t],'real')
y = A*sin(2*pi*10*t + 5*x)
y = A sin 5 x + 20 π t
Apply a –90-degree phase shift to the positive frequency component using the Hilbert transform.
Specify the independent variable as t and the transformation variable as u.
H = htrans(y,t,u)
7-766
htrans
H = − A cos 5 x + 20 π u
Now create a complex signal with negative frequency. Apply a 90-degree phase shift to the negative
frequency component using the Hilbert transform.
z = A*exp(-1i*10*t)
z = A e−10 t i
H = htrans(z)
H = A e−10 x i i
1 dϕ(s)
f instant(s) = ,
2π ds
InstantFreq(s) = diff(angle(F(s)),s)/(2*pi);
assume(s,'real')
simplify(InstantFreq(s))
ans = 75
Input Arguments
f — Input
symbolic expression | symbolic function | symbolic vector | symbolic matrix
Input, specified as a symbolic expression, symbolic function, symbolic vector, or symbolic matrix.
Independent variable, specified as a symbolic variable, symbolic vector, or symbolic matrix. This
variable is usually in the time domain. If you do not specify the variable, then htrans uses t by
7-767
7 Functions
default. If f does not contain t, then htrans uses the function symvar to determine the independent
variable.
Transformation variable, specified as a symbolic variable, symbolic vector, or symbolic matrix. This
variable is in the same domain as var. If you do not specify the variable, then htrans uses x by
default. If x is the independent variable of f, then htrans uses the transformation variable v.
Output Arguments
H — Hilbert transform of f
symbolic expression | symbolic function | symbolic vector | symbolic matrix
Hilbert transform or harmonic conjugate of the input function f. The output H is a function of the
variable specified by transVar.
When htrans cannot transform the input function, it returns an unevaluated call. To return the
original expression, apply the inverse Hilbert transform to the output by using ihtrans.
More About
Hilbert Transform
The Hilbert transform H = H(x) of the expression f = f(t) with respect to the variable t at point x is
∞
1
H x = p.v.
π ∫ xf −t t dt .
−∞
Here, p.v. represents the Cauchy principal value of the integral. The function f(t) can be complex, but
t and x must be real.
Tips
• To compute the inverse Hilbert transform, use ihtrans. The Hilbert transform of a function is
equal to the negative of its inverse Hilbert transform.
• For a signal in the time domain, the Hilbert transform applies a –90-degree phase shift to positive
frequencies of the corresponding Fourier components. It also applies a 90-degree phase shift to
negative frequencies.
• For a real-valued signal a, the Hilbert transform b = htrans(a) returns its harmonic conjugate
b. The real signal a = real(z) and its Hilbert transform b = imag(z) form the analytic signal
z = a + 1i*b.
Version History
Introduced in R2019a
7-768
htrans
See Also
ihtrans | fourier | ifourier | laplace | ilaplace
7-769
7 Functions
hurwitzZeta
Hurwitz zeta function
Syntax
Z = hurwitzZeta(s,a)
Z = hurwitzZeta(n,s,a)
Description
Z = hurwitzZeta(s,a) evaluates the Hurwitz zeta function on page 7-773 for the numeric or
symbolic inputs s and a. The Hurwitz zeta function is defined only if s is not 1 and a is neither 0 nor a
negative integer.
Examples
Z = hurwitzZeta(0,1)
Z = -0.5000
Compute the symbolic output of hurwitzZeta by converting the inputs to symbolic numbers using
sym.
symZ =
1 π2
−
2 6
Use the vpa function to approximate symbolic results with the default 32 digits of precision.
valZ = vpa(symZ)
Special Values
For certain parameter values, symbolic evaluation of the Hurwitz zeta function returns special values
that are related to other symbolic functions.
For a = 1, the Hurwitz zeta function returns the Riemann zeta function zeta.
7-770
hurwitzZeta
syms s a;
Z = hurwitzZeta(s,1)
Z = ζs
For s = 2, the Hurwitz zeta function returns the first derivative of the digamma function psi.
Z = hurwitzZeta(2,a)
Z = ψ′ a
For nonpositive integers s, the Hurwitz zeta function returns polynomials in terms of a.
Z = hurwitzZeta(0,a)
Z =
1
−a
2
Z = hurwitzZeta(-1,a)
Z =
a2 a 1
− + −
2 2 12
Z = hurwitzZeta(-2,a)
Z =
a3 a2 a
− + −
3 2 6
Find the first derivative of the Hurwitz zeta function with respect to the variable s.
syms s a
Z = hurwitzZeta(1,s,a)
Z = ζ′ s, a
symZ =
log 2 log π
− −
2 2
Use the diff function to find the first derivative of the Hurwitz zeta function with respect to a.
Z = diff(hurwitzZeta(s,a),a)
Z = −s ζ s + 1, a
7-771
7 Functions
Plot the Hurwitz zeta function for s within the interval [-20 10], given a = 0.7.
fplot(@(s) hurwitzZeta(s,0.7),[-20 10])
axis([-20 10 -40 35]);
Input Arguments
s — Input
number | array | symbolic number | symbolic variable | symbolic function | symbolic expression |
symbolic array
Input, specified as a number, array, symbolic number, symbolic variable, symbolic function, symbolic
expression, or symbolic array. The Hurwitz zeta function is defined only for values of s not equal to 1.
Data Types: single | double | sym | symfun
Complex Number Support: Yes
a — Input
number | array | symbolic number | symbolic variable | symbolic function | symbolic expression |
symbolic array
Input, specified as a number, array, symbolic number, symbolic variable, symbolic function, symbolic
expression, or symbolic array. The Hurwitz zeta function is defined only for values of a not equal to 0
or a negative integer.
7-772
hurwitzZeta
n — Order of derivative
nonnegative integer
More About
Hurwitz Zeta Function
∞
1
ζ s, a = ∑ s
.
k=0 k+a
The summation series converges only when Re(s) > 1 and a is neither 0 nor a negative integer.
Analytic continuation extends the definition of the function to the entire complex plane, except for a
simple pole at s = 1.
Tips
• Floating-point evaluation of the Hurwitz zeta function can be slow for complex arguments or high-
precision numbers. To increase the computational speed, you can reduce the floating-point
precision by using the vpa and digits functions. For more information, see “Increase Speed by
Reducing Precision” on page 3-321.
• The Hurwitz zeta function is related to other special functions. For example, it can be expressed in
terms of the polylogarithm Lis(z) and the gamma function Γ(z):
Γs
ζ 1 − s, a = s
e−iπs/2 Lis e2πia + eiπs/2 Lis e−2πia .
2π
Here, Re(s) > 0 and Im(a) > 0, or Re(s) > 1 and Im(a) = 0.
Version History
Introduced in R2019a
References
[1] Olver, F. W. J., A. B. Olde Daalhuis, D. W. Lozier, B. I. Schneider, R. F. Boisvert, C. W. Clark, B. R.
Miller, and B. V. Saunders, eds., Chapter 25. Zeta and Related Functions, NIST Digital Library
of Mathematical Functions, Release 1.0.20, Sept. 15, 2018.
See Also
bernoulli | gamma | psi | polylog | zeta
7-773
7 Functions
hypergeom
Hypergeometric function
Syntax
hypergeom(a,b,z)
Description
hypergeom(a,b,z) represents the generalized hypergeometric function on page 7-776.
Examples
Hypergeometric Function for Numeric and Symbolic Arguments
Depending on whether the input is floating point or symbolic, hypergeom returns floating point or
symbolic results.
Compute the hypergeometric function for these numbers. Because these numbers are floating point,
hypergeom returns floating-point results.
A =
-1.2174 - 0.8330i 1.2091 + 0.0000i -0.2028 + 0.2405i
Return exact symbolic results by converting at least one of the inputs to symbolic form by using sym.
For most symbolic (exact) inputs, hypergeom returns unresolved symbolic calls.
symA =
[ hypergeom([1, 2], 5/2, 2), hypergeom(1/3, [2, 3], pi), hypergeom([1/2, 1], 1/3, 3i)]
vpa(symA)
ans =
[ - 1.2174189301051728850455150601879 - 0.83304055090469367131547768563638i,...
1.2090631887094273193917339575087,...
- 0.20275169745081962937527290365593 + 0.24050134226872040357481317881983i]
Show that hypergeom returns special values for certain input values.
7-774
hypergeom
syms a b c d x
hypergeom([], [], x)
ans =
exp(x)
ans =
exp(x)
hypergeom(a, [], x)
ans =
1/(1 - x)^a
syms a b c d
hypergeom([a b], [c d], 0)
ans =
1
If, after cancelling identical parameters in the first two arguments, the list of upper parameters
contains 0, the resulting hypergeometric function is constant with the value 1. For details, see
“Algorithms” on page 7-777.
ans =
1
If, after canceling identical parameters in the first two arguments, the upper parameters contain a
negative integer larger than the largest negative integer in the lower parameters, the hypergeometric
function is a polynomial.
ans =
(3*x^2)/5 - 2*x + 1
Hypergeometric functions reduce to other special functions for certain input values.
hypergeom([1], [a], x)
hypergeom([a], [a, b], x)
ans =
(exp(x/2)*whittakerM(1 - a/2, a/2 - 1/2, -x))/(-x)^(a/2)
ans =
x^(1/2 - b/2)*gamma(b)*besseli(b - 1, 2*x^(1/2))
Many symbolic functions, such as diff and taylor, handle expressions containing hypergeom.
7-775
7 Functions
syms a b c d x
diff(1/x*hypergeom([a b],[c d],x), x)
ans =
(a*b*hypergeom([a + 1, b + 1], [c + 1, d + 1], x))/(c*d*x)...
- hypergeom([a, b], [c, d], x)/x^2
taylor(hypergeom([1 2],3,x), x)
ans =
(2*x^5)/7 + x^4/3 + (2*x^3)/5 + x^2/2 + (2*x)/3 + 1
Input Arguments
a — Upper parameters of hypergeometric function
number | vector | symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector
z — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
More About
Generalized Hypergeometric Function
∞ a1 n… a j n… ap n zn
pF q a; b; z = pFq a1, …, a j, …, ap; b1, …, bk, …, bq; z = ∑ b1 n… bk n… bq n!
.
n=0 n
7-776
hypergeom
∞
1 zk
0F q ; b; z = ∑ b1 b2 k… bq k!
k=0 k k
∞
zk
pF 0 a; ; z = ∑ a1 k a2 k… ap k k!
k=0
∞
zk
0F 0 ;;z = ∑ k!
= ez .
k=0
Pochhammer Symbol
Γ x+n
x n = .
Γx
Algorithms
The hypergeometric function is
∞ a1 n… a j n… ap n zn
pF q a; b; z = pFq a1, …, a j, …, ap; b1, …, bk, …, bq; z = ∑ b1 n… bk n… bq n!
.
n=0 n
• If any bk is a nonpositive integer such that bk > aj where aj is also a nonpositive integer,
because division by 0 occurs
• If any bk is a nonpositive integer and no aj is a nonpositive integer
• The function has reduced order when upper and lower parameter values are equal and cancel. If r
values of the upper and lower parameters are equal (that is, a = [a1,…,ap - r, c1,…,cr], b = [b1,…,bq -
r, c1,…,cr]), then the order (p, q) of pFq(a;b;z) is reduced to (p - r, q - r):
p − r Fq − r a1, …, ap − r ; b1, …, bq − r ; z
∂
δ δ + b − 1 − z(δ + a) U z = 0, δ = z .
∂z
7-777
7 Functions
Here, (δ + a) represents
p
∏ δ + ai .
i=1
And (δ + b) represents
q
∏ δ + bj .
j=1
Thus, the order of this differential equation is max(p, q + 1), and the hypergeometric function is
only one of its solutions. If p < q + 1, this differential equation has a regular singularity at z = 0
and an irregular singularity at z = ∞. If p = q + 1, the points z = 0, z = 1, and z = ∞ are regular
singularities, which explains the convergence properties of the hypergeometric series.
• The hypergeometric function has these special values:
Version History
Introduced before R2006a
References
[1] Oberhettinger, F. “Hypergeometric Functions.” Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New
York: Dover, 1972.
[2] Luke, Y.L. "The Special Functions and Their Approximations", Vol. 1, Academic Press, New York,
1969.
[3] Prudnikov, A.P., Yu.A. Brychkov, and O.I. Marichev, "Integrals and Series", Vol. 3: More Special
Functions, Gordon and Breach, 1990.
See Also
kummerU | meijerG | whittakerM | whittakerW
7-778
ifourier
ifourier
Inverse Fourier transform
Syntax
ifourier(F)
ifourier(F,transVar)
ifourier(F,var,transVar)
Description
ifourier(F) returns the “Inverse Fourier Transform” on page 7-782 of F. By default, the
independent variable is w and the transformation variable is x. If F does not contain w, ifourier
uses the function symvar.
ifourier(F,var,transVar) uses the independent variable var and the transformation variable
transVar instead of w and x, respectively.
Examples
Compute the inverse Fourier transform of exp(-w^2/4). By default, the inverse transform is in
terms of x.
syms w
F = exp(-w^2/4);
ifourier(F)
ans =
exp(-x^2)/pi^(1/2)
Compute the inverse Fourier transform of exp(-w^2-a^2). By default, the independent and
transformation variables are w and x, respectively.
syms a w t
F = exp(-w^2-a^2);
ifourier(F)
ans =
exp(- a^2 - x^2/4)/(2*pi^(1/2))
Specify the transformation variable as t. If you specify only one variable, that variable is the
transformation variable. The independent variable is still w.
7-779
7 Functions
ifourier(F,t)
ans =
exp(- a^2 - t^2/4)/(2*pi^(1/2))
Compute the inverse Fourier transform of expressions in terms of Dirac and Heaviside functions.
syms t w
ifourier(dirac(w), w, t)
ans =
1/(2*pi)
f = 2*exp(-abs(w))-1;
ifourier(f,w,t)
ans =
-(2*pi*dirac(t) - 4/(t^2 + 1))/(2*pi)
f = exp(-w)*heaviside(w);
ifourier(f,w,t)
ans =
-1/(2*pi*(- 1 + t*1i))
Compute the inverse Fourier transform of this expression using the default values of the Fourier
parameters c = 1, s = -1. For details, see “Inverse Fourier Transform” on page 7-782.
syms t w
f = -(sqrt(sym(pi))*w*exp(-w^2/4)*i)/2;
ifourier(f,w,t)
ans =
t*exp(-t^2)
Change the Fourier parameters to c = 1, s = 1 by using sympref, and compute the transform
again. The sign of the result changes.
sympref('FourierParameters',[1 1]);
ifourier(f,w,t)
ans =
-t*exp(-t^2)
7-780
ifourier
ans =
-2*pi*t*exp(-t^2)
Preferences set by sympref persist through your current and future MATLAB sessions. Restore the
default values of c and s by setting FourierParameters to 'default'.
sympref('FourierParameters','default');
Find the inverse Fourier transform of the matrix M. Specify the independent and transformation
variables for each matrix entry by using matrices of the same size. When the arguments are
nonscalars, ifourier acts on them element-wise.
syms a b c d w x y z
M = [exp(x), 1; sin(y), i*z];
vars = [w, x; y, z];
transVars = [a, b; c, d];
ifourier(M,vars,transVars)
ans =
[ exp(x)*dirac(a), dirac(b)]
[ (dirac(c - 1)*1i)/2 - (dirac(c + 1)*1i)/2, dirac(1, d)]
If ifourier is called with both scalar and nonscalar arguments, then it expands the scalars to match
the nonscalars by using scalar expansion. Nonscalar arguments must be the same size.
ifourier(x,vars,transVars)
ans =
[ x*dirac(a), -dirac(1, b)*1i]
[ x*dirac(c), x*dirac(d)]
If ifourier cannot transform the input, then it returns an unevaluated call to fourier.
syms F(w) t
f = ifourier(F,w,t)
f =
fourier(F(w), w, -t)/(2*pi)
Input Arguments
F — Input
symbolic expression | symbolic function | symbolic vector | symbolic matrix
7-781
7 Functions
Independent variable, specified as a symbolic variable. This variable is often called the "frequency
variable." If you do not specify the variable, then ifourier uses w. If F does not contain w, then
ifourier uses the function symvar to determine the independent variable.
More About
Inverse Fourier Transform
The inverse Fourier transform of the expression F = F(w) with respect to the variable w at the point x
is
∞
f x =
s
2πc ∫Fwe
−∞
−iswxdw .
c and s are parameters of the inverse Fourier transform. The ifourier function uses c = 1, s = –1.
Tips
• If any argument is an array, then ifourier acts element-wise on all elements of the array.
• If the first argument contains a symbolic function, then the second argument must be a scalar.
• The toolbox computes the inverse Fourier transform via the Fourier transform:
1
if ourier F, w, t = f ourier F, w, − t .
2π
If ifourier cannot find an explicit representation of the inverse Fourier transform, then it
returns results in terms of the Fourier transform.
• To compute the Fourier transform, use fourier.
Version History
Introduced before R2006a
References
[1] Oberhettinger, F. "Tables of Fourier Transforms and Fourier Transforms of Distributions."
Springer, 1990.
See Also
fourier | ilaplace | iztrans | laplace | sympref | ztrans
7-782
ifourier
Topics
“Fourier and Inverse Fourier Transforms” on page 3-184
7-783
7 Functions
igamma
Incomplete gamma function
Syntax
g = igamma(nu,z)
Description
g = igamma(nu,z) returns the upper incomplete gamma function.
igamma uses the definition of the upper incomplete gamma function on page 7-786. However, the
default MATLAB gammainc function uses the definition of the regularized lower incomplete gamma
function on page 7-786, where gammainc(z,nu) = 1 - igamma(nu,z)/gamma(nu). The order
of input arguments differs between these functions.
Examples
Compute the upper incomplete gamma function for these numbers. Because these numbers are not
symbolic objects, you get floating-point results.
g = 1×4
Compute the upper incomplete gamma function for the numbers converted to symbolic objects.
symg = −ei −1 e− 2 2 2 + 4 Γ π, e 0
vpag = vpa(symg)
7-784
igamma
igamma is implemented according to the definition of the upper incomplete gamma function. If you
want to compute the lower incomplete gamma function, convert results returned by igamma as
follows.
Compute the upper incomplete gamma function for these arguments using igamma.
z = [-5/3, -1/2, 0, 1/3];
gupper = igamma(1/3,z)
Subtract these results out of the gamma function to obtain the lower incomplete gamma function.
glower = gamma(1/3) - gupper
For comparison, you can also calculate the regularized lower incomplete gamma function by using
the MATLAB gammainc function. The regularized definition differs by the gamma function factor.
glower2 = gammainc(z,1/3)*gamma(1/3)
Because gammainc does not accept complex arguments, if one or both arguments are complex
numbers, use igamma to compute the regularized lower incomplete gamma function.
gcomplex = 1 - igamma(1/2,1i)/gamma(1/2)
Input Arguments
nu — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
z — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
7-785
7 Functions
More About
Upper Incomplete Gamma Function
The following integral defines the regularized lower incomplete gamma function:
z
γ z, η =
1
Γ(η) ∫t
0
η − 1 −t
e dt,
∫
∞ η−1
Γη = t e−tdt .
0
Tips
• The MATLAB gammainc function does not accept complex arguments. For complex arguments,
use igamma.
• gammainc(z,nu) = 1 - igamma(nu,z)/gamma(nu) represents the regularized lower
incomplete gamma function in terms of the upper incomplete gamma function.
• igamma(nu,z) = gamma(nu)*(1 - gammainc(z,nu)) represents the upper incomplete
gamma function in terms of the regularized lower incomplete gamma function.
• gammainc(z,nu,"upper") = igamma(nu,z)/gamma(nu).
Version History
Introduced in R2014a
See Also
gammainc | gamma | ei | erfc | factorial | int
7-786
ihtrans
ihtrans
Inverse Hilbert transform
Syntax
f = ihtrans(H)
f = ihtrans(H,transVar)
f = ihtrans(H,var,transVar)
Description
f = ihtrans(H) returns the inverse Hilbert transform of symbolic function H. By default, the
independent variable is x and the transformation variable is t.
• If all input arguments are arrays of the same size, then ihtrans acts element-wise.
• If one input is a scalar and the others are arrays of the same size, then ihtrans expands the
scalar into an array of the same size.
• If f is an array of symbolic expressions with different independent variables, then var must be a
symbolic array with elements corresponding to the independent variables.
Examples
Compute the inverse Hilbert transform of cos(x). By default, the inverse transform returns a
function of t.
syms x;
f = cos(x);
H = ihtrans(f)
H = −sin t
Compute the inverse Hilbert transform of the sinc(t) function, which is equal to sin(pi*t)/
(pi*t). Express the result as a function of s.
7-787
7 Functions
f(s) =
cos π s 1
s
−s
π
H = A sin 5 x + 20 π t
Apply a 90-degree phase shift to the positive frequency component using the inverse Hilbert
transform. Specify the independent variable as x and the transformation variable as u, respectively.
f = ihtrans(H,x,u)
7-788
ihtrans
f = A cos 5 u + 20 π t
Now create a complex signal with negative frequency. Apply a –90-degree phase shift to the negative
frequency component using the inverse Hilbert transform.
Z = A*exp(-1i*10*t)
Z = A e−10 t i
f = ihtrans(Z)
f = − A e−10 u i i
Create a real-valued signal f (s) with two frequency components, 60 Hz and 90 Hz.
Calculate the corresponding analytic signal F(t) using the inverse Hilbert transform.
1 dϕ(t)
f instant(t) = ,
2π dt
InstantFreq(t) = diff(angle(F(t)),t)/(2*pi);
assume(t,'real')
simplify(InstantFreq(t))
ans = 75
Input Arguments
H — Input
symbolic expression | symbolic function | symbolic vector | symbolic matrix
Input, specified as a symbolic expression, symbolic function, symbolic vector, or symbolic matrix.
Independent variable, specified as a symbolic variable, symbolic vector, or symbolic matrix. This
variable is usually in the time domain. If you do not specify the variable, then ihtrans uses x by
7-789
7 Functions
default. If H does not contain x, then ihtrans uses the function symvar to determine the
independent variable.
Transformation variable, specified as a symbolic variable, symbolic vector, or symbolic matrix. This
variable is in the same domain as var. If you do not specify the variable, then ihtrans uses t by
default. If t is the independent variable of H, then ihtrans uses the transformation variable u.
Output Arguments
f — Inverse Hilbert transform of H
symbolic expression | symbolic function | symbolic vector | symbolic matrix
Inverse Hilbert transform of the input function H. The output f is a function of the variable specified
by transVar.
When ihtrans cannot transform the input function, it returns an unevaluated call. To return the
original expression, apply the Hilbert transform to the output by using htrans.
More About
Inverse Hilbert Transform
The inverse Hilbert transform f = f(t) of the expression H = H(x) with respect to the variable x at
point t is
∞
1
f t = p.v.
π
−∞
∫ xH−xt dx .
Here, p.v. represents the Cauchy principal value of the integral. The function H(x) can be complex,
but x and t must be real.
Tips
• To compute the Hilbert transform, use htrans. The inverse Hilbert transform of a function is
equal to the negative of its Hilbert transform.
• For a signal in the time domain, the inverse Hilbert transform applies a 90-degree phase shift to
negative frequencies of the corresponding Fourier components. It also applies a –90-degree phase
shift to positive frequencies.
• A real-valued signal b is the harmonic conjugate of its inverse Hilbert transform a =
ihtrans(b). The inverse Hilbert transform a = real(z) and the signal b = imag(z) form the
analytic signal z = a + 1i*b.
Version History
Introduced in R2019a
7-790
ihtrans
See Also
htrans | fourier | ifourier | laplace | ilaplace
7-791
7 Functions
ilaplace
Inverse Laplace transform
Syntax
f = ilaplace(F)
f = ilaplace(F,transVar)
f = ilaplace(F,var,transVar)
Description
f = ilaplace(F) returns the “Inverse Laplace Transform” on page 7-795 of F. By default, the
independent variable is s and the transformation variable is t. If F does not contain s, ilaplace
uses the function symvar.
Examples
Compute the inverse Laplace transform of 1/s^2. By default, the inverse transform is in terms of t.
syms s
F = 1/s^2;
f = ilaplace(F)
f = t
Compute the inverse Laplace transform of 1/(s-a)^2. By default, the independent and
transformation variables are s and t, respectively.
syms a s
F = 1/(s-a)^2;
f = ilaplace(F)
f = t ea t
Specify the transformation variable as x. If you specify only one variable, that variable is the
transformation variable. The independent variable is still s.
syms x
f = ilaplace(F,x)
7-792
ilaplace
f = x ea x
Specify both the independent and transformation variables as a and x in the second and third
arguments, respectively.
f = ilaplace(F,a,x)
f = x es x
Compute the following inverse Laplace transforms that involve the Dirac and Heaviside functions.
syms s t
f1 = ilaplace(1,s,t)
f1 = δ t
F = exp(-2*s)/(s^2+1);
f2 = ilaplace(F,s,t)
f2 = heaviside t − 2 sin t − 2
Create two functions f t = heaviside t and g t = exp −t . Find the Laplace transforms of the two
functions by using laplace. Because the Laplace transform is defined as a unilateral or one-sided
transform, it only applies to the signals in the region t ≥ 0.
syms t positive
f(t) = heaviside(t);
g(t) = exp(-t);
F = laplace(f);
G = laplace(g);
Find the inverse Laplace transform of the product of the Laplace transforms of the two functions.
h = ilaplace(F*G)
h = 1 − e−t
According to the convolution theorem for causal signals, the inverse Laplace transform of this
t
product is equal to the convolution of the two functions, which is the integral ∫0 f τ g t − τ dτ with
t ≥ 0. Find this integral.
syms tau
conv_fg = int(f(tau)*g(t-tau),tau,0,t)
conv_fg = 1 − e−t
Show that the inverse Laplace transform of the product of the Laplace transforms is equal to the
convolution, where h is equal to conv_fg.
7-793
7 Functions
isAlways(h == conv_fg)
ans = logical
1
Find the inverse Laplace transform of the matrix M. Specify the independent and transformation
variables for each matrix entry by using matrices of the same size. When the arguments are
nonscalars, ilaplace acts on them element-wise.
syms a b c d w x y z
M = [exp(x) 1; sin(y) 1i*z];
vars = [w x; y z];
transVars = [a b; c d];
f = ilaplace(M,vars,transVars)
f =
ex δ a δb
ilaplace sin y , y, c δ′ d i
If ilaplace is called with both scalar and nonscalar arguments, then it expands the scalars to match
the nonscalars by using scalar expansion. Nonscalar arguments must be the same size.
syms w x y z a b c d
f = ilaplace(x,vars,transVars)
f =
xδ a δ′ b
xδ c xδ d
Compute the Inverse Laplace transform of symbolic functions. When the first argument contains
symbolic functions, then the second argument must be a scalar.
f = ilaplace ex , x, a δ′ b
If ilaplace cannot compute the inverse transform, then it returns an unevaluated call to ilaplace.
7-794
ilaplace
syms F(s) t
F(s) = exp(s);
f(t) = ilaplace(F,s,t)
f(t) = ilaplace es , s, t
F(s) = laplace(f,t,s)
F(s) = es
Input Arguments
F — Input
symbolic expression | symbolic function | symbolic vector | symbolic matrix
Independent variable, specified as a symbolic variable, expression, vector, or matrix. This variable is
often called the "complex frequency variable." If you do not specify the variable, then ilaplace uses
s. If F does not contain s, then ilaplace uses the function symvar to determine the independent
variable.
More About
Inverse Laplace Transform
The inverse Laplace transform of F(s) is the signal f(t) such that laplace(f(t),t,s) is F(s).
The inverse Laplace transform ilaplace(F(s),s,t) may only match the original signal f(t) for t
≥ 0.
Tips
• If any argument is an array, then ilaplace acts element-wise on all elements of the array.
• If the first argument contains a symbolic function, then the second argument must be a scalar.
• To compute the direct Laplace transform, use laplace.
• For a signal f(t), computing the Laplace transform (laplace) and then the inverse Laplace
transform (ilaplace) of the result may not return the original signal for t < 0. This is because
the definition of laplace uses the unilateral transform on page 7-953. This definition assumes
that the signal f(t) is only defined for all real numbers t ≥ 0. Therefore, the inverse result is not
7-795
7 Functions
unique for t < 0 and it may not match the original signal for negative t. One way to retrieve the
original signal is to multiply the result of ilaplace by a Heaviside step function. For example,
both of these code blocks:
syms t;
laplace(sin(t))
and
syms t;
laplace(sin(t)*heaviside(t))
syms s;
ilaplace(1/(s^2 + 1))
Version History
Introduced before R2006a
See Also
fourier | ifourier | iztrans | laplace | ztrans | rewrite
Topics
“Solve Differential Equations of RLC Circuit Using Laplace Transform” on page 3-188
7-796
imag
imag
Imaginary part of complex number
Syntax
imag(z)
Description
imag(z) returns the imaginary part of z. If z is a matrix, imag acts elementwise on z.
Examples
Compute Imaginary Part of Numeric Inputs
Find the imaginary parts of these numbers. Because these numbers are not symbolic objects, you get
floating-point results.
ans =
1.5000 74.2032 4.5747
ans =
[ 3/2, -6/5, sinh(5)]
imag(2*exp(1 + sym(i)))
ans =
2*exp(1)*sin(1)
In general, imag cannot extract the entire imaginary parts from symbolic expressions containing
variables. However, imag can rewrite and sometimes simplify the input expression:
syms a x y
imag(a + 2)
imag(x + y*i)
ans =
imag(a)
ans =
imag(x) + real(y)
7-797
7 Functions
If you assign numeric values to these variables or if you specify that these variables are real, imag
can extract the imaginary part of the expression:
syms a
a = 5 + 3*i;
imag(a + 2)
ans =
3
syms x y real
imag(x + y*i)
ans =
y
Clear the assumption that x and y are real by recreating them using syms:
syms x y
syms x
A = [-1 + sym(i), sinh(x); exp(10 + sym(7)*i), exp(sym(pi)*i)];
imag(A)
ans =
[ 1, imag(sinh(x))]
[ exp(10)*sin(7), 0]
Input Arguments
z — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
Tips
• Calling imag for a number that is not a symbolic object invokes the MATLAB imag function.
Alternatives
You can compute the imaginary part of z via the conjugate: imag(z)= (z - conj(z))/2i.
Version History
Introduced before R2006a
7-798
imag
See Also
conj | in | real | sign | signIm
7-799
7 Functions
in
Numeric type of symbolic input
Syntax
in(x,type)
Description
in(x,type) expresses the logical condition that x is of the specified type.
Examples
Express Condition on Symbolic Variable or Expression
The syntax in(x,type) expresses the condition that x is of the specified type. Express the
condition that x is of type Real.
syms x
cond = in(x,'real')
cond =
in(x, 'real')
Evaluate the condition using isAlways. Because isAlways cannot determine the condition, it issues
a warning and returns logical 0 (false).
isAlways(cond)
ans =
logical
0
Assume the condition cond is true using assume, and evaluate the condition again. The isAlways
function returns logical 1 (true) indicating that the condition is true.
assume(cond)
isAlways(cond)
ans =
logical
1
syms x
7-800
in
Solve the equation sin(x) == 0 using solve. Set the option ReturnConditions to true to return
conditions on the solution. The solve function uses in to express the conditions.
syms x
[solx, params, conds] = solve(sin(x) == 0,'ReturnConditions',true)
solx =
pi*k
params =
k
conds =
in(k, 'integer')
The solution is pi*k with parameter k under the condition in(k,'integer'). You can use this
condition to set an assumption for further computations. Under the assumption, solve returns only
integer values of k.
assume(conds)
k = solve(solx > 0, solx < 5*pi, params)
k =
1
2
3
4
To find the solutions corresponding to these values of k, use subs to substitute for k in solx.
subs(solx,k)
ans =
pi
2*pi
3*pi
4*pi
M =
[ 61/50, 1i, x]
[ sin(y), 3*x, 0]
[ Inf, 3^(1/2), 22/7]
Use isAlways to test if the elements of M are rational numbers. The in function acts on M element-
by-element. Note that isAlways returns logical 0 (false) for statements that cannot be decided and
issues a warning for those statements.
in(M,'rational')
7-801
7 Functions
ans =
[ in(61/50, 'rational'), in(1i, 'rational'), in(x, 'rational')]
[ in(sin(y), 'rational'), in(3*x, 'rational'), in(0, 'rational')]
[ in(Inf, 'rational'), in(3^(1/2), 'rational'), in(22/7, 'rational')]
isAlways(in(M,'rational'))
Input Arguments
x — Input
symbolic number | symbolic vector | symbolic matrix | symbolic multidimensional array | symbolic
expression | symbolic function
Input, specified as a symbolic number, vector, matrix, multidimensional array, expression, or function.
Version History
Introduced in R2014b
See Also
assume | assumeAlso | false | imag | isalways | isequal | isequaln | isfinite | isinf |
piecewise | real | true
7-802
incidenceMatrix
incidenceMatrix
Find incidence matrix of system of equations
Syntax
A = incidenceMatrix(eqs,vars)
Description
A = incidenceMatrix(eqs,vars) for m equations eqs and n variables vars returns an m-by-n
matrix A. Here, A(i,j) = 1 if eqs(i) contains vars(j) or any derivative of vars(j). All other
elements of A are 0s.
Examples
Incidence Matrix
Create the following symbolic vector eqs containing five symbolic differential equations.
Create the vector of variables. Here, c1 and c3 are symbolic parameters (not variables) of the
system.
Find the incidence matrix A for the equations eqs and with respect to the variables vars.
A = incidenceMatrix(eqs, vars)
A =
1 1 0 0 0
1 1 1 0 0
0 1 1 1 0
0 0 1 1 1
0 0 0 1 1
Input Arguments
eqs — Equations
vector of symbolic equations | vector of symbolic expressions
7-803
7 Functions
vars — Variables
vector of symbolic variables | vector of symbolic functions | vector of symbolic function calls
Variables, specified as a vector of symbolic variables, symbolic functions, or function calls, such as
x(t).
Output Arguments
A — Incidence matrix
matrix of double-precision values
Version History
Introduced in R2014b
See Also
daeFunction | decic | findDecoupledBlocks | isLowIndexDAE | massMatrixForm |
odeFunction | reduceDAEIndex | reduceDAEToODE | reduceDifferentialOrder |
reduceRedundancies | spy
7-804
int
int
Definite and indefinite integrals
Syntax
F = int(expr)
F = int(expr,var)
F = int(expr,a,b)
F = int(expr,var,a,b)
Description
F = int(expr) computes the indefinite integral of expr. int uses the default integration variable
determined by symvar(expr,1). If expr is a constant, then the default integration variable is x.
F = int(expr,var) computes the indefinite integral of expr with respect to the symbolic scalar
variable var.
F = int(expr,a,b) computes the definite integral of expr from a to b. int uses the default
integration variable determined by symvar(expr,1). If expr is a constant, then the default
integration variable is x.
F = int(expr,var,a,b) computes the definite integral of expr with respect to the symbolic
scalar variable var from a to b.
F = int( ___ ,Name,Value) specifies additional options using one or more Name,Value pair
arguments. For example, 'IgnoreAnalyticConstraints',true specifies that int applies
additional simplifications to the integrand.
Examples
syms x
expr = -2*x/(1+x^2)^2;
F = int(expr)
F =
7-805
7 Functions
1
x2 + 1
Find the indefinite integrals of the multivariate expression with respect to the variables x and z.
Fx = int(f,x)
Fx(x, z) =
x2
2 z2 + 1
Fz = int(f,z)
Fz(x, z) = x atan z
If you do not specify the integration variable, then int uses the first variable returned by symvar as
the integration variable.
var = symvar(f,1)
var = x
F = int(f)
F(x, z) =
x2
2 z2 + 1
F =
1
4
2
F = cos t
7-806
int
When int cannot compute the value of a definite integral, numerically approximate the integral by
using vpa.
syms x
f = cos(x)/sqrt(1 + x^2);
Fint = int(f,x,[0 10])
Fint =
10 cos x
∫0 x2 + 1
dx
Fvpa = vpa(Fint)
Fvpa = 0.37570628299079723478493405557162
To approximate integrals directly, use vpaintegral instead of vpa. The vpaintegral function is
faster and provides control over integration tolerances.
Fvpaint = vpaintegral(f,x,[0 10])
Fvpaint = 0.375706
M =
et ea t
sin t cos t
F =
ea t
et
a
−cos t sin t
Apply IgnoreAnalyticConstraints
F(x) =
x2
x acos cos x −
2 sign sin x
7-807
7 Functions
By default, int uses strict mathematical rules. These rules do not let int rewrite acos(cos(x)) as
x.
F = int(f,x,'IgnoreAnalyticConstraints',true)
F(x) =
x2
2
Define a symbolic expression xt and compute its indefinite integral with respect to the variable x.
syms x t
F = int(x^t,x)
F =
log x if t = −1
xt + 1
if t ≠ −1
t+1
By default, int returns the general results for all values of the other symbolic parameter t. In this
example, int returns two integral results for the case t = − 1 and t ≠ − 1.
To ignore special cases of parameter values, set 'IgnoreSpecialCases' to true. With this option,
int ignores the special case t = − 1 and returns the solution for t ≠ − 1.
F = int(x^t,x,'IgnoreSpecialCases',true)
F =
xt + 1
t+1
syms x
f(x) = 1/(x-1)
f(x) =
1
x−1
Compute the definite integral of this function from x = 0 to x = 2. Since the integration interval
includes the pole, the result is not defined.
F = int(f,[0 2])
F = NaN
7-808
int
However, the Cauchy principal value of the integral exists. To compute the Cauchy principal value of
the integral, set 'PrincipalValue' to true.
F = int(f,[0 2],'PrincipalValue',true)
F = 0
Define the integral without evaluating it by setting the 'Hold' option to true.
syms x g(y)
F = int(x*exp(x),'Hold',true)
F =
∫x ex dx
You can apply integration by parts to F by using the integrateByParts function. Use exp(x) as
the differential to be integrated.
G = integrateByParts(F,exp(x))
G =
x ex − ∫ ex dx
To evaluate the integral in G, use the release function to ignore the 'Hold' option.
Gcalc = release(G)
Gcalc = x ex − ex
Compare the result to the integration result returned by int without setting the 'Hold' option.
Fcalc = int(x*exp(x))
Fcalc = ex x − 1
If int cannot compute a closed form of an integral, then it returns an unresolved integral.
syms f(x)
f(x) = sin(sinh(x));
F = int(f,x)
F(x) =
∫sin sinh x dx
7-809
7 Functions
You can approximate the integrand function f (x) as polynomials by using the Taylor expansion. Apply
taylor to expand the integrand function f (x) as polynomials around x = 0. Compute the integral of
the approximated polynomials.
fTaylor = taylor(f,x,'ExpansionPoint',0,'Order',10)
fTaylor(x) =
x9 x7 x5
− − +x
5670 90 15
Fapprox = int(fTaylor,x)
Fapprox(x) =
x10 x8 x6 x2
− − +
56700 720 90 2
Input Arguments
expr — Integrand
symbolic expression | symbolic function | symbolic vector | symbolic matrix | symbolic number
Integration variable, specified as a symbolic variable. If you do not specify this variable, int uses the
default variable determined by symvar(expr,1). If expr is a constant, then the default variable is
x.
a — Lower bound
number | symbolic number | symbolic variable | symbolic expression | symbolic function
Lower bound, specified as a number, symbolic number, variable, expression, or function (including
expressions and functions with infinities).
b — Upper bound
number | symbolic number | symbolic variable | symbolic expression | symbolic function
Upper bound, specified as a number, symbolic number, variable, expression, or function (including
expressions and functions with infinities).
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: 'IgnoreAnalyticConstraints',true specifies that int applies purely algebraic
simplifications to the integrand.
7-810
int
Indicator for applying purely algebraic simplifications to the integrand, specified as true or false. If
the value is true, apply purely algebraic simplifications to the integrand. This option can provide
simpler results for expressions, for which the direct use of the integrator returns complicated results.
In some cases, it also enables int to compute integrals that cannot be computed otherwise.
Using this option can lead to results not generally valid. This option applies mathematical identities
that are convenient, but the results do not always hold for all values of variables. For details, see
“Algorithms” on page 7-812.
Indicator for ignoring special cases, specified as true or false. This ignores cases that require one
or more parameters to be elements of a comparatively small set, such as a fixed finite set or a set of
integers.
Indicator for returning the principal value, specified as true or false. If the value is true, int
computes the Cauchy principal value of the integral. In live scripts, the Cauchy principal value of the
Indicator for unevaluated integration, specified as true or false. If the value is true, int returns
integrals without evaluating them.
Tips
• In contrast to differentiation, symbolic integration is a more complicated task. If int cannot
compute an integral of an expression, check for these reasons:
For some integrals that have closed form solutions, where these solutions are complicated and
int returns unresolved integrals, you can use simplify to obtain the closed form solutions. For
example, the following code finds the closed form solution of the integral of f(x):
syms x
f(x) = x*log(x/2+sqrt(x^2+1));
F = int(f,x)
simplify(F,Steps=10)
Otherwise, you can try approximating unresolved integrals by using one of these methods:
7-811
7 Functions
• For indefinite integrals, use series expansions. Use this method to approximate an integral
around a particular value of the variable.
• For definite integrals, use numeric approximations.
• For indefinite integrals, int does not return a constant of integration in the result. The results of
integrating mathematically equivalent expressions may be different. For example, syms x;
int((x+1)^2) returns (x+1)^3/3, while syms x; int(x^2+2*x+1) returns (x*(x^2+3*x
+3))/3, which differs from the first result by 1/3.
• For indefinite integrals, int implicitly assumes that the integration variable var is real. For
definite integrals, int restricts the integration variable var to the specified integration interval. If
one or both integration bounds a and b are not numeric, int assumes that a <= b unless you
explicitly specify otherwise.
Algorithms
When you use IgnoreAnalyticConstraints, int applies some of these rules:
• log(a) + log(b) = log(a·b) for all values of a and b. In particular, the following equality is valid for
all values of a, b, and c:
(a·b)c = ac·bc.
• log(ab) = b·log(a) for all values of a and b. In particular, the following equality is valid for all values
of a, b, and c:
(ab)c = ab·c.
• If f and g are standard mathematical functions and f(g(x)) = x for all small positive numbers, then
f(g(x)) = x is assumed to be valid for all complex values x. In particular:
• log(ex) = x
• asin(sin(x)) = x, acos(cos(x)) = x, atan(tan(x)) = x
• asinh(sinh(x)) = x, acosh(cosh(x)) = x, atanh(tanh(x)) = x
• Wk(x·ex) = x for all branch indices k of the Lambert W function.
Version History
Introduced before R2006a
int(___,'Hold',true) returns integrals without evaluating them. Use release to return the
evaluated integrals by ignoring the 'Hold' option in the int function.
See Also
diff | dsolve | functionalDerivative | symvar | vpaintegral | integrateByParts |
changeIntegrationVariable | release | rewrite
Topics
“Integration” on page 3-176
7-812
int
External Websites
Calculus Integrals (MathWorks Teaching Resources)
Beam Bending and Deflection (MathWorks Teaching Resources)
7-813
7 Functions
integrateByParts
Integration by parts
Syntax
G = integrateByParts(F,du)
Description
G = integrateByParts(F,du) applies integration by parts to the integrals in F, in which the
differential du is integrated. For more information, see “Integration by Parts” on page 7-816.
When specifying the integrals in F, you can return the unevaluated form of the integrals by using the
int function with the 'Hold' option set to true. You can then use integrateByParts to show the
steps of integration by parts.
Examples
Product of Functions
F(x) =
∫u x ∂
∂x
v x dx
g = integrateByParts(F,diff(u))
g =
ux vx − ∫v x ∂
∂x
u x dx
Exponential Function
Define the integral using the int function. Show the result without evaluating the integral by setting
the 'Hold' option to true.
syms x
F = int(x^2*exp(x),'Hold',true)
F =
7-814
integrateByParts
∫x2 ex dx
To show the steps of integration, apply integration by parts to F and use exp(x) as the differential to
be integrated.
G = integrateByParts(F,exp(x))
G =
x2 ex − ∫2 x ex dx
H = integrateByParts(G,exp(x))
H =
x2 ex − 2 x ex + ∫2 ex dx
Evaluate the integral in H by using the release function to ignore the 'Hold' option.
F1 = release(H)
F1 = 2 ex + x2 ex − 2 x ex
Compare the result to the integration result returned by the int function without setting the 'Hold'
option to true.
F2 = int(x^2*exp(x))
F2 = ex x2 − 2 x + 2
Define the integral using the int function. Show the integral without evaluating it by setting the
'Hold' option to true.
syms x a b
F = int(exp(a*x)*sin(b*x),'Hold',true)
F =
∫ ea x sin b x dx
To show the steps of integration, apply integration by parts to F and use u′ x = eax as the differential
to be integrated.
G = integrateByParts(F,exp(a*x))
G =
ea x sin b x a x cos b x
a
− ∫b e a
dx
Evaluate the integral in G by using the release function to ignore the 'Hold' option.
7-815
7 Functions
F1 = release(G)
F1 =
ea x sin b x b ea x a cos b x + b sin b x
−
a a a2 + b
2
F2 = simplify(F1)
F2 =
ea x b cos b x − a sin b x
− 2
a2 + b
Input Arguments
F — Expression containing integrals
symbolic expression | symbolic function | symbolic vector | symbolic matrix
du — Differential to be integrated
symbolic variable | symbolic expression | symbolic function
More About
Integration by Parts
Mathematically, the rule of integration by parts is formally defined for indefinite integrals as
a
∫ u′(x) v(x) dx = u(b) v(b) − u(a) v(a) − ∫ u(x) v′(x) dx .
a
Version History
Introduced in R2019b
See Also
changeIntegrationVariable | release | int | diff | vpaintegral
7-816
inv
inv
Inverse of symbolic matrix
Syntax
D = inv(A)
Description
D = inv(A) returns the inverse of a symbolic matrix A.
Examples
D =
3 1 1
4 2 4
1 1
1
2 2
1 1 3
4 2 4
D =
d b
−
ad−bc ad−bc
c a
−
ad−bc ad−bc
Compute the inverse of the Hilbert matrix that contains symbolic numbers.
D = inv(sym(hilb(4)))
D =
16 −120 240 −140
−120 1200 −2700 1680
240 −2700 6480 −4200
−140 1680 −4200 2800
7-817
7 Functions
A 02, 2
C=
02, 2 B
where A and B are 2-by-2 submatrices. The notation 02, 2 represents a 2-by-2 submatrix of zeros.
Use symbolic matrix variables to represent the submatrices in the block matrix.
syms A B [2 2] matrix
Z = symmatrix(zeros(2))
Z = 02, 2
C = [A Z; Z B]
C =
A 02, 2
02, 2 B
D =
A 02, 2 −1
02, 2 B
To show the elements of the inverse matrix, convert the result from a symbolic matrix variable to
symbolic scalar variables using symmatrix2sym.
D1 = symmatrix2sym(D)
D1 =
A2, 2 A1, 2
− 0 0
σ2 σ2
A2, 1 A1, 1
− 0 0
σ2 σ2
B2, 2 B1, 2
0 0 −
σ1 σ1
B2, 1 B1, 1
0 0 −
σ1 σ1
where
7-818
inv
Create the matrix A as a symbolic matrix variable and the coefficient a0 as a symbolic scalar variable.
Create the matrix polynomial as a symbolic matrix function f with a0 and A as its parameters.
syms A [2 2] matrix
syms a0
syms f(a0,A) [2 2] matrix keepargs
f(a0,A) = a0*eye(2) + A
f(a0, A) = a0 I2 + A
Find the inverse of f using inv. The result is a symbolic matrix function of type symfunmatrix that
accepts scalars, vectors, and matrices as its input arguments.
fInv = inv(f)
−1
fInv(a0, A) = a0 I2 + A
Convert the result from the symfunmatrix data type to the symfun data type using
symfunmatrix2symfun. The result is a symbolic function that accepts scalars as its input
arguments.
gInv = symfunmatrix2symfun(fInv)
where
Input Arguments
A — Input matrix
square numeric matrix | square matrix of symbolic scalar variables | square symbolic matrix variable |
square symbolic matrix function | symbolic expression with square size
Input matrix, specified as a square numeric matrix, square matrix of symbolic scalar variables, square
symbolic matrix variable, square symbolic matrix function, or symbolic expression with square size.
Data Types: single | double | sym | symmatrix | symfunmatrix
Tips
• Matrix computations involving many symbolic variables can be slow. To increase the
computational speed, reduce the number of symbolic variables by substituting the given values for
some variables.
7-819
7 Functions
Version History
Introduced before R2006a
The inv function accepts an input argument of type symfunmatrix. For an example, see “Compute
Inverse of Matrix Polynomial” on page 7-818.
The inv function accepts an input argument of type symmatrix. For an example, see “Compute
Inverse of Block Matrix” on page 7-818.
See Also
eig | det | rank
7-820
isAlways
isAlways
Determine if symbolic conditions are true for all values of variables
Syntax
tf = isAlways(cond)
tf = isAlways(cond,Unknown=option)
Description
tf = isAlways(cond) checks if the conditions in cond are always mathematically true and returns
an array of logical values. isAlways checks if cond holds true for all possible values of the symbolic
variables in cond including all assumptions on the variables. If an element in cond is always true,
then the corresponding element in tf is a logical 1 (true). Otherwise, the corresponding element in
tf is a logical 0 (false).
Examples
syms x
tf = isAlways(abs(x) >= 0)
tf = logical
1
isAlways returns logical 1 (true), indicating that the inequality abs(x) >= 0 is true for all values
of x.
tf = isAlways(sin(x)^2 + cos(x)^2 == 1)
tf = logical
1
isAlways returns logical 1 (true), indicating that the equation sin(x)^2 + cos(x)^2 == 1 is
true for all values of x.
7-821
7 Functions
Check if at least one of two conditions holds true. To check if at least one of several conditions is true,
combine them using the logical operator or or its shortcut |.
syms x
tf = isAlways(sin(x)^2 + cos(x)^2 == 1 | x^2 > 0)
tf = logical
1
Check if both conditions hold true. To check if several conditions are true, combine them using the
logical operator and or its shortcut &.
tf = isAlways(sin(x)^2 + cos(x)^2 == 1 & abs(x) > 2*abs(x))
tf = logical
0
For multiple conditions, you can also represent the conditions as a symbolic array.
cond = [sin(x)^2 + cos(x)^2 == 1; abs(x) > 2*abs(x)]
cond =
2 2
cos x + sin x =1
2 x < x
tf = isAlways(cond)
1
0
When isAlways cannot determine if a condition is true, it returns logical 0 (false) and issues a
warning by default.
syms x
tf = isAlways(2*x >= x)
tf = logical
0
To change this default behavior, use the Unknown name-value argument. For example, specify
Unknown as "false" to suppress the warning and make isAlways return logical 0 (false) if it
cannot determine whether the condition is true.
tf = isAlways(2*x >= x,Unknown="false")
7-822
isAlways
tf = logical
0
Instead of "false", you can also specify Unknown as "error" to return an error, and as "true" to
return logical 1 (true).
Check an inequality under the assumption that x is negative. When isAlways tests an equation or
inequality, it takes into account assumptions on variables in that equation or inequality.
syms x
assume(x < 0)
tf = isAlways(2*x < x)
tf = logical
1
syms x
Input Arguments
cond — Condition to check
symbolic condition | vector of symbolic conditions | matrix of symbolic conditions | multidimensional
array of symbolic conditions
Version History
Introduced in R2012a
7-823
7 Functions
isAlways issues a warning when returning false (or logical 0) for undecidable inputs. To suppress
the warning, set the Unknown option to false by using isAlways(cond,Unknown="false"). For
details, see “Handle Output for Undecidable Conditions” on page 7-822.
See Also
assume | assumeAlso | assumptions | in | isequal | isequaln | isfinite | isinf | isnan |
logical | sym | syms
Topics
“Use Assumptions on Symbolic Variables” on page 1-41
“Clear Assumptions and Reset the Symbolic Engine” on page 3-314
“Check Symbolic Equations, Inequalities, and Conditional Statements” on page 2-23
7-824
isequal
isequal
Determine if symbolic inputs are equal
Syntax
tf = isequal(A,B)
tf = isequal(A1,A2,...,An)
Description
tf = isequal(A,B) returns logical 1 (true) if A and B are the same size and their contents are of
equal value (from a coding perspective). Otherwise, isequal returns logical 0 (false). isequal
does not consider NaN (Not a Number) values to be equal. isequal recursively compares the
contents of symbolic data structures and the properties of objects. If all contents in the corresponding
locations are equal, isequal returns logical 1 (true).
tf = isequal(A1,A2,...,An) returns logical 1 (true) if all the inputs A1,A2,...,An are equal.
Examples
Test numeric or symbolic inputs for equality using isequal. If you compare numeric inputs against
symbolic inputs, isequal returns 0 (false) because double and sym are distinct data types.
Test if 2 and 5 are equal. Because you are comparing doubles, the MATLAB® isequal function is
called. isequal returns 0 (false) as expected.
tf = isequal(2,5)
tf = logical
0
Test if the solution of the equation cos(x) == -1 is pi. The isequal function returns 1 (true),
meaning the solution is equal to pi.
syms x
sol = solve(cos(x) == -1,x);
tf = isequal(sol,sym(pi))
tf = logical
1
Compare the double and symbolic representations of pi. isequal returns 0 (false) because
double and sym are distinct data types. To return 1 (true) in this case, use logical instead.
usingIsEqual = isequal(pi,sym(pi))
7-825
7 Functions
usingIsEqual = logical
0
usingLogical = logical
1
Test if the expressions tan(x) and sin(x)/cos(x) are equal (from a coding perspective). The
isequal function returns 0 (false) because the expressions are different. isequal does not
mathematically compare the expressions.
syms x
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) as sin(x)/cos(x). The isequal function returns 1 (true).
f = rewrite(tan(x),"sincos");
testf = sin(x)/cos(x);
tf = isequal(f,testf)
tf = logical
1
To check if the mathematical comparison tan(x) == sin(x)/cos(x) holds true for all values of x,
use isAlways.
tf = isAlways(tan(x) == sin(x)/cos(x))
tf = logical
1
Test if solutions of the quadratic equation found by solve are equal to the expected solutions. The
isequal function returns 1 (true), meaning the symbolic vectors are equal.
syms a b c x
eqn = a*x^2 + b*x + c;
Sol = solve(eqn,x);
testSol = [-(b+(b^2-4*a*c)^(1/2))/(2*a); -(b-(b^2-4*a*c)^(1/2))/(2*a)];
tf = isequal(Sol,testSol)
7-826
isequal
tf = logical
1
The Hilbert matrix is a special matrix that is difficult to invert accurately. If the inverse is accurately
computed, then multiplying the inverse by the original Hilbert matrix returns the identity matrix.
Use this condition to test if the inverse of hilb(20) is correctly calculated. isequal returns 1
(true), meaning that the product of the inverse and the original Hilbert matrix is equal to the
identity matrix.
H = sym(hilb(20));
prod = H*inv(H);
eye20 = sym(eye(20));
tf = isequal(prod,eye20)
tf = logical
1
Compare three vectors containing NaN (not a number). isequal returns logical 0 (false) because
isequal does not treat NaN values as equal.
syms x
A1 = [x NaN NaN];
A2 = [x NaN NaN];
A3 = [x NaN NaN];
tf = isequal(A1,A2,A3)
tf = logical
0
Input Arguments
A,B — Inputs to compare (as separate arguments)
numbers | vectors | matrices | arrays | symbolic numbers | symbolic scalar variables | symbolic matrix
variables | symbolic arrays | symbolic functions | symbolic matrix functions | symbolic expressions
Inputs to compare, specified as numbers, vectors, matrices, or arrays, or symbolic numbers, scalar
variables, matrix variables, arrays, functions, matrix functions, or expressions.
Series of inputs to compare, specified as numbers, vectors, matrices, or arrays, or symbolic numbers,
scalar variables, matrix variables, arrays, functions, matrix functions, or expressions.
7-827
7 Functions
Tips
• isequal(A,B) checks if A and B are the same size and their contents are equal (from a coding
perspective). To check whether the condition A == B is always mathematically true for all values
of variables in A and B, use isAlways(A == B).
• If one of the input arguments is a symbolic type and the other input is a MATLAB numeric type
with the same value, then isequal returns logical 0 (false) because the inputs do not have the
same data type. For example, tf = isequal(1,sym(1)) returns 0 (false).
Version History
Introduced before R2006a
See Also
in | isAlways | isequaln | isfinite | isinf | isnan | logical
Topics
“Check Symbolic Equations, Inequalities, and Conditional Statements” on page 2-23
7-828
isequaln
isequaln
Test symbolic objects for equality, treating NaN values as equal
Syntax
tf = isequaln(A,B)
tf = isequaln(A1,A2,...,An)
Description
tf = isequaln(A,B) returns logical 1 (true) if A and B are the same size and their contents are of
equal value. Otherwise, isequaln returns logical 0 (false). All NaN (not a number) values are
considered to be equal to each other. isequaln recursively compares the contents of symbolic data
structures and the properties of objects. If all contents in the respective locations are equal,
isequaln returns logical 1 (true).
Examples
syms x
tf = isequaln(abs(x),x)
tf = logical
0
assume(x > 0)
tf = isequaln(abs(x),x)
tf = logical
1
syms x
7-829
7 Functions
A = hilb(3);
B = sym(A);
tf = isequaln(A,B)
tf = logical
0
syms x
A1 = [x NaN NaN];
A2 = [x NaN NaN];
A3 = [x NaN NaN];
tf = isequaln(A1,A2,A3)
tf = logical
1
Input Arguments
A,B — Inputs to compare
symbolic numbers | symbolic scalar variables | symbolic matrix variables | symbolic expressions |
symbolic functions | symbolic matrix functions | symbolic vectors | symbolic matrices
Inputs to compare, specified as symbolic numbers, scalar variables, matrix variables, expressions,
functions, matrix functions, vectors, or matrices. If one of the arguments is a symbolic object and the
other one is numeric, the toolbox converts the numeric object to symbolic before comparing them.
Series of inputs to compare, specified as symbolic numbers, scalar variables, matrix variables,
expressions, functions, matrix functions, vectors, or matrices. If at least one of the arguments is a
symbolic object, the toolbox converts all other arguments to symbolic objects before comparing them.
Tips
• isequaln(A,B) checks if A and B are the same size and their contents are equal (from coding
perspective), treating NaN values as equal. To check whether the mathematical comparison A ==
B holds for all values of variables in A and B, use isAlways(A == B).
• If one of the input arguments is a symbolic type and the other input is a MATLAB numeric type
with the same value, then isequaln returns logical 0 (false) because the inputs are not equal
(from coding perspective). For example, tf = isequaln(1,sym(1)) returns 0 (false).
7-830
isequaln
Version History
Introduced in R2013a
See Also
in | isAlways | isequal | isequaln | isfinite | isinf | isnan
Topics
“Check Symbolic Equations, Inequalities, and Conditional Statements” on page 2-23
7-831
7 Functions
isfinite
Check whether symbolic array elements are finite
Syntax
isfinite(A)
Description
isfinite(A) returns an array of the same size as A containing logical 1s (true) where the elements
of A are finite, and logical 0s (false) where they are not. For a complex number, isfinite returns 1 if
both the real and imaginary parts of that number are finite. Otherwise, it returns 0.
Examples
Determine Which Elements of Symbolic Array Are Finite Values
Using isfinite, determine which elements of this symbolic matrix are finite values:
ans =
2×3 logical array
1 0 0
1 0 0
cot(V)
isfinite(cot(V))
ans =
[ Inf, Inf, Inf, Inf]
ans =
1×4 logical array
0 0 0 0
Nevertheless, the cotangents of the approximated values are finite due to the round-off errors:
isfinite(cot(V_approx))
ans =
1×4 logical array
1 1 1 1
7-832
isfinite
Input Arguments
A — Input value
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic array |
symbolic vector | symbolic matrix
Input value, specified as a symbolic number, variable, expression, or function, or as an array, vector,
or matrix of symbolic numbers, variables, expressions, functions.
Tips
• For any A, exactly one of the three quantities isfinite(A), isinf(A), or isnan(A) is 1 for
each element.
• Elements of A are recognized as finite if they are
Version History
Introduced in R2013b
See Also
in | isAlways | isequal | isequaln | isinf | isnan
7-833
7 Functions
isinf
Check whether symbolic array elements are infinite
Syntax
isinf(A)
Description
isinf(A) returns an array of the same size as A containing logical 1s (true) where the elements of A
are infinite, and logical 0s (false) where they are not. For a complex number, isinf returns 1 if the
real or imaginary part of that number is infinite or both real and imaginary parts are infinite.
Otherwise, it returns 0.
Examples
Determine Which Elements of Symbolic Array Are Infinite
Using isinf, determine which elements of this symbolic matrix are infinities:
isinf(sym([pi NaN Inf; 1 + i Inf + i NaN + i]))
ans =
2×3 logical array
0 0 1
0 1 0
ans =
[ Inf, Inf, Inf, Inf]
ans =
1×4 logical array
1 1 1 1
Nevertheless, the cotangents of the approximated values are not infinite due to the round-off errors:
isinf(cot(V_approx))
ans =
1×4 logical array
0 0 0 0
7-834
isinf
Input Arguments
A — Input value
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic array |
symbolic vector | symbolic matrix
Input value, specified as a symbolic number, variable, expression, or function, or as an array, vector,
or matrix of symbolic numbers, variables, expressions, functions.
Tips
• For any A, exactly one of the three quantities isfinite(A), isinf(A), or isnan(A) is 1 for
each element.
• The elements of A are recognized as infinite if they are
Version History
Introduced in R2013b
See Also
in | isAlways | isequal | isequaln | isfinite | isnan
7-835
7 Functions
isLowIndexDAE
Check if differential index of system of equations is lower than 2
Syntax
isLowIndexDAE(eqs,vars)
Description
isLowIndexDAE(eqs,vars) checks if the system eqs of first-order semilinear differential algebraic
equations (DAEs) has a low differential index. If the differential index of the system is 0 or 1, then
isLowIndexDAE returns logical 1 (true). If the differential index of eqs is higher than 1, then
isLowIndexDAE returns logical 0 (false).
The number of equations eqs must match the number of variables vars.
Examples
Check Differential Index of DAE System
Check if a system of first-order semilinear DAEs has a low differential index (0 or 1).
Create the following system of two differential algebraic equations. Here, x(t) and y(t) are the
state variables of the system. Specify the equations and variables as two symbolic vectors: equations
as a vector of symbolic equations, and variables as a vector of symbolic function calls.
syms x(t) y(t)
eqs = [diff(x(t),t) == x(t) + y(t), x(t)^2 + y(t)^2 == 1];
vars = [x(t), y(t)];
Use isLowIndexDAE to check the differential order of the system. The differential order of this
system is 1. For systems of index 0 and 1, isLowIndexDAE returns 1 (true).
isLowIndexDAE(eqs, vars)
ans =
logical
1
Check if the following DAE system has a low or high differential index. If the index is higher than 1,
then use reduceDAEIndex to reduce it.
Create the following system of two differential algebraic equations. Here, x(t), y(t), and z(t) are
the state variables of the system. Specify the equations and variables as two symbolic vectors:
equations as a vector of symbolic equations, and variables as a vector of symbolic function calls.
syms x(t) y(t) z(t) f(t)
eqs = [diff(x(t),t) == x(t) + z(t),...
diff(y(t),t) == f(t), x(t) == y(t)];
vars = [x(t), y(t), z(t)];
7-836
isLowIndexDAE
Use isLowIndexDAE to check the differential index of the system. For this system isLowIndexDAE
returns 0 (false). This means that the differential index of the system is 2 or higher.
isLowIndexDAE(eqs, vars)
ans =
logical
0
Use reduceDAEIndex to rewrite the system so that the differential index is 1. Calling this function
with four output arguments also shows the differential index of the original system. The new system
has one additional state variable, Dyt(t).
newEqs =
diff(x(t), t) - z(t) - x(t)
Dyt(t) - f(t)
x(t) - y(t)
diff(x(t), t) - Dyt(t)
newVars =
x(t)
y(t)
z(t)
Dyt(t)
oldIndex =
2
isLowIndexDAE(newEqs, newVars)
ans =
logical
1
Input Arguments
eqs — System of first-order semilinear differential algebraic equations
vector of symbolic equations | vector of symbolic expressions
State variables, specified as a vector of symbolic functions or function calls, such as x(t).
Example: [x(t),y(t)]
Version History
Introduced in R2014b
7-837
7 Functions
See Also
daeFunction | decic | findDecoupledBlocks | incidenceMatrix | massMatrixForm |
odeFunction | reduceDAEIndex | reduceDAEToODE | reduceDifferentialOrder |
reduceRedundancies
Topics
“Solve Differential Algebraic Equations (DAEs)” on page 3-61
7-838
isnan
isnan
Check whether symbolic array elements are NaNs
Syntax
isnan(A)
Description
isnan(A) returns an array of the same size as A containing logical 1s (true) where the elements of A
are symbolic NaNs, and logical 0s (false) where they are not.
Examples
Determine Which Elements of Symbolic Array Are NaNs
Using isnan, determine which elements of this symbolic matrix are NaNs:
ans =
2×3 logical array
0 1 0
0 0 1
Input Arguments
A — Input value
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic array |
symbolic vector | symbolic matrix
Input value, specified as a symbolic number, variable, expression, or function, or as an array, vector,
or matrix of symbolic numbers, variables, expressions, functions.
Tips
• For any A, exactly one of the three quantities isfinite(A), isinf(A), or isnan(A) is 1 for
each element.
• Symbolic expressions and functions containing NaN evaluate to NaN. For example, sym(NaN + i)
returns symbolic NaN.
Version History
Introduced in R2013b
See Also
isAlways | isequal | isequaln | isfinite | isinf
7-839
7 Functions
isolate
Isolate variable or expression in equation
Syntax
isolate(eqn,expr)
Description
isolate(eqn,expr) rearranges the equation eqn so that the expression expr appears on the left
side. The result is similar to solving eqn for expr. If isolate cannot isolate expr, it moves all terms
containing expr to the left side. The output of isolate lets you eliminate expr from eqn by using
subs.
Examples
Isolate Variable in Equation
syms x a b c
eqn = a*x^2 + b*x + c == 0;
xSol = isolate(eqn, x)
xSol =
x == -(b + (b^2 - 4*a*c)^(1/2))/(2*a)
You can use the output of isolate to eliminate the variable from the equation using subs.
eqn2 =
c + (b + (b^2 - 4*a*c)^(1/2))^2/(4*a) - (b*(b + (b^2 - 4*a*c)^(1/2)))/(2*a) == 0
syms y(t)
eqn = a*y(t)^2 + b*c == 0;
isolate(eqn, y(t))
ans =
y(t) == ((-b)^(1/2)*c^(1/2))/a^(1/2)
isolate(eqn, a*y(t))
ans =
a*y(t) == -(b*c)/y(t)
7-840
isolate
For equations with multiple solutions, isolate returns the simplest solution.
Demonstrate this behavior by isolating x in sin(x) == 0, which has multiple solutions at 0, pi,
3*pi/2, and so on.
isolate(sin(x) == 0, x)
ans =
x == 0
isolate does not consider special cases when returning the solution. Instead, isolate returns a
general solution that is not guaranteed to hold for all values of the variables in the equation.
Isolate x in the equation a*x^2/(x-a) == 1. The returned value of x does not hold in the special
case a = 0.
syms a x
isolate(a*x^2/(x-a) == 1, x)
ans =
x == ((-(2*a - 1)*(2*a + 1))^(1/2) + 1)/(2*a)
isolate returns only results that are consistent with the assumptions on the variables in the
equation.
syms x
assume(x < 0)
eqn = x^4 == 1;
isolate(x^4 == 1, x)
ans =
x == -1
assume(x, 'clear')
isolate(x^4 == 1, x)
ans =
x == 1
Tips
• If eqn has no solution, isolate errors. isolate also ignores special cases. If the only solutions
to eqn are special cases, then isolate ignores those special cases and errors.
• The returned solution is not guaranteed to hold for all values of the variables in the solution.
• expr cannot be a mathematical constant such as pi.
7-841
7 Functions
Input Arguments
eqn — Input equation
symbolic equation
Version History
Introduced in R2017a
See Also
dsolve | lhs | linsolve | rhs | solve | subs | vpasolve
Topics
“Solve Algebraic Equations” on page 3-3
“Solve System of Algebraic Equations” on page 3-7
“Solve Equations Numerically” on page 3-21
“Solve System of Linear Equations” on page 3-30
7-842
isPrimitiveRoot
isPrimitiveRoot
Determine which array elements are primitive roots
Syntax
TF = isPrimitiveRoot(G,N)
Description
TF = isPrimitiveRoot(G,N) returns a logical array containing 1 (true) for the corresponding
elements of G that are primitive roots on page 7-844 modulo N, and 0 (false) for the
corresponding elements that are not primitive roots. The elements of G must be integers, and the
elements of N must be positive integers.
Examples
Create a row vector containing positive integers from 1 to 11. Determine if they are primitive roots
modulo 11.
G = 1:11;
TF = isPrimitiveRoot(G,11)
0 1 0 0 0 1 1 1 0 0 0
Find the smallest positive integer that is a primitive root modulo 11.
Z1 = find(TF,1)
Z1 = 2
Show all positive integers (less than or equal to 11) that are primitive roots modulo 11.
Z = G(TF)
Z = 1×4
2 6 7 8
Create a row vector containing integers from –15 to 15. Find the integers that are primitive roots
modulo 15.
7-843
7 Functions
G = -15:15;
Z = G(isPrimitiveRoot(G,15))
Z =
Input Arguments
G — Base
number | vector | matrix | array | symbolic number | symbolic array
Base, specified as a number, vector, matrix, array, symbolic number, or symbolic array. The elements
of G must be integers. G and N must be the same size, or else one of them must be a scalar.
Data Types: single | double | sym
N — Divisor
number | vector | matrix | array | symbolic number | symbolic array
Divisor, specified as a number, vector, matrix, array, symbolic number, or symbolic array. The
elements of N must be positive integers. G and N must be the same size, or else one of them must be a
scalar.
Data Types: single | double | sym
More About
Primitive Root
A number g is a primitive root modulo n if every number a coprime to n (or gcd(a, n) = 1) is congruent
to a power of g modulo n. That is, g is a primitive root modulo n if for every integer a coprime to n,
there is an integer k such that gk ≡ a (mod n). The primitive roots modulo n exist if and only if
n = 1, 2, 4, pk, or 2pk, where p is an odd prime and k is a positive integer.
k
For example, the integer 2 is a primitive root modulo 5 because 2 ≡ a (mod 5) is satisfied for every
integer a that is coprime to 5.
1
2 = 2 ≡ 2 (mod 5)
2
2 = 4 ≡ 4 (mod 5)
3
2 = 8 ≡ 3 (mod 5)
4
2 = 16 ≡ 1 (mod 5)
⋮
Version History
Introduced in R2020a
7-844
isPrimitiveRoot
See Also
eulerPhi | prevprime | nextprime | nthprime
7-845
7 Functions
isSymType
Determine whether symbolic object is specific type
Syntax
TF = isSymType(symObj,type)
TF = isSymType(symObj,funType,vars)
Description
TF = isSymType(symObj,type) returns logical 1 (true) if the symbolic object symObj is of type
type, and logical 0 (false) otherwise. The input type must be a case-sensitive string scalar or
character vector, and it can include a logical expression. For example, isSymType(sym('3'),'real
& integer') returns logical 1.
You can set the function type funType to 'symfunOf' or 'symfunDependingOn'. For example,
syms f(x); isSymType(f,'symfunOf',x) returns logical 1.
Examples
Create a symbolic number. Check whether the symbolic number is of type 'rational'.
a = sym('1/2');
TF = isSymType(a,'rational')
TF = logical
1
Now construct a symbolic array by including symbolic numbers or constants in the array elements.
N =
1
0.5 π 3.1415926535897932384626433832795 i
2
TF = isSymType(N,'real')
7-846
isSymType
1 1 0 1 0
1 1 0 1 0
1 1 0 1 1
1 1 1 1 1
Determine whether the topmost operator of a symbolic expression is of a specific type, such as
'plus' or 'power'.
expr = x2 + 2 x − 1
TF = logical
1
TF = logical
0
7-847
7 Functions
expr = x2 + 2 x − 1
TF = logical
1
Select the right side of each equation using the rhs function. Check whether the right side of each
equation is of type 'constant'.
TF = isSymType(rhs(eq1),'constant')
0 0 1
eq2 = r t = 5
Create a symbolic function of multiple variables f(x,y) using syms. Check whether the unassigned
symbolic function f is of type 'symfun'.
syms f(x,y)
TF = isSymType(f,'symfun')
TF = logical
1
7-848
isSymType
TF = isSymType(f,'symfunOf',x)
TF = logical
0
TF = isSymType(f,'symfunOf',[x y])
TF = logical
1
TF = isSymType(f,'symfunDependingOn',x)
TF = logical
1
Input Arguments
symObj — Symbolic objects
symbolic expressions | symbolic functions | symbolic variables | symbolic numbers | symbolic units
Symbolic objects, specified as symbolic expressions, symbolic functions, symbolic variables, symbolic
numbers, or symbolic units.
Symbolic types, specified as a case-sensitive scalar string or character vector. The input type can
contain a logical expression. The value options follow.
7-849
7 Functions
7-850
isSymType
• 'symfunOf' checks whether symObj is an unassigned symbolic function that depends on the
exact sequence of variables specified by the array vars. For example, syms f(x,y);
isSymType(f,'symfunOf',[x y]) returns logical 1.
• 'symfunDependingOn' checks whether symObj is an unassigned symbolic function that
depends on the variables specified by the array vars. For example, syms f(x,y);
isSymType(f,'symfunDependingOn',x) returns logical 1.
Version History
Introduced in R2019a
See Also
symFunType | hasSymType | symType | sym | syms
7-851
7 Functions
isUnit
Determine if input is a symbolic unit
Syntax
tf = isUnit(expr)
Description
tf = isUnit(expr) returns logical 1 (true) if expr is a unit, or a product of powers of units, and
logical 0 (false) if it is not.
Examples
Determine if Input is a Unit
Test if 3*u.m is a symbolic unit, where u = symunit. The isUnit function returns logical 0 (false)
because 3*u.m contains the symbolic number 3.
u = symunit;
isUnit(3*u.m)
ans =
logical
0
Check if u.m, u.mW, and x*u.Hz are units, where u = symunit. The isUnit function returns the
array [1 1 0], meaning that the first two expressions are units but the third expression is not.
syms x
units = [u.m u.mW x*u.Hz];
isUnit(units)
ans =
1×3 logical array
1 1 0
Input Arguments
expr — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
Input, specified as a number, vector, matrix or multidimensional array, or a symbolic number, variable,
vector, matrix, multidimensional array, function, or expression.
7-852
isUnit
Tips
• 1 represents a dimensionless unit. Hence, isUnit(sym(1)) returns logical 1 (true).
Version History
Introduced in R2017a
See Also
checkUnits | findUnits | newUnit | separateUnits | symunit | str2symunit | symunit2str |
unitConversionFactor
Topics
“Units of Measurement Tutorial” on page 2-47
“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)
7-853
7 Functions
iztrans
Inverse Z-transform
Syntax
iztrans(F)
iztrans(F,transVar)
iztrans(F,var,transVar)
Description
iztrans(F) returns the “Inverse Z-Transform” on page 7-856 of F. By default, the independent
variable is z and the transformation variable is n. If F does not contain z, iztrans uses the function
symvar.
Examples
Inverse Z-Transform of Symbolic Expression
Compute the inverse Z-transform of 2*z/(z-2)^2. By default, the inverse transform is in terms of n.
syms z
F = 2*z/(z-2)^2;
iztrans(F)
ans =
2^n + 2^n*(n - 1)
Compute the inverse Z-transform of 1/(a*z). By default, the independent and transformation
variables are z and n, respectively.
syms z a
F = 1/(a*z);
iztrans(F)
ans =
kroneckerDelta(n - 1, 0)/a
Specify the transformation variable as m. If you specify only one variable, that variable is the
transformation variable. The independent variable is still z.
syms m
iztrans(F,m)
ans =
kroneckerDelta(m - 1, 0)/a
7-854
iztrans
Specify both the independent and transformation variables as a and m in the second and third
arguments, respectively.
iztrans(F,a,m)
ans =
kroneckerDelta(m - 1, 0)/z
Compute the inverse Z-transforms of these expressions. The results involve the Kronecker Delta
function.
syms n z
iztrans(1/z,z,n)
ans =
kroneckerDelta(n - 1, 0)
f = (z^3 + 3*z^2)/z^5;
iztrans(f,z,n)
ans =
kroneckerDelta(n - 2, 0) + 3*kroneckerDelta(n - 3, 0)
Find the inverse Z-transform of the matrix M. Specify the independent and transformation variables
for each matrix entry by using matrices of the same size. When the arguments are nonscalars,
iztrans acts on them element-wise.
syms a b c d w x y z
M = [exp(x) 1; sin(y) i*z];
vars = [w x; y z];
transVars = [a b; c d];
iztrans(M,vars,transVars)
ans =
[ exp(x)*kroneckerDelta(a, 0), kroneckerDelta(b, 0)]
[ iztrans(sin(y), y, c), iztrans(z, z, d)*1i]
If iztrans is called with both scalar and nonscalar arguments, then it expands the scalars to match
the nonscalars by using scalar expansion. Nonscalar arguments must be the same size.
syms w x y z a b c d
iztrans(x,vars,transVars)
ans =
[ x*kroneckerDelta(a, 0), iztrans(x, x, b)]
[ x*kroneckerDelta(c, 0), x*kroneckerDelta(d, 0)]
Compute the Inverse Z-transform of symbolic functions. When the first argument contains symbolic
functions, then the second argument must be a scalar.
7-855
7 Functions
f2(x) = x;
iztrans([f1, f2],x,[a, b])
ans =
[ iztrans(exp(x), x, a), iztrans(x, x, b)]
syms F(z) n
F(z) = exp(z);
f = iztrans(F,z,n)
f =
iztrans(exp(z), z, n)
ztrans(f,n,z)
ans =
exp(z)
Input Arguments
F — Input
symbolic expression | symbolic function | symbolic vector | symbolic matrix
Independent variable, specified as a symbolic variable, expression, vector, or matrix. This variable is
often called the "complex frequency variable." If you do not specify the variable, then iztrans uses
z. If F does not contain z, then iztrans uses the function symvar.
More About
Inverse Z-Transform
Where R is a positive number, such that the function F = F(z) is analytic on and outside the circle |z|
= R, the inverse Z-transform is
f n =
1
2πi ∮
z =R
F z zn − 1dz, n = 0, 1, 2...
7-856
iztrans
Tips
• If any argument is an array, then iztrans acts element-wise on all elements of the array.
• If the first argument contains a symbolic function, then the second argument must be a scalar.
• To compute the direct Z-transform, use ztrans.
Version History
Introduced before R2006a
See Also
fourier | ifourier | ilaplace | kroneckerDelta | laplace | ztrans
Topics
“Solve Difference Equations Using Z-Transform” on page 3-195
7-857
7 Functions
jacobiAM
Jacobi amplitude function
Syntax
jacobiAM(u,m)
Description
jacobiAM(u,m) returns the “Jacobi Amplitude Function” on page 7-860 of u and m. If u or m is an
array, then jacobiAM acts element-wise.
Examples
jacobiAM(2,1)
ans =
1.3018
ans =
1.3018 0.7370 0.6155
Convert numeric input to symbolic form using sym, and find the Jacobi amplitude function. For
symbolic input where u = 0 or m = 0 or 1, jacobiAM returns exact symbolic output.
jacobiAM(sym(2),sym(1))
ans =
2*atan(exp(2)) - pi/2
Show that for other values of u or m, jacobiAM returns an unevaluated function call.
jacobiAM(sym(2),sym(3))
ans =
jacobiAM(2, 3)
For symbolic variables or expressions, jacobiAM returns the unevaluated function call.
7-858
jacobiAM
syms x y
f = jacobiAM(x,y)
f =
jacobiAM(x, y)
Substitute values for the variables by using subs, and convert values to double by using double.
f =
jacobiAM(3, 5)
fVal = double(f)
fVal =
0.0311
fVal = vpa(f)
fVal =
0.031149815412430844987208470634926
Plot the Jacobi amplitude function using fcontour. Set u on the x-axis and m on the y-axis by using
the symbolic function f with the variable order (u,m). Fill plot contours by setting Fill to on.
syms f(u,m)
f(u,m) = jacobiAM(u,m);
fcontour(f,'Fill','on')
title('Jacobi Amplitude Function')
xlabel('u')
ylabel('m')
7-859
7 Functions
Input Arguments
u — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
m — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
More About
Jacobi Amplitude Function
The Jacobi amplitude function am(u,m) is defined by am(u,m) = φ where F(φ,m) = u and F represents
the incomplete elliptic integral of the first kind. F is implemented as ellipticF.
7-860
jacobiAM
Version History
Introduced in R2017b
See Also
ellipticF | jacobiCD | jacobiCN | jacobiCS | jacobiDC | jacobiDN | jacobiDS | jacobiNC |
jacobiND | jacobiNS | jacobiSC | jacobiSD | jacobiSN | jacobiZeta
7-861
7 Functions
jacobian
Jacobian matrix of symbolic function
Syntax
jacobian(f,v)
Description
jacobian(f,v) computes the Jacobian matrix on page 7-864 of symbolic function f with respect to
∂f i
v. The (i,j) element of the result is .
∂v j
Examples
The Jacobian of a vector function is a matrix of the partial derivatives of that function.
ans =
yz xz xy
0 2y 0
1 0 1
ans =
yz xz xy
0 2y 0
1 0 1
The Jacobian matrix is invariant to the orientation of the vector in the second input position.
7-862
jacobian
ans = 2 3 4
ans =
2
3
4
The Jacobian of a function with respect to a scalar is the first derivative of that function. For a vector
function, the Jacobian with respect to a scalar is a vector of the first derivatives.
syms x y
jacobian([x^2*y,x*sin(y)],x)
ans =
2xy
sin y
diff([x^2*y,x*sin(y)],x)
ans = 2 x y sin y
Specify polar coordinates r(t), ϕ(t), and θ(t) that are functions of time.
Find the Jacobian of the coordinate change from spherical coordinates to Cartesian coordinates.
jacobian(R,[r,phi,theta])
ans(t) =
cos θ t sin ϕ t cos ϕ t cos θ t r t −sin ϕ t sin θ t r t
sin ϕ t sin θ t cos ϕ t sin θ t r t cos θ t sin ϕ t r t
cos ϕ t −sin ϕ t r t 0
7-863
7 Functions
Input Arguments
f — Scalar or vector function
symbolic expression | symbolic function | symbolic vector
Scalar or vector function, specified as a symbolic expression, function, or vector. If f is a scalar, then
the Jacobian matrix of f is the transposed gradient of f.
Vector of variables or functions with respect to which you compute Jacobian, specified as a symbolic
variable, symbolic function, or vector of symbolic variables. If v is a scalar, then the result is equal to
the transpose of diff(f,v). If v is an empty symbolic object, such as sym([]), then jacobian
returns an empty symbolic object.
More About
Jacobian Matrix
The Jacobian matrix of the vector function f = (f1(x1,...,xn),...,fn(x1,...,xn)) is the matrix of the
derivatives of f:
∂f1 ∂f1
⋯
∂x1 ∂xn
J x1, …xn = ⋮ ⋱ ⋮
∂fn ∂fn
⋯
∂x1 ∂xn
Version History
Introduced before R2006a
See Also
curl | divergence | diff | gradient | hessian | laplacian | potential | vectorPotential
7-864
jacobiCD
jacobiCD
Jacobi CD elliptic function
Syntax
jacobiCD(u,m)
Description
jacobiCD(u,m) returns the “Jacobi CD Elliptic Function” on page 7-867 of u and m. If u or m is an
array, then jacobiCD acts element-wise.
Examples
jacobiCD(2,1)
ans =
1
ans =
1.0000 2.3829 -178.6290
Convert numeric input to symbolic form using sym, and find the Jacobi CD elliptic function. For
symbolic input where u = 0 or m = 0 or 1, jacobiCD returns exact symbolic output.
jacobiCD(sym(2),sym(1))
ans =
1
Show that for other values of u or m, jacobiCD returns an unevaluated function call.
jacobiCD(sym(2),sym(3))
ans =
jacobiCD(2, 3)
For symbolic variables or expressions, jacobiCD returns the unevaluated function call.
7-865
7 Functions
syms x y
f = jacobiCD(x,y)
f =
jacobiCD(x, y)
Substitute values for the variables by using subs, and convert values to double by using double.
f =
jacobiCD(3, 5)
fVal = double(f)
fVal =
1.0019
fVal = vpa(f)
fVal =
1.0019475527333315357888731083364
Plot the Jacobi CD elliptic function using fcontour. Set u on the x-axis and m on the y-axis by using
the symbolic function f with the variable order (u,m). Fill plot contours by setting Fill to on.
syms f(u,m)
f(u,m) = jacobiCD(u,m);
fcontour(f,'Fill','on')
title('Jacobi CD Elliptic Function')
xlabel('u')
ylabel('m')
7-866
jacobiCD
Input Arguments
u — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
m — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
More About
Jacobi CD Elliptic Function
7-867
7 Functions
The Jacobi elliptic functions are meromorphic and doubly periodic in their first argument with periods
4K(m) and 4iK'(m), where K is the complete elliptic integral of the first kind, implemented as
ellipticK.
Version History
Introduced in R2017b
See Also
jacobiAM | jacobiCN | jacobiCS | jacobiDC | jacobiDN | jacobiDS | jacobiNC | jacobiND |
jacobiNS | jacobiSC | jacobiSD | jacobiSN | jacobiZeta | ellipticK
7-868
jacobiCN
jacobiCN
Jacobi CN elliptic function
Syntax
jacobiCN(u,m)
Description
jacobiCN(u,m) returns the “Jacobi CN Elliptic Function” on page 7-871 of u and m. If u or m is an
array, then jacobiCN acts element-wise.
Examples
jacobiCN(2,1)
ans =
0.2658
ans =
0.2658 0.7405 0.8165
Convert numeric input to symbolic form using sym, and find the Jacobi CN elliptic function. For
symbolic input where u = 0 or m = 0 or 1, jacobiCN returns exact symbolic output.
jacobiCN(sym(2),sym(1))
ans =
1/cosh(2)
Show that for other values of u or m, jacobiCN returns an unevaluated function call.
jacobiCN(sym(2),sym(3))
ans =
jacobiCN(2, 3)
For symbolic variables or expressions, jacobiCN returns the unevaluated function call.
7-869
7 Functions
syms x y
f = jacobiCN(x,y)
f =
jacobiCN(x, y)
Substitute values for the variables by using subs, and convert values to double by using double.
f =
jacobiCN(3, 5)
fVal = double(f)
fVal =
0.9995
fVal = vpa(f)
fVal =
0.9995148837279268257000709197021
Plot the Jacobi CN elliptic function using fcontour. Set u on the x-axis and m on the y-axis by using
the symbolic function f with the variable order (u,m). Fill plot contours by setting Fill to on.
syms f(u,m)
f(u,m) = jacobiCN(u,m);
fcontour(f,'Fill','on')
title('Jacobi CN Elliptic Function')
xlabel('u')
ylabel('m')
7-870
jacobiCN
Input Arguments
u — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
m — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
More About
Jacobi CN Elliptic Function
The Jacobi CN elliptic function is cn(u,m) = cos(am(u,m)) where am is the Jacobi amplitude function.
7-871
7 Functions
The Jacobi elliptic functions are meromorphic and doubly periodic in their first argument with periods
4K(m) and 4iK'(m), where K is the complete elliptic integral of the first kind, implemented as
ellipticK.
Version History
Introduced in R2017b
See Also
jacobiAM | jacobiCD | jacobiCS | jacobiDC | jacobiDN | jacobiDS | jacobiNC | jacobiND |
jacobiNS | jacobiSC | jacobiSD | jacobiSN | jacobiZeta | ellipticK
7-872
jacobiCS
jacobiCS
Jacobi CS elliptic function
Syntax
jacobiCS(u,m)
Description
jacobiCS(u,m) returns the “Jacobi CS Elliptic Function” on page 7-875 of u and m. If u or m is an
array, then jacobiCS acts element-wise.
Examples
jacobiCS(2,1)
ans =
0.2757
ans =
0.2757 1.1017 1.4142
Convert numeric input to symbolic form using sym, and find the Jacobi CS elliptic function. For
symbolic input where u = 0 or m = 0 or 1, jacobiCS returns exact symbolic output.
jacobiCS(sym(2),sym(1))
ans =
1/sinh(2)
Show that for other values of u or m, jacobiCS returns an unevaluated function call.
jacobiCS(sym(2),sym(3))
ans =
jacobiCS(2, 3)
For symbolic variables or expressions, jacobiCS returns the unevaluated function call.
7-873
7 Functions
syms x y
f = jacobiCS(x,y)
f =
jacobiCS(x, y)
Substitute values for the variables by using subs, and convert values to double by using double.
f =
jacobiCS(3, 5)
fVal = double(f)
fVal =
32.0925
fVal = vpa(f)
fVal =
32.092535022751828816106562829547
Plot the Jacobi CS elliptic function using fcontour. Set u on the x-axis and m on the y-axis by using
the symbolic function f with the variable order (u,m). Fill plot contours by setting Fill to on.
syms f(u,m)
f(u,m) = jacobiCS(u,m);
fcontour(f,'Fill','on')
title('Jacobi CS Elliptic Function')
xlabel('u')
ylabel('m')
7-874
jacobiCS
Input Arguments
u — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
m — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
More About
Jacobi CS Elliptic Function
7-875
7 Functions
The Jacobi elliptic functions are meromorphic and doubly periodic in their first argument with periods
4K(m) and 4iK'(m), where K is the complete elliptic integral of the first kind, implemented as
ellipticK.
Version History
Introduced in R2017b
See Also
jacobiAM | jacobiCD | jacobiCN | jacobiDC | jacobiDN | jacobiDS | jacobiNC | jacobiND |
jacobiNS | jacobiSC | jacobiSD | jacobiSN | jacobiZeta | ellipticK
7-876
jacobiDC
jacobiDC
Jacobi DC elliptic function
Syntax
jacobiDC(u,m)
Description
jacobiDC(u,m) returns the “Jacobi DC Elliptic Function” on page 7-879 of u and m. If u or m is an
array, then jacobiDC acts element-wise.
Examples
jacobiDC(2,1)
ans =
1
ans =
1.0000 0.4197 -0.0056
Convert numeric input to symbolic form using sym, and find the Jacobi DC elliptic function. For
symbolic input where u = 0 or m = 0 or 1,jacobiDC returns exact symbolic output.
jacobiDC(sym(2),sym(1))
ans =
1
Show that for other values of u or m, jacobiDC returns an unevaluated function call.
jacobiDC(sym(2),sym(3))
ans =
jacobiDC(2, 3)
For symbolic variables or expressions, jacobiDC returns the unevaluated function call.
7-877
7 Functions
syms x y
f = jacobiDC(x,y)
f =
jacobiDC(x, y)
Substitute values for the variables by using subs, and convert values to double by using double.
f =
jacobiDC(3, 5)
fVal = double(f)
fVal =
0.9981
fVal = vpa(f)
fVal =
0.99805623285568333815968501058428
Plot the Jacobi DC elliptic function using fcontour. Set u on the x-axis and m on the y-axis by using
the symbolic function f with the variable order (u,m). Fill plot contours by setting Fill to on.
syms f(u,m)
f(u,m) = jacobiDC(u,m);
fcontour(f,'Fill','on')
title('Jacobi DC Elliptic Function')
xlabel('u')
ylabel('m')
7-878
jacobiDC
Input Arguments
u — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
m — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
More About
Jacobi DC Elliptic Function
7-879
7 Functions
The Jacobi elliptic functions are meromorphic and doubly periodic in their first argument with periods
4K(m) and 4iK'(m), where K is the complete elliptic integral of the first kind, implemented as
ellipticK.
Version History
Introduced in R2017b
See Also
jacobiAM | jacobiCD | jacobiCN | jacobiCS | jacobiDN | jacobiDS | jacobiNC | jacobiND |
jacobiNS | jacobiSC | jacobiSD | jacobiSN | jacobiZeta | ellipticK
7-880
jacobiDN
jacobiDN
Jacobi DN elliptic function
Syntax
jacobiDN(u,m)
Description
jacobiDN(u,m) returns the “Jacobi DN Elliptic Function” on page 7-883 of u and m. If u or m is an
array, then jacobiDN acts element-wise.
Examples
jacobiDN(2,1)
ans =
0.2658
ans =
0.2658 0.3107 -0.0046
Convert numeric input to symbolic form using sym, and find the Jacobi DN elliptic function. For
symbolic input where u = 0 or m = 0 or 1, jacobiDN returns exact symbolic output.
jacobiDN(sym(2),sym(1))
ans =
1/cosh(2)
Show that for other values of u or m, jacobiDN returns an unevaluated function call.
jacobiDN(sym(2),sym(3))
ans =
jacobiDN(2, 3)
For symbolic variables or expressions, jacobiDN returns the unevaluated function call.
7-881
7 Functions
syms x y
f = jacobiDN(x,y)
f =
jacobiDN(x, y)
Substitute values for the variables by using subs, and convert values to double by using double.
f =
jacobiDN(3, 5)
fVal = double(f)
fVal =
0.9976
fVal = vpa(f)
fVal =
0.99757205953668099307853539907267
Plot the Jacobi DN elliptic function using fcontour. Set u on the x-axis and m on the y-axis by using
the symbolic function f with the variable order (u,m). Fill plot contours by setting Fill to on.
syms f(u,m)
f(u,m) = jacobiDN(u,m);
fcontour(f,'Fill','on')
title('Jacobi DN Elliptic Function')
xlabel('u')
ylabel('m')
7-882
jacobiDN
Input Arguments
u — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
m — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
More About
Jacobi DN Elliptic Function
2
dn u, m = 1 − msin(ϕ)
7-883
7 Functions
where ϕ is such that F(ϕ,m) = u and F represents the incomplete elliptic integral of the first kind. F is
implemented as ellipticF.
The Jacobi elliptic functions are meromorphic and doubly periodic in their first argument with periods
4K(m) and 4iK'(m), where K is the complete elliptic integral of the first kind, implemented as
ellipticK.
Version History
Introduced in R2017b
See Also
jacobiAM | jacobiCD | jacobiCN | jacobiCS | jacobiDC | jacobiDS | jacobiNC | jacobiND |
jacobiNS | jacobiSC | jacobiSD | jacobiSN | jacobiZeta | ellipticK
7-884
jacobiDS
jacobiDS
Jacobi DS elliptic function
Syntax
jacobiDS(u,m)
Description
jacobiDS(u,m) returns the “Jacobi DS Elliptic Function” on page 7-887 of u and m. If u or m is an
array, then jacobiDS acts element-wise.
Examples
jacobiDS(2,1)
ans =
0.2757
ans =
0.2757 0.4623 -0.0079
Convert numeric input to symbolic form using sym, and find the Jacobi DS elliptic function. For
symbolic input where u = 0 or m = 0 or 1, jacobiDS returns exact symbolic output.
jacobiDS(sym(2),sym(1))
ans =
1/sinh(2)
Show that for other values of u or m, jacobiDS returns an unevaluated function call.
jacobiDS(sym(2),sym(3))
ans =
jacobiDS(2, 3)
For symbolic variables or expressions, jacobiDS returns the unevaluated function call.
7-885
7 Functions
syms x y
f = jacobiDS(x,y)
f =
jacobiDS(x, y)
Substitute values for the variables by using subs, and convert values to double by using double.
f =
jacobiDS(3, 5)
fVal = double(f)
fVal =
32.0302
fVal = vpa(f)
fVal =
32.030154607596772037587224629884
Plot the Jacobi DS elliptic function using fcontour. Set u on the x-axis and m on the y-axis by using
the symbolic function f with the variable order (u,m). Fill plot contours by setting Fill to on.
syms f(u,m)
f(u,m) = jacobiDS(u,m);
fcontour(f,'Fill','on')
title('Jacobi DS Elliptic Function')
xlabel('u')
ylabel('m')
7-886
jacobiDS
Input Arguments
u — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
m — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
More About
Jacobi DS Elliptic Function
7-887
7 Functions
The Jacobi elliptic functions are meromorphic and doubly periodic in their first argument with periods
4K(m) and 4iK'(m), where K is the complete elliptic integral of the first kind, implemented as
ellipticK.
Version History
Introduced in R2017b
See Also
jacobiAM | jacobiCD | jacobiCN | jacobiCS | jacobiDC | jacobiDN | jacobiNC | jacobiND |
jacobiNS | jacobiSC | jacobiSD | jacobiSN | jacobiZeta | ellipticK
7-888
jacobiNC
jacobiNC
Jacobi NC elliptic function
Syntax
jacobiNC(u,m)
Description
jacobiNC(u,m) returns the “Jacobi NC Elliptic Function” on page 7-891 of u and m. If u or m is an
array, then jacobiNC acts element-wise.
Examples
jacobiNC(2,1)
ans =
3.7622
ans =
3.7622 1.3505 1.2247
Convert numeric input to symbolic form using sym, and find the Jacobi NC elliptic function. For
symbolic input where u = 0 or m = 0 or 1, jacobiNC returns exact symbolic output.
jacobiNC(sym(2),sym(1))
ans =
cosh(2)
Show that for other values of u or m, jacobiNC returns an unevaluated function call.
jacobiNC(sym(2),sym(3))
ans =
jacobiNC(2, 3)
For symbolic variables or expressions, jacobiNC returns the unevaluated function call.
7-889
7 Functions
syms x y
f = jacobiNC(x,y)
f =
jacobiNC(x, y)
Substitute values for the variables by using subs, and convert values to double by using double.
f =
jacobiNC(3, 5)
fVal = double(f)
fVal =
1.0005
fVal = vpa(f)
fVal =
1.0004853517240922102007985618873
Plot the Jacobi NC elliptic function using fcontour. Set u on the x-axis and m on the y-axis by using
the symbolic function f with the variable order (u,m). Fill plot contours by setting Fill to on.
syms f(u,m)
f(u,m) = jacobiNC(u,m);
fcontour(f,'Fill','on')
title('Jacobi NC Elliptic Function')
xlabel('u')
ylabel('m')
7-890
jacobiNC
Input Arguments
u — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
m — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
More About
Jacobi NC Elliptic Function
7-891
7 Functions
The Jacobi elliptic functions are meromorphic and doubly periodic in their first argument with periods
4K(m) and 4iK'(m), where K is the complete elliptic integral of the first kind, implemented as
ellipticK.
Version History
Introduced in R2017b
See Also
jacobiAM | jacobiCD | jacobiCN | jacobiCS | jacobiDC | jacobiDN | jacobiDS | jacobiND |
jacobiNS | jacobiSC | jacobiSD | jacobiSN | jacobiZeta | ellipticK
7-892
jacobiND
jacobiND
Jacobi ND elliptic function
Syntax
jacobiND(u,m)
Description
jacobiND(u,m) returns the “Jacobi ND Elliptic Function” on page 7-895 of u and m. If u or m is an
array, then jacobiND acts element-wise.
Examples
jacobiND(2,1)
ans =
3.7622
ans =
3.7622 3.2181 -218.7739
Convert numeric input to symbolic form using sym, and find the Jacobi ND elliptic function. For
symbolic input where u = 0 or m = 0 or 1, jacobiND returns exact symbolic output.
jacobiND(sym(2),sym(1))
ans =
cosh(2)
Show that for other values of u or m, jacobiND returns an unevaluated function call.
jacobiND(sym(2),sym(3))
ans =
jacobiND(2, 3)
For symbolic variables or expressions, jacobiND returns the unevaluated function call.
7-893
7 Functions
syms x y
f = jacobiND(x,y)
f =
jacobiND(x, y)
Substitute values for the variables by using subs, and convert values to double by using double.
f =
jacobiND(3, 5)
fVal = double(f)
fVal =
1.0024
fVal = vpa(f)
fVal =
1.0024338497055006289470589737758
Plot the Jacobi ND elliptic function using fcontour. Set u on the x-axis and m on the y-axis by using
the symbolic function f with the variable order (u,m). Fill plot contours by setting Fill to on.
syms f(u,m)
f(u,m) = jacobiND(u,m);
fcontour(f,'Fill','on')
title('Jacobi ND Elliptic Function')
xlabel('u')
ylabel('m')
7-894
jacobiND
Input Arguments
u — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
m — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
More About
Jacobi ND Elliptic Function
7-895
7 Functions
The Jacobi elliptic functions are meromorphic and doubly periodic in their first argument with periods
4K(m) and 4iK'(m), where K is the complete elliptic integral of the first kind, implemented as
ellipticK.
Version History
Introduced in R2017b
See Also
jacobiAM | jacobiCD | jacobiCN | jacobiCS | jacobiDC | jacobiDN | jacobiDS | jacobiNC |
jacobiNS | jacobiSC | jacobiSD | jacobiSN | jacobiZeta | ellipticK
7-896
jacobiNS
jacobiNS
Jacobi NS elliptic function
Syntax
jacobiNS(u,m)
Description
jacobiNS(u,m) returns the “Jacobi NS Elliptic Function” on page 7-899 of u and m. If u or m is an
array, then jacobiNS acts element-wise.
Examples
jacobiNS(2,1)
ans =
1.0373
ans =
1.0373 1.4879 1.7321
Convert numeric input to symbolic form using sym, and find the Jacobi NS elliptic function. For
symbolic input where u = 0 or m = 0 or 1, jacobiNS returns exact symbolic output.
jacobiNS(sym(2),sym(1))
ans =
coth(2)
Show that for other values of u or m, jacobiNS returns an unevaluated function call.
jacobiNS(sym(2),sym(3))
ans =
jacobiNS(2, 3)
For symbolic variables or expressions, jacobiNS returns the unevaluated function call.
7-897
7 Functions
syms x y
f = jacobiNS(x,y)
f =
jacobiNS(x, y)
Substitute values for the variables by using subs, and convert values to double by using double.
f =
jacobiNS(3, 5)
fVal = double(f)
fVal =
32.1081
fVal = vpa(f)
fVal =
32.108111189955611054545195854805
Plot the Jacobi NS elliptic function using fcontour. Set u on the x-axis and m on the y-axis by using
the symbolic function f with the variable order (u,m). Fill plot contours by setting Fill to on.
syms f(u,m)
f(u,m) = jacobiNS(u,m);
fcontour(f,'Fill','on')
title('Jacobi NS Elliptic Function')
xlabel('u')
ylabel('m')
7-898
jacobiNS
Input Arguments
u — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
m — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
More About
Jacobi NS Elliptic Function
7-899
7 Functions
The Jacobi elliptic functions are meromorphic and doubly periodic in their first argument with periods
4K(m) and 4iK'(m), where K is the complete elliptic integral of the first kind, implemented as
ellipticK.
Version History
Introduced in R2017b
See Also
jacobiAM | jacobiCD | jacobiCN | jacobiCS | jacobiDC | jacobiDN | jacobiDS | jacobiNC |
jacobiND | jacobiSC | jacobiSD | jacobiSN | jacobiZeta | ellipticK
7-900
jacobiP
jacobiP
Jacobi polynomials
Syntax
jacobiP(n,a,b,x)
Description
jacobiP(n,a,b,x) returns the nth degree Jacobi polynomial on page 7-904 with parameters a and
b at x.
Examples
Find Jacobi Polynomials for Numeric and Symbolic Inputs
jacobiP(2,0.5,-3,6)
ans =
7.3438
syms n a b x
jacobiP(n,a,b,x)
ans =
jacobiP(n, a, b, x)
If the degree of the Jacobi polynomial is not specified, jacobiP cannot find the polynomial and
returns the function call.
Specify the degree of the Jacobi polynomial as 1 to return the form of the polynomial.
J = jacobiP(1,a,b,x)
J =
a/2 - b/2 + x*(a/2 + b/2 + 1)
To find the numeric value of a Jacobi polynomial, call jacobiP with the numeric values directly. Do
not substitute into the symbolic polynomial because the result can be inaccurate due to round-off.
Test this by using subs to substitute into the symbolic polynomial, and compare the result with a
numeric call.
ans =
101573673381249394050.64541318209
7-901
7 Functions
ans =
0.032559931334979678350422392588404
When subs is used to substitute into the symbolic polynomial, the numeric result is subject to round-
off error. The direct numerical call to jacobiP is accurate.
syms x
jacobiP([1 2],3,1,x)
ans =
[ 3*x + 1, 7*x^2 + (7*x)/2 - 1/2]
If multiple inputs are specified as a vector, matrix, or multidimensional array, these inputs must be
the same size. Find the Jacobi polynomials for a = [1 2;3 1], b = [2 2;1 3], n = 1 and x.
a = [1 2;3 1];
b = [2 2;1 3];
J = jacobiP(1,a,b,x)
J =
[ (5*x)/2 - 1/2, 3*x]
[ 3*x + 1, 3*x - 1]
jacobiP acts element-wise on a and b to return a matrix of the same size as a and b.
Plot Jacobi polynomials of degree 1, 2, and 3 for a = 3, b = 3, and -1<x<1. To better view the plot,
set axis limits by using axis.
syms x
fplot(jacobiP(1:3,3,3,x))
axis([-1 1 -2 2])
grid on
ylabel('P_n^{(\alpha,\beta)}(x)')
title('Zeros of Jacobi polynomials of degree=1,2,3 with a=3 and b=3');
legend('1','2','3','Location','best')
7-902
jacobiP
a b
The Jacobi polynomials P(n,a,b,x) are orthogonal with respect to the weight function 1 − x 1−x
on the interval [-1,1].
a b
Prove P(3,a,b,x) and P(5,a,b,x) are orthogonal with respect to the weight function 1 − x 1−x by
integrating their product over the interval [-1,1], where a = 3.5 and b = 7.2.
syms x
a = 3.5;
b = 7.2;
P3 = jacobiP(3, a, b, x);
P5 = jacobiP(5, a, b, x);
w = (1-x)^a*(1+x)^b;
int(P3*P5*w, x, -1, 1)
ans =
0
Input Arguments
n — Degree of Jacobi polynomial
nonnegative integer | vector of nonnegative integers | matrix of nonnegative integers |
multidimensional array of nonnegative integers | symbolic nonnegative integer | symbolic variable |
7-903
7 Functions
a — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic vector | symbolic
matrix | symbolic function | symbolic expression | symbolic multidimensional array
Input, specified as a number, vector, matrix, multidimensional array, or a symbolic number, vector,
matrix, function, expression, or multidimensional array.
b — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic vector | symbolic
matrix | symbolic function | symbolic expression | symbolic multidimensional array
Input, specified as a number, vector, matrix, multidimensional array, or a symbolic number, vector,
matrix, function, expression, or multidimensional array.
x — Evaluation point
number | vector | matrix | multidimensional array | symbolic number | symbolic vector | symbolic
matrix | symbolic function | symbolic expression | symbolic multidimensional array
Evaluation point, specified as a number, vector, matrix, multidimensional array, or a symbolic number,
vector, matrix, function, expression, or multidimensional array.
More About
Jacobi Polynomials
1 0 if n ≠ m
∫ P(n, a, b, x)P(m, a, b, x) 1 − x
−1
a
1+x
b
dx = 2
a+b+1
Γ n+a+1 Γ n+b+1
if n = m .
2n + a + b + 1 Γ n + a + b + 1 n!
• For a = 0 and b = 0, the Jacobi polynomials P(n,0,0,x) reduce to the Legendre polynomials P(n, x).
• The relation between Jacobi polynomials P(n,a,b,x) and Chebyshev polynomials of the first kind
T(n,x) is
7-904
jacobiP
2n 2
2 n! 1 1
T n, x = P n, − , − , x .
2n ! 2 2
• The relation between Jacobi polynomials P(n,a,b,x) and Chebyshev polynomials of the second kind
U(n,x) is
2n
2 n! n + 1 ! 1 1
U n, x = P n, , , x .
2n + 1 ! 2 2
• The relation between Jacobi polynomials P(n,a,b,x) and Gegenbauer polynomials G(n,a,x) is
1
Γ a+ 2
Γ n + 2a 1 1
G n, a, x = P n, a − ,a − ,x .
Γ 2a Γ n + a +
1 2 2
2
Version History
Introduced in R2014b
See Also
chebyshevT | chebyshevU | gegenbauerC | hermiteH | hypergeom | laguerreL | legendreP
7-905
7 Functions
jacobiSC
Jacobi SC elliptic function
Syntax
jacobiSC(u,m)
Description
jacobiSC(u,m) returns the “Jacobi SC Elliptic Function” on page 7-908 of u and m. If u or m is an
array, then jacobiSC acts element-wise.
Examples
jacobiSC(2,1)
ans =
3.6269
ans =
3.6269 0.9077 0.7071
Convert numeric input to symbolic form using sym, and find the Jacobi SC elliptic function. For
symbolic input where u = 0 or m = 0 or 1, jacobiSC returns exact symbolic output.
jacobiSC(sym(2),sym(1))
ans =
sinh(2)
Show that for other values of u or m, jacobiSC returns an unevaluated function call.
jacobiSC(sym(2),sym(3))
ans =
jacobiSC(2, 3)
For symbolic variables or expressions, jacobiSC returns the unevaluated function call.
7-906
jacobiSC
syms x y
f = jacobiSC(x,y)
f =
jacobiSC(x, y)
Substitute values for the variables by using subs, and convert values to double by using double.
f =
jacobiSC(3, 5)
fVal = double(f)
fVal =
0.0312
fVal = vpa(f)
fVal =
0.031159894327171581127518352857409
Plot the Jacobi SC elliptic function using fcontour. Set u on the x-axis and m on the y-axis by using
the symbolic function f with the variable order (u,m). Fill plot contours by setting Fill to on.
syms f(u,m)
f(u,m) = jacobiSC(u,m);
fcontour(f,'Fill','on')
title('Jacobi SC Elliptic Function')
xlabel('u')
ylabel('m')
7-907
7 Functions
Input Arguments
u — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
m — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
More About
Jacobi SC Elliptic Function
7-908
jacobiSC
The Jacobi elliptic functions are meromorphic and doubly periodic in their first argument with periods
4K(m) and 4iK'(m), where K is the complete elliptic integral of the first kind, implemented as
ellipticK.
Version History
Introduced in R2017b
See Also
jacobiAM | jacobiCD | jacobiCN | jacobiCS | jacobiDC | jacobiDN | jacobiDS | jacobiNC |
jacobiND | jacobiNS | jacobiSD | jacobiSN | jacobiZeta | ellipticK
7-909
7 Functions
jacobiSD
Jacobi SD elliptic function
Syntax
jacobiSD(u,m)
Description
jacobiSD(u,m) returns the “Jacobi SD Elliptic Function” on page 7-912 of u and m. If u or m is an
array, then jacobiSD acts element-wise.
Examples
jacobiSD(2,1)
ans =
3.6269
ans =
3.6269 2.1629 -126.3078
Convert numeric input to symbolic form using sym, and find the Jacobi SD elliptic function. For
symbolic input where u = 0 or m = 0 or 1, jacobiSD returns exact symbolic output.
jacobiSD(sym(2),sym(1))
ans =
sinh(2)
Show that for other values of u or m, jacobiSD returns an unevaluated function call.
jacobiSD(sym(2),sym(3))
ans =
jacobiSD(2, 3)
For symbolic variables or expressions, jacobiSD returns the unevaluated function call.
7-910
jacobiSD
syms x y
f = jacobiSD(x,y)
f =
jacobiSD(x, y)
Substitute values for the variables by using subs, and convert values to double by using double.
f =
jacobiSD(3, 5)
fVal = double(f)
fVal =
0.0312
fVal = vpa(f)
fVal =
0.031220579864538785956650143970485
Plot the Jacobi SD elliptic function using fcontour. Set u on the x-axis and m on the y-axis by using
the symbolic function f with the variable order (u,m). Fill plot contours by setting Fill to on.
syms f(u,m)
f(u,m) = jacobiSD(u,m);
fcontour(f,'Fill','on')
title('Jacobi SD Elliptic Function')
xlabel('u')
ylabel('m')
7-911
7 Functions
Input Arguments
u — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
m — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
More About
Jacobi SD Elliptic Function
7-912
jacobiSD
The Jacobi elliptic functions are meromorphic and doubly periodic in their first argument with periods
4K(m) and 4iK'(m), where K is the complete elliptic integral of the first kind, implemented as
ellipticK.
Version History
Introduced in R2017b
See Also
jacobiAM | jacobiCD | jacobiCN | jacobiCS | jacobiDC | jacobiDN | jacobiDS | jacobiNC |
jacobiND | jacobiNS | jacobiSC | jacobiSN | jacobiZeta | ellipticK
7-913
7 Functions
jacobiSN
Jacobi SN elliptic function
Syntax
jacobiSN(u,m)
Description
jacobiSN(u,m) returns the “Jacobi SN Elliptic Function” on page 7-916 of u and m. If u or m is an
array, then jacobiSN acts element-wise.
Examples
jacobiSN(2,1)
ans =
0.9640
ans =
0.9640 0.6721 0.5773
Convert numeric input to symbolic form using sym, and find the Jacobi SN elliptic function. For
symbolic input where u = 0 or m = 0 or 1, jacobiSN returns exact symbolic output.
jacobiSN(sym(2),sym(1))
ans =
tanh(2)
Show that for other values of u or m, jacobiSN returns an unevaluated function call.
jacobiSN(sym(2),sym(3))
ans =
jacobiSN(2, 3)
For symbolic variables or expressions, jacobiSN returns the unevaluated function call.
7-914
jacobiSN
syms x y
f = jacobiSN(x,y)
f =
jacobiSN(x, y)
Substitute values for the variables by using subs, and convert values to double by using double.
f =
jacobiSN(3, 5)
fVal = double(f)
fVal =
0.0311
fVal = vpa(f)
fVal =
0.031144778155397389598324170696454
Plot the Jacobi SN elliptic function using fcontour. Set u on the x-axis and m on the y-axis by using
the symbolic function f with the variable order (u,m). Fill plot contours by setting Fill to on.
syms f(u,m)
f(u,m) = jacobiSN(u,m);
fcontour(f,'Fill','on')
title('Jacobi SN Elliptic Function')
xlabel('u')
ylabel('m')
7-915
7 Functions
Input Arguments
u — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
m — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
More About
Jacobi SN Elliptic Function
The Jacobi SN elliptic function is sn(u,m) = sin(am(u,m)) where am is the Jacobi amplitude function.
7-916
jacobiSN
The Jacobi elliptic functions are meromorphic and doubly periodic in their first argument with periods
4K(m) and 4iK'(m), where K is the complete elliptic integral of the first kind, implemented as
ellipticK.
Version History
Introduced in R2017b
See Also
jacobiAM | jacobiCD | jacobiCN | jacobiCS | jacobiDC | jacobiDN | jacobiDS | jacobiNC |
jacobiND | jacobiNS | jacobiSC | jacobiSD | jacobiZeta | ellipticK
7-917
7 Functions
jacobiSymbol
Jacobi symbol
Syntax
J = jacobiSymbol(a,n)
Description
J = jacobiSymbol(a,n) returns the value of the Jacobi symbol on page 7-921 for integer a and
positive odd integer n.
Examples
a = 1:9;
n = 3;
J = jacobiSymbol(a,n)
J = 1×9
1 -1 0 1 -1 0 1 -1 0
a b
The Jacobi symbol is periodic with respect to its first argument, where = if a ≡ b (mod n).
n n
J = jacobiSymbol(28,9)
J = 1
The Jacobi symbol is a completely multiplicative function, where the Jacobi symbol satisfies the
a a1 a2 ar
relation = × ×… for a = a1 × a2 × …ar . Show that the Jacobi symbol follows this
n n n n
relation for a = 28 = 2 × 2 × 7.
Ja = jacobiSymbol(2,9)*jacobiSymbol(2,9)*jacobiSymbol(7,9)
Ja = 1
7-918
jacobiSymbol
a a a a
The Jacobi symbol also satisfies the relation = × ×… for n = n1 × n2 × …nr . Show
n n1 n2 nr
that the Jacobi symbol follows this relation for n = 9 = 3 × 3.
Jb = jacobiSymbol(28,3)*jacobiSymbol(28,3)
Jb = 1
a
You can use the Jacobi symbol for the Solovay–Strassen primality test. If an odd integer n > 1 is
n
prime, then the congruence
a
≡ a(n − 1)/2 (mod n)
n
must hold for all integers a. If there is an integer a in 1, 2, …, n − 1 such that the congruence
relation is not satisfied, then n is not prime.
Check if n = 561 is prime or not. Choose a = 19 and perform the primality test. Compare the two
values in the congruence relation.
First calculate the left side of the congruence relation using the Jacobi symbol.
n = 561;
a = 14;
J = jacobiSymbol(a,n)
J = 1
m = powermod(a,(n-1)/2,n)
m = 67
The integer n = 561 is not prime since it does not satisfy the congruence relation for a = 19.
checkPrime = mod(J,n) == m
checkPrime = logical
0
Next, check if n = 557 is prime or not. Choose a = 19 and perform the primality test.
n = 557;
a = 19;
J = jacobiSymbol(a,n);
m = powermod(a,(n-1)/2,n);
The integer n = 557 is probably prime since it satisfies the congruence relation for a = 19.
checkPrime = mod(J,n) == m
7-919
7 Functions
checkPrime = logical
1
Perform the primality test for all a in 1, 2, …, 556 to confirm that the integer n = 557 is indeed
prime.
a = 1:n-1;
J = jacobiSymbol(a,n);
m = powermod(a,(n-1)/2,n);
checkPrime = all(mod(J,n) == m)
checkPrime = logical
1
isprime(n)
ans = logical
1
Input Arguments
a — Input
number | vector | matrix | array | symbolic number | symbolic array
Input, specified as a number, vector, matrix, array, symbolic number, or symbolic array. The elements
of a must be integers. a and n must be the same size, or else one of them must be a scalar.
Data Types: single | double | sym
n — Input
number | vector | matrix | array | symbolic number | symbolic array
Input, specified as a number, vector, matrix, array, symbolic number, or symbolic array. The elements
of n must be positive odd integers. a and n must be the same size, or else one of them must be a
scalar.
Data Types: single | double | sym
Output Arguments
J — Output value
–1 | 0 | 1
7-920
jacobiSymbol
More About
Jacobi Symbol
k1 k2 kr
a a a a
= …
n p1 p2 pr
0 if a ≡ 0 (mod p)
a
p
= 1 if a is a quadratic residue modulo p or x2 ≡ a (mod p) has a nonzero solution for x
−1 if a is a quadratic nonresidue modulo p or x2 ≡ a (mod p) has no solutions for x.
When n is an odd prime, the Jacobi symbol is equal to the Legendre symbol.
Version History
Introduced in R2020a
References
[1] Dietzfelbinger, M. Primality Testing in Polynomial Time: From Randomized Algorithms to "PRIMES
Is in P". Springer, 2004.
See Also
mod | powermod | isprime
7-921
7 Functions
jacobiZeta
Jacobi zeta function
Syntax
jacobiZeta(u,m)
Description
jacobiZeta(u,m) returns the “Jacobi Zeta Function” on page 7-924 of u and m. If u or m is an
array, then jacobiZeta acts element-wise.
Examples
jacobiZeta(2,1)
ans =
0.9640
ans =
0.9640 + 0.0000i 0.5890 - 0.4569i -2.3239 + 1.9847i
Convert numeric input to symbolic form using sym, and find the Jacobi zeta function. For symbolic
input where u = 0 or m = 0 or 1, jacobiZeta returns exact symbolic output.
jacobiZeta(sym(2),sym(1))
ans =
tanh(2)
Show that for other values of u or m, jacobiZeta returns an unevaluated function call.
jacobiZeta(sym(2),sym(3))
ans =
jacobiZeta(2, 3)
For symbolic variables or expressions, jacobiZeta returns the unevaluated function call.
7-922
jacobiZeta
syms x y
f = jacobiZeta(x,y)
f =
jacobiZeta(x, y)
Substitute values for the variables by using subs, and convert values to double by using double.
f =
jacobiZeta(3, 5)
fVal = double(f)
fVal =
4.0986 - 3.0018i
fVal = vpa(f)
fVal =
4.0986033838332279126523721581432 - 3.0017792319714320747021938869936i
Plot real and imaginary values of the Jacobi zeta function using fcontour. Set u on the x-axis and m
on the y-axis by using the symbolic function f with the variable order (u,m). Fill plot contours by
setting Fill to on.
syms f(u,m)
f(u,m) = jacobiZeta(u,m);
subplot(2,2,1)
fcontour(real(f),'Fill','on')
title('Real Values of Jacobi Zeta')
xlabel('u')
ylabel('m')
subplot(2,2,2)
fcontour(imag(f),'Fill','on')
title('Imaginary Values of Jacobi Zeta')
xlabel('u')
ylabel('m')
7-923
7 Functions
Input Arguments
u — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
m — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
More About
Jacobi Zeta Function
E(m)
Z u, m = E(φ, m) − F(φ, m) .
K(m)
7-924
jacobiZeta
• E(φ | m) and E(m) are the incomplete and complete elliptic integrals of the second kind,
respectively, implemented as ellipticE.
• K(m) is the complete elliptic integral of the first kind, implemented as ellipticK.
• F(φ | m) is the incomplete elliptic integral of the first kind, implemented as ellipticF.
• am(u, m) is the Jacobi's amplitude function, implemented as jacobiAM.
The argument u is related to φ by the relations u = F(φ | m) and am(u, m) = φ, where am(u, m) is the
Jacobi's amplitude function.
Version History
Introduced in R2017b
References
[1] Olver, F. W. J., A. B. Olde Daalhuis, D. W. Lozier, B. I. Schneider, R. F. Boisvert, C. W. Clark, B. R.
Miller, B. V. Saunders, H. S. Cohl, and M. A. McClain, eds., Chapter 22. Jacobian Elliptic
Functions, NIST Digital Library of Mathematical Functions, Release 1.0.26 of 2020-03-15.
See Also
jacobiAM | jacobiCD | jacobiCN | jacobiCS | jacobiDC | jacobiDN | jacobiDS | jacobiNC |
jacobiND | jacobiNS | jacobiSC | jacobiSD | jacobiSN
7-925
7 Functions
jordan
Jordan normal form (Jordan canonical form)
Syntax
J = jordan(A)
[V,J] = jordan(A)
Description
J = jordan(A) computes the Jordan normal form of the matrix A. Because the Jordan form of a
numeric matrix is sensitive to numerical errors, prefer converting numeric input to exact symbolic
form.
[V,J] = jordan(A) computes the Jordan form J and the similarity transform V. The matrix V
contains the generalized eigenvectors of A as columns, such that V\A*V = J.
Examples
Compute the Jordan form and the similarity transform for a matrix. Because the Jordan form of a
numeric matrix is sensitive to numerical errors, first convert the matrix to symbolic form by using
sym.
A = [ 1 -3 -2;
-1 1 -1;
2 4 5];
A = sym(A);
[V,J] = jordan(A)
V =
[ -1, 1, -1]
[ -1, 0, 0]
[ 2, 0, 1]
J =
[ 2, 1, 0]
[ 0, 2, 0]
[ 0, 0, 3]
cond = J == V\A*V;
isAlways(cond)
ans =
3×3 logical array
1 1 1
7-926
jordan
1 1 1
1 1 1
Version History
Introduced before R2006a
See Also
charpoly | eig | hermiteForm | inv | smithForm
7-927
7 Functions
kroneckerDelta
Kronecker delta function
Syntax
kroneckerDelta(m)
kroneckerDelta(m,n)
Description
kroneckerDelta(m) returns 1 if m == 0 and 0 if m ~= 0.
Examples
Compare Two Symbolic Variables
Note For kroneckerDelta with numeric inputs, use the eq function instead.
Set symbolic variable m equal to symbolic variable n and test their equality using kroneckerDelta.
syms m n
m = n;
kroneckerDelta(m,n)
ans =
1
ans =
kroneckerDelta(p - q, 0)
kroneckerDelta cannot decide if p == q and returns the function call with the undecidable input.
Note that kroneckerDelta(p, q) is equal to kroneckerDelta(p - q, 0).
To force a logical result for undecidable inputs, use isAlways. The isAlways function issues a
warning and returns logical 0 (false) for undecidable inputs. Set the Unknown option to false to
suppress the warning.
isAlways(kroneckerDelta(p, q), 'Unknown', 'false')
ans =
logical
0
7-928
kroneckerDelta
Set symbolic variable m to 0 and test m for equality with 0. The kroneckerDelta function errors
because it does not accept numeric inputs of type double.
m = 0;
kroneckerDelta(m)
Use sym to convert 0 to a symbolic object before assigning it to m. This is because kroneckerDelta
only accepts symbolic inputs.
syms m
m = sym(0);
kroneckerDelta(m)
ans =
1
V = 1:4
syms m
m = sym(3)
sol = kroneckerDelta(V,m)
V =
1 2 3 4
m =
3
sol =
[ 0, 0, 1, 0]
kroneckerDelta acts on V element-wise to return a vector, sol, which is the same size as V. The
third element of sol is 1 indicating that the third element of V equals m.
syms m
A = [m m+1 m+2;m-2 m-1 m]
B = [m m+3 m+2;m-1 m-1 m+1]
A =
[ m, m + 1, m + 2]
[ m - 2, m - 1, m]
B =
[ m, m + 3, m + 2]
[ m - 1, m - 1, m + 1]
7-929
7 Functions
sol = kroneckerDelta(A,B)
sol =
[ 1, 0, 1]
[ 0, 1, 0]
kroneckerDelta acts on A and B element-wise to return the matrix sol which is the same size as A
and B. The elements of sol that are 1 indicate that the corresponding elements of A and B are equal.
The elements of sol that are 0 indicate that the corresponding elements of A and B are not equal.
syms z n
sol = iztrans(1/(z-1), z, n)
sol =
1 - kroneckerDelta(n, 0)
Use this output as input to ztrans to return the initial input expression.
ztrans(sol, n, z)
ans =
z/(z - 1) - 1
Use filter to find the response of a filter when the input is the Kronecker Delta function. Convert k
to a symbolic vector using sym because kroneckerDelta only accepts symbolic inputs, and convert
it back to double using double. Provide arbitrary filter coefficients a and b for simplicity.
b = [0 1 1];
a = [1 -0.5 0.3];
k = -20:20;
x = double(kroneckerDelta(sym(k)));
y = filter(b,a,x);
plot(k,y)
7-930
kroneckerDelta
Input Arguments
m — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic vector | symbolic
matrix | symbolic function | symbolic multidimensional array
Input, specified as a number, vector, matrix, multidimensional array, or a symbolic number, vector,
matrix, function, or multidimensional array. At least one of the inputs, m or n, must be symbolic.
n — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic vector | symbolic
matrix | symbolic function | symbolic multidimensional array
Input, specified as a number, vector, matrix, multidimensional array, or a symbolic number, vector,
matrix, function, or multidimensional array. At least one of the inputs, m or n, must be symbolic.
More About
Kronecker Delta Function
0 if m ≠ n
δ m, n =
1 if m = n
7-931
7 Functions
Tips
• When m or n is NaN, the kroneckerDelta function returns NaN.
Version History
Introduced in R2014b
See Also
iztrans | ztrans
7-932
kummerU
kummerU
Confluent hypergeometric Kummer U function
Syntax
kummerU(a,b,z)
Description
kummerU(a,b,z) computes the value of confluent hypergeometric function, U(a,b,z). If the real
parts of z and a are positive values, then the integral representations of the Kummer U function is as
follows:
∞
U a, b, z =
1
Γa ∫e
0
−ztta − 1 1+t
b−a−1
dt
Examples
Equation Returning the Kummer U Function as Its Solution
dsolve can return solutions of second-order ordinary differential equations in terms of the Kummer
U function.
Solve this equation. The solver returns the results in terms of the Kummer U function and another
hypergeometric function.
syms t z y(z)
dsolve(z^3*diff(y,2) + (z^2 + t)*diff(y) + z*y)
ans =
(C4*hypergeom(1i/2, 1 + 1i, t/(2*z^2)))/z^1i +...
(C3*kummerU(1i/2, 1 + 1i, t/(2*z^2)))/z^1i
Depending on its arguments, kummerU can return floating-point or exact symbolic results.
Compute the Kummer U function for these numbers. Because these numbers are not symbolic
objects, you get floating-point results.
A = [kummerU(-1/3, 2.5, 2)
kummerU(1/3, 2, pi)
kummerU(1/2, 1/3, 3*i)]
A =
0.8234 + 0.0000i
0.7284 + 0.0000i
0.4434 - 0.3204i
Compute the Kummer U function for the numbers converted to symbolic objects. For most symbolic
(exact) numbers, kummerU returns unresolved symbolic calls.
7-933
7 Functions
symA =
kummerU(-1/3, 5/2, 2)
kummerU(1/3, 2, pi)
kummerU(1/2, 1/3, 3i)
Use vpa to approximate symbolic results with the required number of digits.
vpa(symA,10)
ans =
0.8233667846
0.7284037305
0.4434362538 - 0.3204327531i
syms a b z
[kummerU(-1, b, z)
kummerU(-2, b, z)
kummerU(-3, b, z)]
ans =
z - b
b - 2*z*(b + 1) + b^2 + z^2
6*z*(b^2/2 + (3*b)/2 + 1) - 2*b - 6*z^2*(b/2 + 1) - 3*b^2 - b^3 + z^3
If b = 2*a, the Kummer U function reduces to an expression involving the modified Bessel function
of the second kind.
kummerU(a, 2*a, z)
ans =
(z^(1/2 - a)*exp(z/2)*besselk(a - 1/2, z/2))/pi^(1/2)
kummerU(1, b, z)
ans =
z^(1 - b)*exp(z)*igamma(b - 1, z)
kummerU(a, a, z)
ans =
exp(z)*igamma(1 - a, z)
kummerU(0, a, z)
7-934
kummerU
ans =
1
Many functions, such as diff, int, and limit, can handle expressions containing kummerU.
syms a b z
diff(kummerU(a, b, z), z)
ans =
(a*kummerU(a + 1, b, z)*(a - b + 1))/z - (a*kummerU(a, b, z))/z
int(kummerU(a, b, z), z)
ans =
((b - 2)/(a - 1) - 1)*kummerU(a, b, z) +...
(kummerU(a + 1, b, z)*(a - a*b + a^2))/(a - 1) -...
(z*kummerU(a, b, z))/(a - 1)
ans =
4/(3*pi^(1/2))
Input Arguments
a — Parameter of Kummer U function
number | vector | symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector
7-935
7 Functions
More About
Confluent Hypergeometric Function (Kummer U Function)
The confluent hypergeometric function (Kummer U function) is one of the solutions of the differential
equation
∂2 ∂
z y+ b−z y − ay = 0
∂z 2 ∂z
1
Wa, b z = e−z/2 zb + 1/2 U b − a + , 2b + 1, z
2
Tips
• kummerU returns floating-point results for numeric arguments that are not symbolic objects.
• kummerU acts element-wise on nonscalar inputs.
• All nonscalar arguments must have the same size. If one or two input arguments are nonscalar,
then kummerU expands the scalars into vectors or matrices of the same size as the nonscalar
arguments, with all elements equal to the corresponding scalar.
Version History
Introduced in R2014b
References
[1] Slater, L. J. “Confluent Hypergeometric Functions.” Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New
York: Dover, 1972.
See Also
hypergeom | whittakerM | whittakerW
7-936
laguerreL
laguerreL
Generalized Laguerre Function and Laguerre Polynomials
Syntax
laguerreL(n,x)
laguerreL(n,a,x)
Description
laguerreL(n,x) returns the Laguerre polynomial of degree n if n is a nonnegative integer. When n
is not a nonnegative integer, laguerreL returns the Laguerre function. For details, see “Generalized
Laguerre Function” on page 7-941.
Examples
Find Laguerre Polynomials for Numeric and Symbolic Inputs
laguerreL(3,4.3)
ans =
2.5838
Find the Laguerre polynomial for symbolic inputs. Specify degree n as 3 to return the explicit form of
the polynomial.
syms x
laguerreL(3,x)
ans =
- x^3/6 + (3*x^2)/2 - 3*x + 1
If the degree of the Laguerre polynomial n is not specified, laguerreL cannot find the polynomial.
When laguerreL cannot find the polynomial, it returns the function call.
syms n x
laguerreL(n,x)
ans =
laguerreL(n, x)
Find the explicit form of the generalized Laguerre polynomial L(n,a,x) of degree n = 2.
syms a x
laguerreL(2,a,x)
7-937
7 Functions
ans =
(3*a)/2 - x*(a + 2) + a^2/2 + x^2/2 + 1
When n is not a nonnegative integer, laguerreL(n,a,x) returns the generalized Laguerre function.
laguerreL(-2.7,3,2)
ans =
0.2488
ans =
[ 1 - x, x^2/2 - 2*x + 1]
If multiple inputs are specified as a vector, matrix, or multidimensional array, the inputs must be the
same size. Find the generalized Laguerre polynomials where input arguments n and x are matrices.
syms a
n = [2 3; 1 2];
xM = [x^2 11/7; -3.2 -x];
laguerreL(n,a,xM)
ans =
[ a^2/2 - a*x^2 + (3*a)/2 + x^4/2 - 2*x^2 + 1,...
a^3/6 + (3*a^2)/14 - (253*a)/294 - 676/1029]
[ a + 21/5,...
a^2/2 + a*x + (3*a)/2 + x^2/2 + 2*x + 1]
laguerreL acts element-wise on n and x to return a matrix of the same size as n and x.
Use limit to find the limit of a generalized Laguerre polynomial of degree 3 as x tends to ∞.
syms x
expr = laguerreL(3,2,x);
limit(expr,x,Inf)
ans =
-Inf
Use diff to find the third derivative of the generalized Laguerre polynomial laguerreL(n,a,x).
7-938
laguerreL
syms n a
expr = laguerreL(n,a,x);
diff(expr,x,3)
ans =
-laguerreL(n - 3, a + 3, x)
Use taylor to find the Taylor series expansion of the generalized Laguerre polynomial of degree 2 at
x = 0.
syms a x
expr = laguerreL(2,a,x);
taylor(expr,x)
ans =
(3*a)/2 - x*(a + 2) + a^2/2 + x^2/2 + 1
syms x
fplot(laguerreL(1:4,x))
axis([-2 10 -10 10])
grid on
ylabel('L_n(x)')
title('Laguerre polynomials of orders 1 through 4')
legend('1','2','3','4','Location','best')
7-939
7 Functions
Input Arguments
n — Degree of polynomial
number | vector | matrix | multidimensional array | symbolic number | symbolic vector | symbolic
matrix | symbolic function | symbolic multidimensional array
x — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic vector | symbolic
matrix | symbolic function | symbolic multidimensional array
Input, specified as a number, vector, matrix, multidimensional array, or a symbolic number, vector,
matrix, function, or multidimensional array.
a — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic vector | symbolic
matrix | symbolic function | symbolic multidimensional array
Input, specified as a number, vector, matrix, multidimensional array, or a symbolic number, vector,
matrix, function, or multidimensional array.
7-940
laguerreL
More About
Generalized Laguerre Function
n+a
laguerreL n, a, x = 1F 1 −n; a + 1; x .
a
For nonnegative integer values of n, the function returns the generalized Laguerre polynomials that
are orthogonal with respect to the scalar product
∞
f 1, f 2 = ∫e
0
−xxa f 1 x f 2 x dx .
0 if n ≠ m
laguerreL n, a, x , laguerreL m, a, x = Γ a+n+1
if n = m .
n!
Algorithms
• The generalized Laguerre function is not defined for all values of parameters n and a because
certain restrictions on the parameters exist in the definition of the hypergeometric functions. If
the generalized Laguerre function is not defined for a particular pair of n and a, the laguerreL
function returns an error message. See “Return Generalized Laguerre Function” on page 7-938.
• The calls laguerreL(n,x) and laguerreL(n,0,x) are equivalent.
• If n is a nonnegative integer, the laguerreL function returns the explicit form of the
corresponding Laguerre polynomial.
• n+a
The special values laguerreL n, a, 0 = are implemented for arbitrary values of n and a.
a
• If n is a negative integer and a is a numerical noninteger value satisfying a ≥ -n, then laguerreL
returns 0.
• If n is a negative integer and a is an integer satisfying a < -n, the function returns an explicit
expression defined by the reflection rule
a
laguerreL n, a, x = −1 exlaguerreL −n − a − 1, a, − x
• If all arguments are numerical and at least one argument is a floating-point number, then
laguerreL(x) returns a floating-point number. For all other arguments, laguerreL(n,a,x)
returns a symbolic function call.
Version History
Introduced in R2014b
See Also
chebyshevT | chebyshevU | gegenbauerC | hermiteH | hypergeom | jacobiP | legendreP
7-941
7 Functions
lambertw
Lambert W function
Syntax
lambertw(x)
lambertw(k,x)
Description
lambertw(x) returns the principal branch of the Lambert W function on page 7-949. This syntax is
equivalent to lambertw(0,x).
lambertw(k,x) is the kth branch of the Lambert W function. This syntax returns real values only if
k = 0 or k = -1.
Examples
syms x W
eqn = x == W*exp(W);
solve(eqn,W)
ans =
lambertw(0, x)
Verify that branches of the Lambert W function are valid solutions of the equation x = W*eW:
k = -2:2;
eqn = subs(eqn,W,lambertw(k,x));
isAlways(eqn)
ans =
1×5 logical array
1 1 1 1 1
Depending on its arguments, lambertw can return floating-point or exact symbolic results.
Compute the Lambert W functions for these numbers. Because the numbers are not symbolic objects,
you get floating-point results.
7-942
lambertw
A = [0 -1/exp(1); pi i];
lambertw(A)
ans =
0.0000 + 0.0000i -1.0000 + 0.0000i
1.0737 + 0.0000i 0.3747 + 0.5764i
lambertw(-1,A)
ans =
-Inf + 0.0000i -1.0000 + 0.0000i
-0.3910 - 4.6281i -1.0896 - 2.7664i
Compute the Lambert W functions for the numbers converted to symbolic objects. For most symbolic
(exact) numbers, lambertw returns unresolved symbolic calls.
A = [0 -1/exp(sym(1)); pi i];
W0 = lambertw(A)
W0 =
[ 0, -1]
[ lambertw(0, pi), lambertw(0, 1i)]
Wmin1 = lambertw(-1,A)
Wmin1 =
[ -Inf, -1]
[ lambertw(-1, pi), lambertw(-1, 1i)]
double(W0)
ans =
0.0000 + 0.0000i -1.0000 + 0.0000i
1.0737 + 0.0000i 0.3747 + 0.5764i
Plot the two main branches, W0(x) and W−1(x), of the Lambert W function.
syms x
fplot(lambertw(x))
hold on
fplot(lambertw(-1,x))
hold off
axis([-0.5 4 -4 2])
title('Lambert W function, two main branches')
legend('k=0','k=1','Location','best')
7-943
7 Functions
Plot the principal branch of the Lambert W function on the complex plane.
Plot the real value of the Lambert W function by using fmesh. Simultaneously plot the contours by
setting 'ShowContours' to 'On'.
syms x y
f = lambertw(x + 1i*y);
interval = [-100 100 -100 100];
fmesh(real(f),interval,'ShowContours','On')
7-944
lambertw
Plot the imaginary value of the Lambert W function. The plot has a branch cut along the negative real
axis. Plot the contours separately.
fmesh(imag(f),interval)
7-945
7 Functions
fcontour(imag(f),interval,'Fill','on')
7-946
lambertw
fmesh(abs(f),interval,'ShowContours','On')
7-947
7 Functions
Input Arguments
x — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
At least one input argument must be a scalar, or both arguments must be vectors or matrices of the
same size. If one input argument is a scalar and the other is a vector or matrix, lambertw expands
the scalar into a vector or matrix of the same size as the other argument with all elements equal to
that scalar.
At least one input argument must be a scalar, or both arguments must be vectors or matrices of the
same size. If one input argument is a scalar and the other is a vector or matrix, lambertw expands
the scalar into a vector or matrix of the same size as the other argument with all elements equal to
that scalar.
7-948
lambertw
More About
Lambert W Function
The Lambert W function W(x) represents the solutions y of the equation yey = x for any complex
number x.
• For complex x, the equation has an infinite number of solutions y = lambertW(k,x) where k ranges
over all integers.
• For all real x ≥ 0, the equation has exactly one real solution y = lambertW(x) = lambertW(0,x).
• For real x where −e−1 < x < 0, the equation has exactly two real solutions. The larger solution is
represented by y = lambertW(x) and the smaller solution by y = lambertW(–1,x).
• For x = − e−1, the equation has exactly one real solution y = –1 = lambertW(0, –exp(–1)) =
lambertW(–1, -exp(–1)).
Version History
Introduced before R2006a
References
[1] Corless, R.M., G.H. Gonnet, D.E.G. Hare, D.J. Jeffrey, and D.E. Knuth. "On the Lambert W
Function." Advances in Computational Mathematics, Vol. 5, pp. 329–359, 1996.
See Also
Functions
wrightOmega
7-949
7 Functions
laplace
Laplace transform
Syntax
F = laplace(f)
F = laplace(f,transVar)
F = laplace(f,var,transVar)
Description
F = laplace(f) returns the “Laplace Transform” on page 7-953 of f. By default, the independent
variable is t and the transformation variable is s.
Examples
syms x y
f = 1/sqrt(x);
F = laplace(f)
F =
π
s
Compute the Laplace transform of exp(-a*t). By default, the independent variable is t, and the
transformation variable is s.
syms a t y
f = exp(-a*t);
F = laplace(f)
F =
1
a+s
Specify the transformation variable as y. If you specify only one variable, that variable is the
transformation variable. The independent variable is still t.
7-950
laplace
F = laplace(f,y)
F =
1
a+y
Specify both the independent and transformation variables as a and y in the second and third
arguments, respectively.
F = laplace(f,a,y)
F =
1
t+y
syms t s
syms a positive
F = laplace(dirac(t-a),t,s)
F = e−a s
F = laplace(heaviside(t-a),t,s)
F =
e−a s
s
Show that the Laplace transform of the derivative of a function is expressed in terms of the Laplace
transform of the function itself.
syms f(t) s
Df = diff(f(t),t);
F = laplace(Df,t,s)
F = s laplace f t , t, s − f 0
Find the Laplace transform of the matrix M. Specify the independent and transformation variables for
each matrix entry by using matrices of the same size. When the arguments are nonscalars, laplace
acts on them element-wise.
syms a b c d w x y z
M = [exp(x) 1; sin(y) 1i*z];
7-951
7 Functions
vars = [w x; y z];
transVars = [a b; c d];
F = laplace(M,vars,transVars)
F =
ex 1
a b
1 i
c2 + 1 d2
If laplace is called with both scalar and nonscalar arguments, then it expands the scalars to match
the nonscalars by using scalar expansion. Nonscalar arguments must be the same size.
F = laplace(x,vars,transVars)
F =
x 1
a b2
x x
c d
Compute the Laplace transform of symbolic functions. When the first argument contains symbolic
functions, then the second argument must be a scalar.
F =
1 1
a − 1 b2
syms f(t) s
f(t) = 1/t;
F(s) = laplace(f,t,s)
F(s) =
1
laplace , t, s
t
f(t) = ilaplace(F,s,t)
f(t) =
7-952
laplace
1
t
Input Arguments
f — Input
symbolic expression | symbolic function | symbolic vector | symbolic matrix
Independent variable, specified as a symbolic variable. This variable is often called the "time
variable" or the "space variable." If you do not specify the variable then, by default, laplace uses t.
If f does not contain t, then laplace uses the function symvar to determine the independent
variable.
Transformation variable, specified as a symbolic variable, expression, vector, or matrix. This variable
is often called the "complex frequency variable." If you do not specify the variable then, by default,
laplace uses s. If s is the independent variable of f, then laplace uses z.
More About
Laplace Transform
The Laplace transform F(s) of the expression f(t) with respect to the variable t at the point s is a
unilateral transform defined by
∞
Fs = ∫f t e
–
−stdt .
Tips
• If any argument is an array, then laplace acts element-wise on all elements of the array.
• If the first argument contains a symbolic function, then the second argument must be a scalar.
• To compute the inverse Laplace transform, use ilaplace.
Algorithms
The Laplace transform is defined as a unilateral or one-sided transform. This definition assumes that
the signal f(t) is only defined for all real numbers t ≥ 0, or f(t) = 0 for t < 0. Therefore, for a
generalized signal with f(t) ≠ 0 for t < 0, the Laplace transform of f(t) gives the same result as if f(t)
is multiplied by a Heaviside step function.
7-953
7 Functions
syms t;
laplace(sin(t))
and
syms t;
laplace(sin(t)*heaviside(t))
Version History
Introduced before R2006a
See Also
fourier | ifourier | ilaplace | iztrans | ztrans
Topics
“Solve Differential Equations of RLC Circuit Using Laplace Transform” on page 3-188
7-954
laplacian
laplacian
Laplacian of symbolic field
Syntax
l = laplacian(f,v)
l = laplacian(f)
Description
l = laplacian(f,v) returns the “Laplacian” on page 7-957 of the symbolic field f with respect
to the vector v in Cartesian coordinates. If f is an array, then the function computes the Laplacian for
each element of f and returns the output l that is the same size as f.
l = laplacian(f) returns the Laplacian of the symbolic field f with respect to a default vector
constructed from the symbolic variables in f.
Examples
Create a symbolic function for the scalar field f x, y, z = sin x + y2 + z3. Compute the Laplacian of
this function with respect to the vector x, y, z .
syms x y z
f(x,y,z) = sin(x) + y^2 + z^3;
v = [x y z];
lf = laplacian(f,v)
lf(x, y, z) = 6 z − sin x + 2
Create another scalar field g x, y, z = x2 y + z. Find the Laplacian without specifying the vector to
differentiate with. Because g is a function of symbolic scalar variables, laplacian finds the
Laplacian of g with respect to the default variables as defined by symvar(g).
g(x,y,z) = x^2*y + z;
lg = laplacian(g)
lg(x, y, z) = 2 y
sin x + y2 + z3
Create a symbolic vector field F = . Find the Laplacian of this vector field with
x2 y + z2
respect to x, y, z .
syms x y z
F = [sin(x) + y^2 + z^3; x^2*y + z];
7-955
7 Functions
v = [x y z];
l = laplacian(F,v)
l =
6 z − sin x + 2
2y
Create a 3-by-1 vector as a symbolic matrix variable X. Create a scalar field that is a function of X as
a symbolic matrix function ψ X , keeping the existing definition of X.
syms X [3 1] matrix
syms psi(X) [1 1] matrix keepargs
Show that the divergence of the gradient of ψ X is equal to the Laplacian of ψ X , that is
∇ X ⋅ ∇ X ψ X = ΔX ψ X .
divOfGradPsi = divergence(gradient(psi,X),X)
divOfGradPsi(X) = ΔX ψ X
lapPsi = laplacian(psi,X)
lapPsi(X) = ΔX ψ X
Show that the gradient of the divergence of A X minus the curl of the curl of A X is equal to the
Laplacian of A X , that is ∇ X ∇ X ⋅ A X − ∇ X × ∇ X × A X = ΔX A X .
identityA(X) = ΔX A X
Input Arguments
f — Symbolic field
symbolic expression | symbolic function | symbolic matrix variable | symbolic matrix function
Symbolic field, specified as a symbolic expression, symbolic function, symbolic matrix variable, or
symbolic matrix function. The input field can be a scalar, vector, matrix, or a multidimensional array,
where the Laplacian is computed for each element in the input.
• If f is a function of symbolic scalar variables, where f is of type sym or symfun, then the vector v
must be of type sym or symfun.
• If f is a function of symbolic matrix variables, where f is of type symmatrix or symfunmatrix,
then the vector v must be of type symmatrix or symfunmatrix.
7-956
laplacian
Vector with respect to which you find the Laplacian, specified as a vector of symbolic scalar variables,
symbolic function, symbolic matrix variable, or a symbolic matrix function.
• If you do not specify v and f is a function of symbolic scalar variables, then, by default,
laplacian constructs vector v from the symbolic scalar variables in f with the order of variables
as defined by symvar(f).
• If v is a symbolic matrix variable of type symmatrix, then v must have a size of 1-by-N or N-by-1.
• If v is scalar, then laplacian(f,v) = diff(f,2,v).
Limitations
• Symbolic Math Toolbox currently does not support the dot or cross functions for symbolic matrix
variables and functions of type symmatrix and symfunmatrix. If vector calculus identities
involve dot or cross products, then the toolbox displays those identities in terms of other
supported functions instead. To see a list of all the functions that support symbolic matrix
variables and functions, use the commands methods symmatrix and methods symfunmatrix.
• If the input data type of the symbolic field f is symmatrix or symfunmatrix, then laplacian
does not evaluate the partial derivatives of f. Instead, it returns an unevaluated formula for
symbolic manipulation and formula rearrangement.
More About
Laplacian
The Laplacian or Laplace's differential operator of the scalar field f with respect to the vector
x = (x1,...,xn) is the sum of the second derivatives of f with respect to x1,...,xn.
n
∂2 f
Δx f = ∑ 2
i = 1 ∂xi
If f is a vector field or a tensor field (multidimensional array), then the Laplacian operator is applied
to each element in f.
Alternatives
The Laplacian of a scalar function or functional expression is the divergence of the gradient of that
function or expression.
Δf = ∇ ⋅ ∇ f
For a symbolic scalar field f, you can also compute the Laplacian using the divergence and
gradient functions.
syms f(x,y)
divergence(gradient(f(x,y)),[x y])
7-957
7 Functions
Version History
Introduced in R2012a
The laplacian function accepts symbolic matrix variables and functions of type symmatrix and
symfunmatrix as input arguments. For example, see “Find Vector Calculus Identities Involving
Laplacian” on page 7-956.
You can also compute the Laplacian of a multidimensional array f. The laplacian function
computes the Laplacian for each element of f and returns the output l that is the same size as f. In
previous releases, f must be scalar. For example, see “Laplacian of Vector Field” on page 7-955.
See Also
curl | diff | divergence | gradient | hessian | jacobian | potential | vectorPotential
7-958
latex
latex
LaTeX form of symbolic expression
Syntax
chr = latex(S)
Description
chr = latex(S) returns the LaTeX form of the symbolic expression S.
Examples
Find the LaTeX form of the symbolic expressions x^2 + 1/x and sin(pi*x) + phi.
syms x phi
chr = latex(x^2 + 1/x)
chr =
'\frac{1}{x}+x^2'
chr =
'\phi +\sin\left(\pi \,x\right)'
syms x
S = [sym(1)/3 x; exp(x) x^2]
S =
1
x
3
ex x2
chr = latex(S)
chr =
'\left(\begin{array}{cc} \frac{1}{3} & x\\ {\mathrm{e}}^x & x^2 \end{array}\right)'
7-959
7 Functions
Perform computation using several symbolic matrix variables, and then find their LaTeX forms.
Find the Hessian matrix of X T AX. Derived equations involving symbolic matrix variables appear in
typeset as they would be in textbooks.
f = X.'*A*X
f = XT A X
H = diff(f,X,X.')
H = AT + A
chrf =
'{\textbf{X}}^{\mathrm{T}}\,\textbf{A}\,\textbf{X}'
chrH = latex(H)
chrH =
'{\textbf{A}}^{\mathrm{T}}+\textbf{A}'
Perform computation using symbolic matrix functions, and then find their LaTeX forms.
f(X) = X T X
Df(X) = 2 X T
Generate the LaTeX forms of the symbolic matrix functions f and Df.
chrf = latex(f)
7-960
latex
chrf =
'{\textbf{X}}^{\mathrm{T}}\,\textbf{X}'
chrDf = latex(Df)
chrDf =
'2\,{\textbf{X}}^{\mathrm{T}}'
Modify generated LaTeX by setting symbolic preferences using the sympref function.
Generate the LaTeX form of the expression π with the default symbolic preference.
sympref("default");
chr = latex(sym(pi))
chr =
'\pi '
sympref("FloatingPointOutput",true);
chr = latex(sym(pi))
chr =
'3.1416'
Now change the output order of a symbolic polynomial. Create a symbolic polynomial and set the
"PolynomialDisplayStyle" preference to "ascend". Generate the LaTeX form of the polynomial
sorted in ascending order.
syms x;
poly = x^2 - 2*x + 1;
sympref("PolynomialDisplayStyle","ascend");
chr = latex(poly)
chr =
'1-2\,x+x^2'
The preferences you set using sympref persist through your current and future MATLAB® sessions.
Restore the default values by specifying the "default" option.
sympref("default");
For x and y from −2π to 2π, plot the 3-D surface y sin(x) − x cos(y). Store the axes object in a by using
gca. Use latex interpreter for the tick labels.
Create the x-axis ticks by spanning the x-axis limits at intervals of pi/2. Convert the axis limits to
precise multiples of pi/2 using round and get the symbolic tick values in S. Set the locations of the
7-961
7 Functions
x-axis ticks by using the xticks function. Create the LaTeX labels for the x-axis by using arrayfun
to apply latex to S and then concatenating $. Display the labels by using the xticklabels
function.
Repeat these steps for the y-axis. Set the x- and y-axes labels and the title using the latex
interpreter.
syms x y
f = y*sin(x)-x*cos(y);
fsurf(f,[-2*pi 2*pi])
a = gca;
a.TickLabelInterpreter = "latex";
S = sym(a.XLim(1):pi/2:a.XLim(2));
S = sym(round(S/pi*2)*pi/2);
xticks(double(S));
labels = "$" + arrayfun(@latex,S,UniformOutput=false) + "$";
xticklabels(labels);
S = sym(a.YLim(1):pi/2:a.YLim(2));
S = sym(round(S/pi*2)*pi/2);
yticks(double(S))
labels = "$" + arrayfun(@latex,S,UniformOutput=false) + "$";
yticklabels(labels);
xlabel("$x$",Interpreter="latex");
ylabel("$y$",Interpreter="latex");
zlabel("$z$",Interpreter="latex");
titletext = "$" + latex(f) + "$ for $x$ and $y$ in $[-2\pi,2\pi]$";
title(titletext,Interpreter="latex")
7-962
latex
Input Arguments
S — Input
symbolic number | symbolic variable | symbolic vector | symbolic array | symbolic function | symbolic
expression | symbolic matrix variable | symbolic matrix function
Input, specified as a symbolic number, variable, vector, array, function, expression, matrix variable, or
symbolic matrix function.
Data Types: sym | symfun | symmatrix | symfunmatrix
Version History
Introduced before R2006a
The latex function accepts an input argument of type symfunmatrix. For an example, see “LaTeX
Form of Symbolic Matrix Functions” on page 7-960.
7-963
7 Functions
The latex function accepts an input argument of type symmatrix. For an example, see “LaTeX Form
of Symbolic Matrix Variables” on page 7-959.
See Also
ccode | displayFormula | fortran | texlabel | mathml | sympref
Topics
“Copy and Paste Symbolic Output in Live Editor” on page 2-18
7-964
lcm
lcm
Least common multiple
Syntax
lcm(A)
lcm(A,B)
Description
lcm(A) finds the least common multiple of all elements of A.
Examples
Least Common Multiple of Four Integers
To find the least common multiple of three or more values, specify those values as a symbolic vector
or matrix.
Find the least common multiple of these four integers, specified as elements of a symbolic vector.
A =
[ 4420, -128, 8984, -488]
ans =
9689064320
A =
[ 4420, -128]
[ 8984, -488]
ans =
9689064320
lcm lets you find the least common multiple of symbolic rational numbers.
Find the least common multiple of these rational numbers, specified as elements of a symbolic vector.
7-965
7 Functions
ans =
924
lcm lets you find the least common multiple of symbolic complex numbers.
Find the least common multiple of these complex numbers, specified as elements of a symbolic vector.
ans =
- 60 + 30i
For vectors and matrices, lcm finds the least common multiples element-wise. Nonscalar arguments
must be the same size.
Find the least common multiples for the elements of these two matrices.
ans =
[ 57474, 13764]
[ 248832, 13888]
Find the least common multiples for the elements of matrix A and the value 99. Here, lcm expands 99
into the 2-by-2 matrix with all elements equal to 99.
lcm(A,99)
ans =
[ 10197, 6138]
[ 5346, 22176]
syms x
lcm(x^3 - 3*x^2 + 3*x - 1, x^2 - 5*x + 4)
ans =
(x - 4)*(x^3 - 3*x^2 + 3*x - 1)
Find the least common multiple of these multivariate polynomials. Because there are more than two
polynomials, specify them as elements of a symbolic vector.
syms x y
lcm([x^2*y + x^3, (x + y)^2, x^2 + x*y^2 + x*y + x + y^3 + y])
ans =
(x^3 + y*x^2)*(x^2 + x*y^2 + x*y + x + y^3 + y)
7-966
lcm
Input Arguments
A — Input value
number | symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic
vector | symbolic matrix
Input value, specified as a number, symbolic number, variable, expression, function, or a vector or
matrix of numbers, symbolic numbers, variables, expressions, or functions.
B — Input value
number | symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic
vector | symbolic matrix
Input value, specified as a number, symbolic number, variable, expression, function, or a vector or
matrix of numbers, symbolic numbers, variables, expressions, or functions.
Tips
• Calling lcm for numbers that are not symbolic objects invokes the MATLAB lcm function.
• The MATLAB lcm function does not accept rational or complex arguments. To find the least
common multiple of rational or complex numbers, convert these numbers to symbolic objects by
using sym, and then use lcm.
• Nonscalar arguments must have the same size. If one input arguments is nonscalar, then lcm
expands the scalar into a vector or matrix of the same size as the nonscalar argument, with all
elements equal to the corresponding scalar.
Version History
Introduced in R2014b
See Also
gcd
7-967
7 Functions
ldivide, .\
Symbolic array left division
Syntax
B.\A
ldivide(B,A)
Description
B.\A divides A by B.
Examples
Divide Scalar by Matrix
B = sym('b', [2 3])
B =
[ b1_1, b1_2, b1_3]
[ b2_1, b2_2, b2_3]
syms a
B.\sin(a)
ans =
[ sin(a)/b1_1, sin(a)/b1_2, sin(a)/b1_3]
[ sin(a)/b2_1, sin(a)/b2_2, sin(a)/b2_3]
H = sym(hilb(3))
d = diag(sym([1 2 3]))
H =
[ 1, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
d =
[ 1, 0, 0]
[ 0, 2, 0]
[ 0, 0, 3]
7-968
ldivide, .\
Divide d by H by using the elementwise left division operator .\. This operator divides each element
of the first matrix by the corresponding element of the second matrix. The dimensions of the matrices
must be the same.
H.\d
ans =
[ 1, 0, 0]
[ 0, 6, 0]
[ 0, 0, 15]
syms f(x)
f(x) = x^2;
f1 = f.\(x^2 + 5*x + 6)
f1(x) =
(x^2 + 5*x + 6)/x^2
Input Arguments
A — Input
symbolic scalar variable | symbolic matrix variable | symbolic function | symbolic matrix function |
symbolic expression | symbolic vector | symbolic matrix | symbolic array
Input, specified as a symbolic scalar variable, matrix variable, function, matrix function, expression,
or vector, matrix, or array of symbolic scalar variables. Inputs A and B must be the same size unless
one is a scalar. A scalar value expands into an array of the same size as the other input.
B — Input
symbolic scalar variable | symbolic matrix variable | symbolic function | symbolic matrix function |
symbolic expression | symbolic vector | symbolic matrix | symbolic array
Input, specified as a symbolic scalar variable, matrix variable, function, matrix function, expression,
or vector, matrix, or array of symbolic scalar variables. Inputs A and B must be the same size unless
one is a scalar. A scalar value expands into an array of the same size as the other input.
Version History
Introduced before R2006a
7-969
7 Functions
See Also
ctranspose | minus | mldivide | mpower | mrdivide | mtimes | plus | power | rdivide | times
| transpose
7-970
le
le
Define less than or equal to condition
Syntax
A <= B
le(A,B)
Description
A <= B defines the condition less than or equal to.
Examples
syms x
cond = x <= 3;
assume(cond)
Solve an equation for x. The solver only returns solutions that are valid under the assumption on x.
eqn = (x-1)*(x-2)*(x-3)*(x-4) == 0;
solve(eqn,x)
ans =
1
2
3
syms x
cond = abs(sin(x)) <= 1/2;
Find multiples of π/24 that satisfy the condition by using a for loop from 0 to π.
for i = 0:sym(pi/12):sym(pi)
if subs(cond, x, i)
disp(i)
end
end
0
pi/12
pi/6
7-971
7 Functions
(5*pi)/6
(11*pi)/12
pi
Input Arguments
A — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
B — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
Tips
• Calling <= or le for non-symbolic A and B invokes the MATLAB le function. This function returns
a logical array with elements set to logical 1 (true) where A is less than or equal to B;
otherwise, it returns logical 0 (false).
• If both A and B are arrays, then these arrays must have the same dimensions. A <= B returns an
array of relations A(i,j,...) <= B(i,j,...).
• If one input is scalar and the other an array, then the scalar input is expanded into an array of the
same dimensions as the other array.
• The field of complex numbers is not an ordered field. MATLAB projects complex numbers in
relations to the real axis. For example, x <= i becomes x <= 0, and x <= 3 + 2*i becomes x
<= 3.
Version History
Introduced in R2012a
See Also
eq | ge | gt | isAlways | lt | ne
Topics
“Use Assumptions on Symbolic Variables” on page 1-41
7-972
legendreP
legendreP
Legendre polynomials
Syntax
legendreP(n,x)
Description
legendreP(n,x) returns the nth degree Legendre polynomial on page 7-976 at x.
Examples
Find Legendre Polynomials for Numeric and Symbolic Inputs
legendreP(3,5.6)
ans =
430.6400
syms x
legendreP(2,x)
ans =
(3*x^2)/2 - 1/2
If you do not specify a numerical value for the degree n, the legendreP function cannot find the
explicit form of the polynomial and returns the function call.
syms n
legendreP(n,x)
ans =
legendreP(n, x)
syms x
legendreP([1 2],x)
ans =
[ x, (3*x^2)/2 - 1/2]
If multiple inputs are specified as a vector, matrix, or multidimensional array, the inputs must be the
same size. Find the Legendre polynomials where input arguments n and x are matrices.
7-973
7 Functions
n = [2 3; 1 2];
xM = [x^2 11/7; -3.2 -x];
legendreP(n,xM)
ans =
[ (3*x^4)/2 - 1/2, 2519/343]
[ -16/5, (3*x^2)/2 - 1/2]
legendreP acts element-wise on n and x to return a matrix of the same size as n and x.
Use limit to find the limit of a Legendre polynomial of degree 3 as x tends to -∞.
syms x
expr = legendreP(4,x);
limit(expr,x,-Inf)
ans =
Inf
Use diff to find the third derivative of the Legendre polynomial of degree 5.
syms n
expr = legendreP(5,x);
diff(expr,x,3)
ans =
(945*x^2)/2 - 105/2
Use taylor to find the Taylor series expansion of the Legendre polynomial of degree 2 at x = 0.
syms x
expr = legendreP(2,x);
taylor(expr,x)
ans =
(3*x^2)/2 - 1/2
syms x y
fplot(legendreP(1:4, x))
axis([-1.5 1.5 -1 1])
grid on
ylabel('P_n(x)')
title('Legendre polynomials of degrees 1 through 4')
legend('1','2','3','4','Location','best')
7-974
legendreP
syms x
roots = vpasolve(legendreP(7,x) == 0)
roots =
-0.94910791234275852452618968404785
-0.74153118559939443986386477328079
-0.40584515137739716690660641207696
0
0.40584515137739716690660641207696
0.74153118559939443986386477328079
0.94910791234275852452618968404785
Input Arguments
n — Degree of polynomial
nonnegative number | vector | matrix | multidimensional array | symbolic number | symbolic vector |
symbolic matrix | symbolic function | symbolic multidimensional array
7-975
7 Functions
x — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic vector | symbolic
matrix | symbolic function | symbolic multidimensional array
Input, specified as a number, vector, matrix, multidimensional array, or a symbolic number, vector,
matrix, function, or multidimensional array.
More About
Legendre Polynomial
2n − 1 n−1
P n, x = xP n − 1, x − P n − 2, x ,
n n
where
P 0, x = 1
P 1, x = x .
• The Legendre polynomials are orthogonal on the interval [-1,1] with respect to the weight function
w(x) = 1, where
x=1 0 if n ≠ m
∫ P(n, x)P(m, x) dx = 1
if n = m .
x= −1 n + 1/2
• The relation with Gegenbauer polynomials G(n,a,x) is
1
P n, x = G n, , x .
2
• The relation with Jacobi polynomials P(n,a,b,x) is
P n, x = P n, 0, 0, x .
Version History
Introduced in R2014b
See Also
chebyshevT | chebyshevU | gegenbauerC | hermiteH | hypergeom | jacobiP | laguerreL
7-976
lhs
lhs
Left side (LHS) of equation
Syntax
lhsEqn = lhs(eqn)
Description
lhsEqn = lhs(eqn) returns the left side of the symbolic equation eqn. The value of eqn also can
be a symbolic condition, such as x > 0. If eqn is an array, then lhs returns an array of the left sides
of the equations in eqn.
Conditions that use the > or >= operator are internally rewritten using the < or <= operator.
Therefore, lhs returns the original right side. For example, lhs(x > 0) returns 0.
Examples
eqn = 2 y = x2
lhsEqn = 2 y
cond = x + y < 1
7-977
7 Functions
lhsCond = x + y
For an array that contains equations and conditions, lhs returns an array of the left sides of those
equations or conditions. The output array is the same size as the input array.
Find the left side of the equations and conditions in the vector V.
syms x y
V = [y^2 == x^2, x ~= 0, x*y >= 1]
V = y2 = x2 x ≠ 0 1 ≤ x y
lhsV = lhs(V)
lhsV = y2 x 1
Because any condition using the >= operator is internally rewritten using the <= operator, the sides of
the last condition in V are exchanged.
Find the left side of a symbolic equation that involves symbolic matrix variables.
syms A [2 2] matrix
syms B [2 1] matrix
syms C [1 2] matrix
eqn = B*C == A*A - 2*A + eye(2)
eqn = B C = I2 − 2 A + A2
lhsEqn = lhs(eqn)
lhsEqn = B C
Input Arguments
eqn — Equation or condition
symbolic equation | symbolic condition | vector of symbolic equations or conditions | matrix of
symbolic equations or conditions | multidimensional array of symbolic equations or conditions
7-978
lhs
Version History
Introduced in R2017a
R2022b: Find left side of symbolic equation or condition involving symbolic matrix
variables and matrix functions
The lhs function accepts a symbolic equation or condition involving symbolic matrix variables and
matrix functions as an input argument. The input data type can be symmatrix or symfunmatrix.
For an example, see “Find Left Side of Equation Involving Symbolic Matrix Variables” on page 7-978.
See Also
assume | children | rhs | subs
7-979
7 Functions
limit
Limit of symbolic expression
Syntax
limit(f,var,a)
limit(f,a)
limit(f)
limit(f,var,a,"left")
limit(f,var,a,"right")
Description
limit(f,var,a) returns the bidirectional limit on page 7-982 of the symbolic expression f when
var approaches a.
Examples
syms x h
f = sin(x)/x;
limit(f,x,0)
ans = 1
f = (sin(x+h)-sin(x))/h;
limit(f,h,0)
ans = cos x
7-980
limit
syms x
f = 1/x;
limit(f,x,0,"right")
ans = ∞
limit(f,x,0,"left")
ans = − ∞
Because the limit from the left is not equal to the limit from the right, the two-sided limit does not
exist. In this case, limit returns NaN (Not a Number).
limit(f,x,0)
ans = NaN
Calculate the limit of expressions in a symbolic vector. limit acts element-wise on the vector.
syms x a
V = [(1+a/x)^x exp(-x)];
limit(V,x,Inf)
ans = ea 0
+
Calculate the right-side limit of xn as x → 0 for real n and then for positive n.
Create the symbolic variables x and n. When you create symbolic variables, they are assumed to be
complex by default. Set the assumption that n is real.
syms x n
assume(n,"real")
limit(x^n,x,0,"right")
ans =
1 if n = 0
0 if 0 < n
∞ if n < 0
Next, assume that n is positive. Find the limit using this assumption.
assume(n>0)
limit(x^n,x,0,"right")
ans = 0
7-981
7 Functions
Input Arguments
f — Input
symbolic expression | symbolic function | symbolic vector | symbolic matrix
Independent variable, specified as a symbolic variable. If you do not specify var, then symvar
determines the independent variable.
a — Limit point
number | symbolic number | symbolic variable | symbolic expression
More About
Bidirectional Limit
L = lim f x , x − a ∈ ℝ\ 0 .
x a
Left-Side Limit
L = lim f x , x − a < 0.
x a−
Right-Side Limit
L = lim f x , x − a > 0.
x a+
Version History
Introduced before R2006a
See Also
diff | poles | taylor
7-982
linsolve
linsolve
Solve symbolic linear equations in matrix form
Syntax
X = linsolve(A,B)
[X,R] = linsolve(A,B)
Description
X = linsolve(A,B) solves the matrix equation AX = B, where A is a symbolic matrix and B is a
symbolic column vector.
[X,R] = linsolve(A,B) also returns the reciprocal of the condition number of A if A is a square
matrix. Otherwise, linsolve returns the rank of A.
Examples
2 1 1 x 2
−1 1 −1 y = 3
1 2 3 z −10
A = [ 2 1 1;
-1 1 -1;
1 2 3];
B = [2; 3; -10];
X = linsolve(A,B)
X = 3×1
3
1
-5
Compute the reciprocal of the condition number of the square coefficient matrix by using two output
arguments.
syms a x y z
A = [a 0 0; 0 a 0; 0 0 1];
7-983
7 Functions
B = [x; y; z];
[X, R] = linsolve(A, B)
X =
x
a
y
a
z
R =
1
1
max a , 1 max a , 1
If the coefficient matrix is rectangular, linsolve returns the rank of the coefficient matrix as the
second output argument. Show this behavior.
syms a b x y
A = [a 0 1; 1 b 0];
B = [x; y];
[X,R] = linsolve(A,B)
X =
x
a
x−ay
−
ab
0
R = 2
Input Arguments
A — Coefficient matrix
symbolic matrix
Output Arguments
X — Solution
symbolic vector | symbolic matrix
7-984
linsolve
More About
Matrix Representation of System of Linear Equations
This system can be represented as the matrix equation A ⋅ x = b , where A is the coefficient matrix.
a11 … a1n
A= ⋮ ⋱ ⋮
am1 ⋯ amn
b1
b = ⋮
bm
Tips
• If the solution is not unique, linsolve issues a warning, chooses one solution, and returns it.
• If the system does not have a solution, linsolve issues a warning and returns X with all elements
set to Inf.
• Calling linsolve for numeric matrices that are not symbolic objects invokes the MATLAB
linsolve function. This function accepts real arguments only. If your system of equations uses
complex numbers, use sym to convert at least one matrix to a symbolic matrix, and then call
linsolve.
Version History
Introduced in R2012b
See Also
cond | dsolve | equationsToMatrix | inv | norm | odeToVectorField | rank | solve | symvar |
vpasolve
7-985
7 Functions
Topics
“Solve System of Algebraic Equations” on page 3-7
7-986
log
log
Natural logarithm of entries of symbolic matrix
Syntax
Y = log(X)
Description
Y = log(X) returns the natural logarithm of X.
Examples
Compute Natural Logarithm
syms x
M = x*hilb(2);
log(M)
ans =
[ log(x), log(x/2)]
[ log(x/2), log(x/3)]
syms x
diff(log(x^3), x)
ans =
3/x
Input Arguments
X — Input
number | vector | matrix | array | symbolic number | symbolic scalar variable | symbolic matrix
variable | symbolic array | symbolic function | symbolic matrix function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, scalar variable, matrix
variable, array, function, matrix function, or expression.
Version History
Introduced before R2006a
7-987
7 Functions
See Also
log2 | log10
7-988
log10
log10
Log base 10 of symbolic input
Syntax
log10(x)
Description
log10(x) returns the logarithm to the base 10 of x. If x is an array, log10 acts element-wise on x.
Examples
log10(20)
ans =
1.3010
Compute the log base 10 of symbolic input. The result is in terms of log.
syms x
f = x^2;
fLog10 = log10(f)
fLog10 =
log(x^2)/log(10)
Convert symbolic output to double by substituting for x with a number using subs, and then using
double.
fLog10 = subs(fLog10,x,5); % x is 5
fLog10 = double(fLog10)
fLog10 =
1.3979
Input Arguments
x — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
7-989
7 Functions
Version History
Introduced before R2006a
See Also
log | log2
7-990
log2
log2
Base-2 logarithm of symbolic input
Syntax
Y = log2(X)
[F,E] = log2(X)
Description
Y = log2(X) returns the logarithm to the base 2 of X such that 2Y = X. If X is an array, then log2
acts element-wise on X.
E
[F,E] = log2(X) returns arrays of mantissas and exponents, F and E, such that X = F ⋅ 2 . The
values returned in F are in the range 0.5 <= abs(F) < 1. Any zeros in X return F = 0 and E = 0.
Examples
y = log2(4^(1/3))
y = 0.6667
Compute the base-2 logarithm of a symbolic input. The result is in terms of the natural logarithm log
function.
syms x
ySym = log2(x^(1/3))
ySym =
log x1/3
log 2
Substitute the symbolic variable x with a number by using subs. Simplify the result by using
simplify.
yVal = subs(ySym,x,4)
yVal =
1/3
log 4
log 2
simplify(yVal)
ans =
2
3
7-991
7 Functions
Find the mantissa and exponent of a base-2 logarithm of an input X . The mantissa F and the exponent
E
E satisfy the relation X = F ⋅ 2 .
Create a symbolic variable a and assume that it is real. Create a symbolic vector X that contains
symbolic numbers and expressions. Find the exponent and mantissa for each element of X.
syms a real;
X = [1 0.5*2^a 5/7]
X =
a
2 5
1
2 7
[F,E] = log2(X)
F =
1 a
a
2
2
log
2
1 2 log 2 +1 5
2 2 7
E =
a
2
log 2
1 +1 0
log 2
The values returned in F have magnitudes in the range 0.5 <= abs(F) < 1.
F = simplify(F)
F =
1 a− a −1 5
2
2 7
E = simplify(E)
E = 1 a 0
Input Arguments
X — Input array
symbolic number | symbolic array | symbolic variable | symbolic function | symbolic expression
• When computing the base-2 logarithms of complex elements in X, log2 ignores their imaginary
parts.
7-992
log2
• For the syntax [F,E] = log2(X), any zeros in X produce F = 0 and E = 0. Input values of Inf,
-Inf, or NaN are returned unchanged in F with a corresponding exponent of E = 0.
Output Arguments
Y — Base-2 logarithm values
symbolic number | symbolic vector | symbolic matrix | symbolic array
Base-2 logarithm values, returned as a symbolic number, vector, matrix, or array of the same size as
X.
F — Mantissa values
symbolic number | symbolic vector | symbolic matrix | symbolic array
Mantissa values, returned as a symbolic scalar, vector, matrix, or array of the same size as X. The
values in F and E satisfy X = F.*2.^E.
E — Exponent values
symbolic number | symbolic vector | symbolic matrix | symbolic array
Exponent values, returned as a symbolic scalar, vector, matrix, or array of the same size as X. The
values in F and E satisfy X = F.*2.^E.
Tips
• For floating-point input, the syntax [F,E] = log2(X) corresponds to the ANSI® C function
frexp() and the IEEE® standard function logb(). Any zeros in X produce F = 0 and E = 0.
Version History
Introduced before R2006a
See Also
log | log10 | power
7-993
7 Functions
logical
Determine if symbolic equation, inequality, or condition is true
Syntax
tf = logical(cond)
Description
tf = logical(cond) checks if the conditions in cond are true and returns an array of logical
values. To test conditions that require assumptions or mathematical transformations, use isAlways
instead.
Examples
tf = logical
1
To check if several conditions are true at the same time, combine them by using logical operators. For
example, check if 1 is less than 2 and if exp(log(x)) == x. Note that when you define a condition
that uses other functions, such as exp and log, these functions are evaluated when defining the
condition.
syms x
cond1 = 1 < 2 & exp(log(x)) == x
cond1 = x = x
tf = logical(cond1)
tf = logical
1
For multiple conditions, you can represent the conditions as a symbolic array.
cond2 = [1 < 2; exp(log(x)) == x]
cond2 =
1
x=x
tf = logical(cond2)
7-994
logical
1
1
Test an inequality that has a symbolic type on the left side and a numeric type on the right side. The
expressions on both sides have compatible data types, and the inequality is true.
tf = logical
1
logical also checks the validity of equations and inequalities involving other functions, such as int.
For example, the left side of this equation that contains an integral evaluates to sym(1). Both sides of
the equation are equal, and logical returns 1 (true).
syms x
tf = logical(int(x,x,0,2) - 1 == 1)
tf = logical
1
logical does not simplify or apply mathematical transformations when checking if a condition is
2
true. For example, check the equality of x + 1 and x2 + 2x + 1 using logical.
syms x
tf = logical((x+1)^2 == x^2+2*x+1)
tf = logical
0
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
Using logical on symtrue converts the symbolic logical constant to logical 1 (true).
tf = logical(cond)
tf = logical
1
7-995
7 Functions
To check an equation that requires simplifications, you can use isAlways instead.
tf = isAlways((x+1)^2 == x^2+2*x+1)
tf = logical
1
Check if an equation that involves a function, such as sqrt, is true. Without an additional assumption
that x is nonnegative, sqrt(x^2) does not evaluate to x.
syms x
tf = logical(x == sqrt(x^2))
tf = logical
0
Use assume to set an assumption that x is nonnegative. Now the expression sqrt(x^2) evaluates to
x, and logical returns 1 because x == x is true.
assume(x >= 0)
tf = logical(x == sqrt(x^2))
tf = logical
1
Note that the logical function itself ignores assumptions on symbolic variables.
syms x
assume(x == 5)
tf = logical(x == 5)
tf = logical
0
To compare expressions taking into account assumptions on their variables, use isAlways.
tf = isAlways(x == 5)
tf = logical
1
syms x
The logical function does not simplify or apply mathematical transformations when checking if a
condition is true. For example, logical does not recognize the mathematical equivalence of this
equation.
7-996
logical
syms x
tf = logical(sin(x)/cos(x) == tan(x))
tf = logical
0
tf = logical(sin(x)/cos(x) ~= tan(x))
tf = logical
1
To test the validity of equations and inequalities that require simplification or mathematical
transformations, use isAlways instead. isAlways issues a warning when returning false for
undecidable inputs.
tf = isAlways(sin(x)/cos(x) == tan(x))
tf = logical
1
tf = isAlways(sin(x)/cos(x) ~= tan(x))
tf = logical
0
Input Arguments
cond — Input
symbolic equation | symbolic inequality | symbolic array of equations or inequalities
Tips
• For symbolic equations, logical returns logical 1 (true) only if the left and right sides are equal.
Otherwise, it returns logical 0 (false).
• For symbolic inequalities constructed with ~=, logical returns logical 0 (false) only if the left
and right sides are equal. Otherwise, it returns logical 1 (true).
• For all other inequalities (constructed with <, <=, >, or >=), logical returns logical 1 if it can
prove that the inequality is true and logical 0 if it can prove that the inequality is false. If logical
cannot determine whether an inequality is true or false, it returns an error.
• logical does not simplify or mathematically transform a conditional statement. To compare a
conditional statement applying mathematical transformations and simplifications, use isAlways.
7-997
7 Functions
• If you use logical to check a conditional statement that involves a symbolic type, then the data
types of the compared expressions must be compatible. For example, logical(1==sym(1))
returns 1 (true). If the expressions do not have compatible data types, then logical returns an
error. For example, syms f(x) g(y); tf = logical(f~=g) returns an error.
• logical ignores assumptions on symbolic variables.
Version History
Introduced in R2012a
See Also
assume | assumeAlso | assumptions | in | isAlways | isequal | isequaln | isfinite | isinf |
isnan | sym | syms
Topics
“Use Assumptions on Symbolic Variables” on page 1-41
“Clear Assumptions and Reset the Symbolic Engine” on page 3-314
“Check Symbolic Equations, Inequalities, and Conditional Statements” on page 2-23
7-998
logint
logint
Logarithmic integral function
Syntax
A = logint(x)
Description
A = logint(x) evaluates the logarithmic integral function on page 7-1001 (integral logarithm).
Examples
Integral Logarithm for Numeric and Symbolic Arguments
logint returns floating-point or exact symbolic results depending on the arguments you use.
Compute integral logarithms for these numbers. Because these numbers are not symbolic objects,
logint returns floating-point results.
A =
0.0737 + 3.4227i 0.0000 + 0.0000i -0.1187 + 0.0000i -0.3787 + 0.0000i...
-Inf + 0.0000i 1.0452 + 0.0000i 6.1656 + 0.0000i
Compute integral logarithms for the numbers converted to symbolic objects. For many symbolic
(exact) numbers, logint returns unresolved symbolic calls.
symA =
[ logint(-1), 0, logint(1/4), logint(1/2), -Inf, logint(2), logint(10)]
A = vpa(symA)
A =
[ 0.07366791204642548599010096523015...
+ 3.4227333787773627895923750617977i,...
0,...
-0.11866205644712310530509570647204,...
-0.37867104306108797672720718463656,...
-Inf,...
1.0451637801174927848445888891946,...
6.1655995047872979375229817526695]
7-999
7 Functions
syms x
fplot(logint(x),[0 10])
grid on
Many functions, such as diff and limit, can handle expressions containing logint.
dA =
1/log(x)
dA =
-1/(x*log(x)^2)
Find the right and left limits of this expression involving logint:
A_r = limit(exp(1/x)/logint(x + 1), x, 0, 'right')
A_r =
Inf
7-1000
logint
A_l =
0
Input Arguments
x — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
More About
Logarithmic Integral Function
The logarithmic integral function, also called the integral logarithm, is defined as follows:
x
logint x = li x = ∫ ln1t
0
dt
Tips
• logint(sym(0)) returns 1.
• logint(sym(1)) returns -Inf.
• logint(z) = ei(log(z)) for all complex z.
Version History
Introduced in R2014a
References
[1] Gautschi, W., and W. F. Cahill. “Exponential Integral and Related Functions.” Handbook of
Mathematical Functions with Formulas, Graphs, and Mathematical Tables. (M. Abramowitz
and I. A. Stegun, eds.). New York: Dover, 1972.
See Also
coshint | cosint | ei | expint | int | log | sinhint | sinint | ssinint
7-1001
7 Functions
logm
Matrix logarithm
Syntax
R = logm(A)
Description
R = logm(A) computes the matrix logarithm of the square matrix A.
Examples
Matrix Logarithm
syms x
A = [x 1; 0 -x];
logm(A)
ans =
[ log(x), log(x)/(2*x) - log(-x)/(2*x)]
[ 0, log(-x)]
Input Arguments
A — Input matrix
square matrix
Output Arguments
R — Resulting matrix
symbolic matrix
Version History
Introduced in R2014b
See Also
eig | expm | funm | jordan | sqrtm
7-1002
lt
lt
Define less than relation
Syntax
A < B
lt(A,B)
Description
A < B creates a less than relation.
Examples
Set and Use Assumption Using Less
Use assume and the relational operator < to set the assumption that x is less than 3:
syms x
assume(x < 3)
Solve this equation. The solver takes into account the assumption on variable x, and therefore returns
these two solutions.
ans =
1
2
syms x
cond = abs(sin(x)) + abs(cos(x)) < 6/5;
Use the for loop with step π/24 to find angles from 0 to π that satisfy that condition:
for i = 0:sym(pi/24):sym(pi)
if subs(cond, x, i)
disp(i)
end
end
0
pi/24
(11*pi)/24
pi/2
(13*pi)/24
7-1003
7 Functions
(23*pi)/24
pi
Input Arguments
A — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
B — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
Tips
• Calling < or lt for non-symbolic A and B invokes the MATLAB lt function. This function returns a
logical array with elements set to logical 1 (true) where A is less than B; otherwise, it returns
logical 0 (false).
• If both A and B are arrays, then these arrays must have the same dimensions. A < B returns an
array of relations A(i,j,...) < B(i,j,...)
• If one input is scalar and the other an array, then the scalar input is expanded into an array of the
same dimensions as the other array. In other words, if A is a variable (for example, x), and B is an
m-by-n matrix, then A is expanded into m-by-n matrix of elements, each set to x.
• The field of complex numbers is not an ordered field. MATLAB projects complex numbers in
relations to a real axis. For example, x < i becomes x < 0, and x < 3 + 2*i becomes x < 3.
Version History
Introduced in R2012a
See Also
eq | ge | gt | isAlways | le | ne
Topics
“Use Assumptions on Symbolic Variables” on page 1-41
7-1004
lu
lu
LU factorization
Syntax
[L,U] = lu(A)
[L,U,P] = lu(A)
[L,U,p] = lu(A,'vector')
[L,U,p,q] = lu(A,'vector')
[L,U,P,Q,R] = lu(A)
[L,U,p,q,R] = lu(A,'vector')
lu(A)
Description
[L,U] = lu(A) returns an upper triangular matrix U and a matrix L, such that A = L*U. Here, L is
a product of the inverse of the permutation matrix and a lower triangular matrix.
[L,U,P] = lu(A) returns an upper triangular matrix U, a lower triangular matrix L, and a
permutation matrix P, such that P*A = L*U. The syntax lu(A,'matrix') is identical.
[L,U,p] = lu(A,'vector') returns the permutation information as a vector p, such that A(p,:)
= L*U.
[L,U,p,q] = lu(A,'vector') returns the permutation information as two row vectors p and q,
such that A(p,q) = L*U.
[L,U,p,q,R] = lu(A,'vector') returns the permutation information in two row vectors p and q,
such that R(:,p)\A(:,q) = L*U.
lu(A) returns the matrix that contains the strictly lower triangular matrix L (the matrix without its
unit diagonal) and the upper triangular matrix U as submatrices. Thus, lu(A) returns the matrix U +
L - eye(size(A)), where L and U are defined as [L,U,P] = lu(A). The matrix A must be
square.
Examples
Compute the LU factorization of this matrix. Because the numbers are not symbolic objects, you get
floating-point results.
7-1005
7 Functions
L =
1.0000 0 0
0.2500 1.0000 0
0 0.5714 1.0000
U =
2.0000 -3.0000 -1.0000
0 1.7500 -0.7500
0 0 -0.5714
Now convert this matrix to a symbolic object, and compute the LU factorization.
M = sym(M);
[L, U] = lu(M)
L =
[ 1, 0, 0]
[ 1/4, 1, 0]
[ 0, 4/7, 1]
U =
[ 2, -3, -1]
[ 0, 7/4, -3/4]
[ 0, 0, -4/7]
Return the lower and upper triangular matrices and the permutation matrix by providing three
output arguments.
syms a
[L, U, P] = lu(sym([0 0 a; a 2 3; 0 a 2]))
L =
[ 1, 0, 0]
[ 0, 1, 0]
[ 0, 0, 1]
U =
[ a, 2, 3]
[ 0, a, 2]
[ 0, 0, a]
P =
0 1 0
0 0 1
1 0 0
L =
[ 1, 0, 0]
7-1006
lu
[ 0, 1, 0]
[ 0, 0, 1]
U =
[ a, 2, 3]
[ 0, a, 2]
[ 0, 0, a]
p =
2 3 1
isAlways(A(p,:) == L*U)
ans =
3×3 logical array
1 1 1
1 1 1
1 1 1
P = zeros(3, 3);
for i = 1:3
P(i, p(i)) = 1;
end
P
P =
0 1 0
0 0 1
1 0 0
syms a
A = [a, 2, 3*a; 2*a, 3, 4*a; 4*a, 5, 6*a];
[L, U, p, q] = lu(A, 'vector')
L =
[ 1, 0, 0]
[ 2, 1, 0]
[ 4, 3, 1]
U =
[ a, 2, 3*a]
[ 0, -1, -2*a]
[ 0, 0, 0]
p =
1 2 3
q =
1 2 3
isAlways(A(p, q) == L*U)
7-1007
7 Functions
ans =
3×3 logical array
1 1 1
1 1 1
1 1 1
Return the lower and upper triangular matrices, permutation matrices, and scaling matrix.
syms a
A = [0, a; 1/a, 0; 0, 1/5; 0,-1];
[L, U, P, Q, R] = lu(A)
L =
[ 1, 0, 0, 0]
[ 0, 1, 0, 0]
[ 0, 1/(5*a), 1, 0]
[ 0, -1/a, 0, 1]
U =
[ 1/a, 0]
[ 0, a]
[ 0, 0]
[ 0, 0]
P =
0 1 0 0
1 0 0 0
0 0 1 0
0 0 0 1
Q =
1 0
0 1
R =
[ 1, 0, 0, 0]
[ 0, 1, 0, 0]
[ 0, 0, 1, 0]
[ 0, 0, 0, 1]
isAlways(P*(R\A)*Q == L*U)
ans =
4×2 logical array
1 1
1 1
1 1
1 1
Return the permutation information as vectors p and q by using the 'vector' flag. Also, compute
the scaling matrix R.
7-1008
lu
syms a
A = [0, a; 1/a, 0; 0, 1/5; 0,-1];
[L, U, p, q, R] = lu(A,'vector')
L =
[ 1, 0, 0, 0]
[ 0, 1, 0, 0]
[ 0, 1/(5*a), 1, 0]
[ 0, -1/a, 0, 1]
U =
[ 1/a, 0]
[ 0, a]
[ 0, 0]
[ 0, 0]
p =
2 1 3 4
q =
1 2
R =
[ 1, 0, 0, 0]
[ 0, 1, 0, 0]
[ 0, 0, 1, 0]
[ 0, 0, 0, 1]
isAlways(R(:,p)\A(:,q) == L*U)
ans =
4×2 logical array
1 1
1 1
1 1
1 1
syms a
A = [0 0 a; a 2 3; 0 a 2];
lu(A)
ans =
[ a, 2, 3]
[ 0, a, 2]
[ 0, 0, a]
Verify that the resulting matrix is equal to U + L - eye(size(A)), where L and U are defined as
[L,U,P] = lu(A).
[L,U,P] = lu(A);
U + L - eye(size(A))
ans =
[ a, 2, 3]
7-1009
7 Functions
[ 0, a, 2]
[ 0, 0, a]
Input Arguments
A — Input
numeric matrix | symbolic matrix
More About
LU Factorization of a Matrix
Permutation Vector
The permutation vector p contains numbers corresponding to row exchanges in the matrix A. For an
m-by-m matrix, p represents the following permutation matrix with indices i and j ranging from 1 to
m.
1 if j = pi
Pi j = δpi, j =
0 if j ≠ pi
Tips
• Calling lu for numeric arguments that are not symbolic objects invokes the MATLAB lu function.
• The thresh option supported by the MATLAB lu function does not affect symbolic inputs.
• If you use 'matrix' instead of 'vector', then lu returns permutation matrices, as it does by
default.
• L and U are nonsingular if and only if A is nonsingular. lu also can compute the LU factorization of
a singular matrix A. In this case, L or U is a singular matrix.
• Most algorithms for computing LU factorization are variants of Gaussian elimination.
Version History
Introduced in R2013a
See Also
chol | eig | isAlways | lu | qr | svd | vpa
7-1010
mapSymType
mapSymType
Apply function to symbolic subobjects of specific type
Syntax
X = mapSymType(symObj,type,func)
X = mapSymType(symObj,funType,vars,func)
Description
X = mapSymType(symObj,type,func) applies the function func to the symbolic subobjects of
type type in the symbolic object symObj. The input type must be a case-sensitive string scalar or
character vector, and it can include a logical expression.
If symObj contains several subexpressions of type type, then mapSymType applies the function func
to the largest subexpression.
You can set the function type funType to 'symfunOf' or 'symfunDependingOn'. For example,
syms f(x); mapSymType(f,'symfunOf',x,@(u)cos(u)) returns cos(f(x)).
Examples
expr = 2 + π i
Apply the function sq to the symbolic subobject of type 'integer' in the expression expr.
X = mapSymType(expr,'integer',sq)
X = 4+π i
You can also apply an existing MATLAB® function, such as exp. Apply the exp function to the
symbolic subobject of type 'complex' in the expression expr.
X = mapSymType(expr,'complex',@exp)
7-1011
7 Functions
X = π ei + 2
syms x t
eq = 0.5*x + sin(x) == t/4
eq =
x t
+ sin x =
2 4
syms f(u)
f(u) = 2*u;
Apply the symbolic function f to the symbolic subobjects of type 'variable' in the equation eq.
X = mapSymType(eq,'variable',f)
X =
t
x + sin 2 x =
2
You can also apply the same symbolic function that is created using symfun.
X = mapSymType(eq,'variable',symfun(2*u,u))
X =
t
x + sin 2 x =
2
Now create an unassigned symbolic function. Apply the unassigned function to the symbolic
subobjects of type 'sin' in the equation eq.
syms g(u)
X = mapSymType(eq,'sin',g)
X =
x t
+ g sin x =
2 4
7-1012
mapSymType
syms f(x) y
expr = sin(x) + f(x) - 2*y
expr = f x − 2 y + sin x
Apply the log function to the symbolic subobject of type 'expression' in the expression expr.
X = mapSymType(expr,'expression',@log)
X = log f x − 2 y + sin x
When there are several subexpressions of type 'expression', mapSymType applies the log
function to the largest subexpression.
expr = 2 g t + f x + sin x h x, t
Construct a function handle that converts an input to a symbolic variable with name 'z'.
Apply the conversion function func to the unassigned symbolic functions in the expression expr.
Convert the functions that depend on the exact sequence of variables [x t] using 'symfunOf'.
X = mapSymType(expr,'symfunOf',[x t],func)
X = 2 g t + f x + z sin x
Convert the functions that have a dependency on the variable t using 'symfunDependingOn'.
X = mapSymType(expr,'symfunDependingOn',x,func)
X = z + 2 g t + z sin x
eq =
7-1013
7 Functions
∂
f 1 t + f 2 t = 0 f 1 t = 2 g1 t g1 t = g t
∂t 2
Apply the symFunType function to replace an unassigned symbolic function with a variable of the
same name.
Find all functions that have a dependency on the variable t using 'symfunOf' and convert them
using symFunType.
X = mapSymType(eq,'symfunOf',t,@symFunType)
X = f 1 + f 2 = 0 f 1 = 2 g1 g1 = 0
expr =
3 sin 3 t 18 3 sinh 3 t
19 e−t cos 3 t + 19
19 e2 t cosh 3 t − 19
−
39 39
The result is in terms of the exp, sin, cos, sinh, and cosh functions.
Rewrite sinh and cosh in the result as exp. Use mapSymType to apply the rewrite function to
subexpressions that contain sinh or cosh.
expr = mapSymType(expr,"sinh|cosh",@(subexpr) rewrite(subexpr,"exp"))
expr =
e 3t e− 3 t
18 3 −
e 3t e− 3 t 2 2
19 e2 t 2
+ 2
− 19
3 sin 3 t
19 e−t cos 3t + 19
−
39 39
Input Arguments
symObj — Symbolic objects
symbolic expressions | symbolic functions | symbolic variables | symbolic numbers | symbolic units
Symbolic objects, specified as symbolic expressions, symbolic functions, symbolic variables, symbolic
numbers, or symbolic units.
Symbolic types, specified as a case-sensitive scalar string or character vector. The input type can
contain a logical expression. The value options follow.
7-1014
mapSymType
7-1015
7 Functions
Input function, specified as a function handle or symbolic function. For more information about
function handles and symbolic function, see “Create Function Handle” and symfun, respectively.
If symObj contains several subexpressions of type type, then mapSymType applies the function func
to the largest subexpression (topmost matching node in a tree data structure).
• 'symfunOf' applies func to the unassigned symbolic functions that depend on the exact
sequence of variables specified by the array vars. For example, syms f(x,y);
mapSymType(f,'symfunOf',[x y],@(g)g^2) returns f(x,y)^2.
• 'symfunDependingOn' applies func to the unassigned symbolic functions that have a
dependency on the variables specified by the array vars. For example, syms f(x,y);
mapSymType(f,'symfunDependingOn',x,@(g)g/2) returns f(x,y)/2.
Version History
Introduced in R2019a
See Also
symFunType | isSymType | symType | sym | syms | findSymType | hasSymType | str2sym |
symfun
7-1016
massMatrixForm
massMatrixForm
Extract mass matrix and right side of semilinear system of differential algebraic equations
Syntax
[M,F] = massMatrixForm(eqs,vars)
Description
[M,F] = massMatrixForm(eqs,vars) returns the mass matrix M and the right side of equations F
of a semilinear system of first-order differential algebraic equations (DAEs). Algebraic equations in
eqs that do not contain any derivatives of the variables in vars correspond to empty rows of the
mass matrix M.
The mass matrix M and the right side of equations F refer to this form.
M t, x t ẋ t = F t, x t .
Examples
Create the following system of differential algebraic equations. Here, the functions x1(t) and x2(t)
represent state variables of the system. The system also contains symbolic parameters r and m, and
the function f(t,x1,x2). Specify the equations and variables as two symbolic vectors: equations as
a vector of symbolic equations, and variables as a vector of symbolic function calls.
M =
m x2 t m t
0 0
F =
f t, x1 t , x2 t
2 2
r 2 − x1 t − x2 t
Solve this system using the numerical solver ode15s. Before you use ode15s, assign the following
values to symbolic parameters of the system: m = 100, r = 1, f(t,x1,x2) = t + x1*x2. Also,
replace the state variables x1(t), x2(t) by variables Y1, Y2 acceptable by matlabFunction.
7-1017
7 Functions
syms Y1 Y2
M = subs(M, [vars, m, r, f], [Y1, Y2, 100, 1, @(t,x1,x2) t + x1*x2]);
F = subs(F, [vars, m, r, f], [Y1, Y2, 100, 1, @(t,x1,x2) t + x1*x2]);
Create the following function handles MM and FF. You can use these function handles as input
arguments for odeset and ode15s. These functions require state variables to be specified as column
vectors.
Input Arguments
eqs — System of semilinear first-order DAEs
vector of symbolic equations | vector of symbolic expressions
7-1018
massMatrixForm
State variables, specified as a vector of symbolic functions or function calls, such as x(t).
Example: [x(t),y(t)] or [x(t);y(t)]
Output Arguments
M — Mass matrix
symbolic matrix
Mass matrix of the system, returned as a symbolic matrix. The number of rows is the number of
equations in eqs, and the number of columns is the number of variables in vars.
Right sides of equations, returned as a column vector of symbolic expressions. The number of
elements in this vector is equal to the number of equations in eqs.
Version History
Introduced in R2014b
See Also
findDecoupledBlocks | daeFunction | decic | incidenceMatrix | isLowIndexDAE |
matlabFunction | odeFunction | ode15s | odeset | reduceDAEIndex | reduceDAEToODE |
reduceDifferentialOrder | reduceRedundancies
Topics
“Solve DAEs Using Mass Matrix Solvers” on page 3-77
7-1019
7 Functions
mathml
Generate MathML from symbolic expression
Syntax
chr = mathml(f)
chr = mathml(f,Name,Value)
Description
chr = mathml(f) returns the generated MathML from the symbolic expression f.
chr = mathml(f,Name,Value) uses additional options specified by one or more name-value pair
arguments. For example, generate MathML for inline display by specifying DisplayInline as true.
Examples
chr =
'<math xmlns='http://www.w3.org/1998/Math/MathML' display='block'>
<msup>
<mo>ⅇ</mo>
<mrow>
<mo>-</mo>
<msup>
<mi>x</mi>
<mn>2</mn>
</msup>
</mrow>
</msup>
</math>
'
chr =
'<math xmlns='http://www.w3.org/1998/Math/MathML'>
7-1020
mathml
<msup>
<mo>ⅇ</mo>
<mrow>
<mo>-</mo>
<msup>
<mi>x</mi>
<mn>2</mn>
</msup>
</mrow>
</msup>
</math>
'
Use MathML tooltips for units and some special functions to provide more information. Generate
tooltips by specifying Tooltips as true.
syms nu x
f = besselj(nu,x);
chr = mathml(f,'Tooltips',true)
chr =
'<math xmlns='http://www.w3.org/1998/Math/MathML' display='block'>
<mrow>
<msub>
<maction actiontype='tooltip'>
<mo>J</mo>
<mtext>besselj</mtext>
</maction>
<mi>ν</mi>
</msub>
<mrow>
<mo form='prefix'>(</mo>
<mi>x</mi>
<mo form='postfix'>)</mo>
</mrow>
</mrow>
</math>
'
When you use MathML in a web page, then hovering your mouse on J displays a tooltip containing
besselj.
Modify generated MathML by setting symbolic preferences using the sympref function.
Generate the MathML form of the expression π with the default symbolic preference.
7-1021
7 Functions
sympref('default');
chr = mathml(sym(pi))
chr =
'<math xmlns='http://www.w3.org/1998/Math/MathML' display='block'>
<mi>π</mi>
</math>
'
chr =
'<math xmlns='http://www.w3.org/1998/Math/MathML' display='block'>
<mn>3.1416</mn>
</math>
'
Now change the output order of a symbolic polynomial. Create a symbolic polynomial and set
'PolynomialDisplayStyle' preference to 'ascend'. Generate MathML form of the polynomial
sorted in ascending order.
syms x;
poly = x^2 - 2*x + 1;
sympref('PolynomialDisplayStyle','ascend');
chr = mathml(poly)
chr =
'<math xmlns='http://www.w3.org/1998/Math/MathML' display='block'>
<mrow>
<mn>1</mn>
<mo>-</mo>
<mrow>
<mn>2</mn>
<mo form='infix'>⁢</mo>
<mi>x</mi>
</mrow>
<mo>+</mo>
<msup>
<mi>x</mi>
<mn>2</mn>
</msup>
</mrow>
</math>
'
The preferences you set using sympref persist through your current and future MATLAB sessions.
Restore the default values by specifying the 'default' option.
sympref('default');
Input Arguments
f — Input
symbolic number | symbolic variable | symbolic array | symbolic function | symbolic expression
7-1022
mathml
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: mathml(f,'Tooltips',true)
Inline MathML display, specified as the comma-separated pair consisting of 'DisplayInline' and
either true or false (default).
Tooltips — tooltips
false (default) | true
Tooltips in MathML output, specified as the comma-separated pair consisting of 'Tooltips' and
either true or false (default). mathml adds tooltips for units and some special functions.
Version History
Introduced in R2018b
See Also
latex | texlabel | ccode | fortran | sympref
Topics
“Copy and Paste Symbolic Output in Live Editor” on page 2-18
7-1023
7 Functions
matlabFunction
Convert symbolic expression to function handle or file
Syntax
ht = matlabFunction(f)
ht = matlabFunction(f1,...,fN)
ht = matlabFunction( ___ ,Name,Value)
Description
ht = matlabFunction(f) converts the symbolic expression or function f to a MATLAB function
with handle ht. If there is an equivalent MATLAB function operating on the double data type for the
symbolic expression or function, then the converted function can be used without Symbolic Math
Toolbox.
For example, you can specify the File name-value argument to write the generated MATLAB
function to a file. You can also specify the Vars name-value argument to generate a MATLAB function
with input arguments that are a combination of scalar and vector variables.
Examples
Convert the symbolic expression r to a MATLAB function with the handle ht. The converted function
can be used without Symbolic Math Toolbox.
syms x y
r = sqrt(x^2 + y^2);
ht = matlabFunction(r)
ht =
function_handle with value:
@(x,y)sqrt(x.^2+y.^2)
ht =
function_handle with value:
@(x,y)deal(sqrt(x.^2+y.^2),x.^2+y.^2)
7-1024
matlabFunction
Create a symbolic function and convert it to a MATLAB function with the handle ht.
syms x y
f(x,y) = x^3 + y^3;
ht = matlabFunction(f)
ht =
function_handle with value:
@(x,y)x.^3+y.^3
Write the generated MATLAB function to a file by specifying the File name-value argument. Existing
files are overwritten. When writing to a file, matlabFunction optimizes the code using intermediate
variables named t0, t1, and so on. Include comments in the file by using the Comments name-value
argument.
function f = myfile(x)
%MYFILE
% F = MYFILE(X)
% This function was generated by the Symbolic Math Toolbox version 8.4.
% 01-Sep-2019 00:00:00
t2 = x.^2;
f = t2+log(t2);
function f = myfile(x)
...
%Version: 1.1
t2 = x.^2;
...
When converting a symbolic expression to a MATLAB function, you can specify the order of the input
arguments of the resulting function. You can also specify that some input arguments are vectors
instead of scalar variables.
7-1025
7 Functions
Convert r to a MATLAB function and write this function to the file myfile. By default,
matlabFunction uses alphabetical order for the input arguments when converting symbolic
expressions that contain only lowercase letters for the variable names. The generated input
arguments are scalar variables x, y, and z.
matlabFunction(r,"File","myfile");
function r = myfile(x,y,z)
%MYFILE
% R = MYFILE(X,Y,Z)
r = x+y./2.0+z./3.0;
Specify the Vars name-value argument as the vector [y z x] to modify the order of the input
arguments for the generated MATLAB function. The generated input arguments are scalar variables
y, z, and x.
matlabFunction(r,"File","myfile","Vars",[y z x]);
function r = myfile(y,z,x)
%MYFILE
% R = MYFILE(Y,Z,X)
r = x+y./2.0+z./3.0;
Now, convert a symbolic expression v to a MATLAB function whose input arguments are a scalar and
a vector. Specify the Vars name-value argument as the cell array {t,[x y z]}. The generated input
arguments are a scalar variable t and a 1-by-3 vector variable in2.
syms x y z t
v = (x + y/2 + z/3)*exp(-t);
matlabFunction(v,"File","myfile","Vars",{t,[x y z]});
function v = myfile(t,in2)
%MYFILE
% R = MYFILE(T,IN2)
x = in2(:,1);
y = in2(:,2);
z = in2(:,3);
v = exp(-t).*(x+y./2.0+z./3.0);
To generate a MATLAB function with input arguments that are vector variables, specify the Vars
name-value argument as a cell array.
Create a symbolic expression that finds the dot product of two 1-by-3 vectors.
syms x y [1 3] real
f = dot(x,y);
Convert the expression f to a MATLAB function. Specify Vars as a cell array {x,y}. The generated
input arguments are two 1-by-3 vector variables, in1 and in2, that correspond to x and y,
respectively.
matlabFunction(f,"File","myfile","Vars",{x,y});
function f = myfile(in1,in2)
%MYFILE
7-1026
matlabFunction
% F = MYFILE(IN1,IN2)
x1 = in1(:,1);
x2 = in1(:,2);
x3 = in1(:,3);
y1 = in2(:,1);
y2 = in2(:,2);
y3 = in2(:,3);
f = x1.*y1+x2.*y2+x3.*y3;
syms g(x,y,z,t)
g(x,y,z,t) = x^2 + y^2 + z^2 - t^2;
Convert the function g to a MATLAB function. To specify the generated input arguments as a 4-by-1
column vector from the input variables of g, specify Vars as a cell array that contains the 4-by-1
vector. You can use argnames to obtain the input variables x, y, z, and t from g.
matlabFunction(g,"File","myfunction","Vars",{argnames(g).'});
function g = myfunction(in1)
%MYFUNCTION
% G = MYFUNCTION(IN1)
x = in1(1,:);
y = in1(2,:);
z = in1(3,:);
t = in1(4,:);
g = -t.^2+x.^2+y.^2+z.^2;
When you convert a symbolic expression to a MATLAB function and write the resulting function to a
file, matlabFunction optimizes the code by default. This approach can help simplify and speed up
further computations that use the file. However, generating the optimized code from some symbolic
expressions and functions can be time-consuming. Use the Optimize name-value argument to
disable code optimization.
syms x
r = x^2*(x^2 + 1);
Convert r to a MATLAB function and write the function to the file myfile. By default,
matlabFunction creates a file containing the optimized code.
f = matlabFunction(r,"File","myfile");
function r = myfile(x)
%MYFILE
% R = MYFILE(X)
t2 = x.^2;
r = t2.*(t2+1.0);
f = matlabFunction(r,"File","myfile","Optimize",false);
7-1027
7 Functions
function r = myfile(x)
%MYFILE
% R = MYFILE(X)
r = x.^2.*(x.^2+1.0);
When you convert a symbolic matrix to a MATLAB function, matlabFunction represents the
symbolic matrix with a dense matrix by default. If most of the elements of the input symbolic matrix
are zeros, the more efficient approach is to represent the symbolic matrix with a sparse matrix.
syms x
A = diag(x*ones(1,3))
A =
[ x, 0, 0]
[ 0, x, 0]
[ 0, 0, x]
Convert A to a MATLAB function representing a numeric matrix, and write the result to the file
myfile1. By default, the generated MATLAB function creates a dense numeric matrix specifying
each element of the matrix, including all zero elements.
f1 = matlabFunction(A,"File","myfile1");
function A = myfile1(x)
%MYFILE1
% A = MYFILE1(X)
A = reshape([x,0.0,0.0,0.0,x,0.0,0.0,0.0,x],[3,3]);
Convert A to a MATLAB function by setting Sparse name-value argument to true. Now, the
generated MATLAB function creates a sparse numeric matrix specifying only nonzero elements and
assuming that all other elements are zeros.
f2 = matlabFunction(A,"File","myfile2","Sparse",true);
function A = myfile2(x)
%MYFILE2
% A = MYFILE2(X)
A = sparse([1,2,3],[1,2,3],[x,x,x],3,3);
When converting a symbolic expression to a MATLAB function, you can specify the names of the
output variables. Note that matlabFunction without the File name-value argument (or with a file
path specified as an empty character vector) creates a function handle and ignores the Outputs
name-value argument.
7-1028
matlabFunction
syms x y z
r = x^2 + y^2 + z^2;
q = x^2 - y^2 - z^2;
Convert r and q to a single MATLAB function and write the resulting function to a file myfile, which
returns a vector of two elements, name1 and name2.
f = matlabFunction(r,q,"File","myfile", ...
"Outputs",{'name1','name2'});
You can speed up the evaluation of a symbolic function at given coordinates by converting the
symbolic function to an anonymous MATLAB function. Use matlabFunction to perform the
conversion. Evaluation of a symbolic function returns symbolic numbers that are exact, while
evaluation of a MATLAB function returns double-precision numbers.
Evaluate the symbolic function at these coordinates. Measure the elapsed time using a pair of tic
and toc calls.
tic
fResult = f(xDouble,yDouble,zDouble);
toc
Here, evaluation is slow, but it returns symbolic numbers that are exact. Show a sample of the
results.
fResult(1:2,1:2,20)
ans =
20 sin 1 + cos 1 sin 20 − 8000 20 sin 2 + 2 cos 1 sin 20 − 8000
40 sin 1 + cos 2 sin 20 − 8000 40 sin 2 + 2 cos 2 sin 20 − 8000
To speed up the evaluation of the function, convert the symbolic function to a MATLAB function using
matlabFunction. Evaluate the MATLAB function at the same coordinates.
7-1029
7 Functions
f1 = matlabFunction(f);
tic
fResult = f1(xDouble,yDouble,zDouble);
toc
Here, evaluation is faster. The evaluated MATLAB function returns double-precision numbers. Show a
sample of the results.
fResult(1:2,1:2,20)
ans = 2×2
103 ×
-7.9827 -7.9808
-7.9667 -7.9644
Input Arguments
f — Symbolic input to be converted to MATLAB function
symbolic expression | symbolic function | symbolic vector | symbolic matrix
matlabFunction does not create a separate output argument for each element of a symbolic vector
or matrix. For example, ht = matlabFunction([x + 1, y + 1]) creates a MATLAB function
with one output argument, while ht = matlabFunction(x + 1, y + 1) creates a MATLAB
function with two output arguments.
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: matlabFunction(f,"File","myfile","Optimize",false)
Comments to include in the file header, specified as a character vector, cell array of character
vectors, or string array.
7-1030
matlabFunction
Path to the file containing the generated MATLAB function, specified as a character vector or string
scalar. The generated function accepts arguments of type double and can be used without Symbolic
Math Toolbox. If File is empty, matlabFunction generates an anonymous function. If File does
not end in .m, the function appends .m.
When writing to a file, matlabFunction optimizes the code using intermediate variables named t0,
t1, and so on. To disable code optimization, use the Optimize name-value argument.
Whether to optimize code written to a function file, specified as logical 1 (true) or 0 (false).
When writing to a file, matlabFunction optimizes the code by default using intermediate variables
named t0, t1, and so on.
Using matlabFunction without the File name-value argument (or with a file path specified as an
empty character vector) creates a function handle. In this case, the code is not optimized by default.
If you try to enforce code optimization by setting Optimize to true, then matlabFunction throws
an error.
Whether to use sparse matrix generation, specified as logical 0 (false) or 1 (true). By default,
Sparse is false, so the generated MATLAB function represents symbolic matrices with dense
numeric matrices. When you specify Sparse as true, the generated MATLAB function represents
symbolic matrices with sparse numeric matrices. Specify Sparse as true when you convert symbolic
matrices containing many zero elements. Often, operations on sparse matrices are more efficient than
the same operations on dense matrices.
Order of input variables or vectors in a generated MATLAB function, specified as a character vector, a
vector of symbolic variables, or a one-dimensional cell array of character vectors, symbolic variables,
or vectors of symbolic variables.
The number of specified input variables must equal or exceed the number of symbolic variables in f.
Do not use the same names for the input variables specified by Vars and the output variables
specified by Outputs.
7-1031
7 Functions
By default, when you convert symbolic expressions that contain only lowercase letters for the variable
names, the order of the input variables is alphabetical. When you convert symbolic functions, their
input arguments appear in front of other variables, and all other variables are ordered alphabetically.
Specify Vars as a vector to generate a MATLAB function with input arguments that are scalar
variables. Specify Vars as a cell array to generate a MATLAB function with input arguments that are
a combination of scalar and vector variables.
If you do not specify the output variable names, then they coincide with the names you use when
calling matlabFunction. If you call matlabFunction using an expression instead of individual
variables, the default names of output variables consist of the word out followed by a number, for
example, out3.
Do not use the same names for the input variables specified by Vars and the output variables
specified by Outputs.
matlabFunction without the File name-value argument (or with a file path specified as an empty
character vector) creates a function handle. In this case, matlabFunction ignores the Outputs
name-value argument.
Output Arguments
ht — Function handle
MATLAB function handle
MATLAB function handle. You can use this function handle to return numerical results to be used
without Symbolic Math Toolbox.
Limitations
• Some symbolic functions that have no corresponding MATLAB functions operating on the double
data type, such as simplify and solve, are kept as symbolic functions in the converted MATLAB
function handle or file. The converted file that consists of these functions cannot be deployed
using MATLAB Coder or MATLAB Compiler. You need to create your own functions with the
double data type to replace these symbolic functions. If you are interested in a symbolic function
that cannot be deployed, please contact MathWorks Technical Support.
Tips
• When you use the File name-value argument, use rehash to make the generated function
available immediately. rehash updates the MATLAB list of known files for directories on the
search path.
• If the File name-value argument is empty, then MATLAB function returns an anonymous function.
7-1032
matlabFunction
syms x
p = piecewise(x<0, x^2-8, x>=0, -x)
matlabFunction(p,"File","piecewiseFunc")
y1 = piecewiseFunc(0)
y2 = piecewiseFunc(-2)
• Use matlabFunction to convert one or more symbolic expressions to a MATLAB function and
write the resulting function to an M-file. You can then use the generated M-file to create
standalone applications and web apps using MATLAB Compiler. For example, see “Deploy
Generated MATLAB Functions from Symbolic Expressions with MATLAB Compiler” on page 5-10.
You can also use the generated M-file to create C or C++ code using the MATLAB Coder app. For
example, see “Generate C Code from Symbolic Expressions Using the MATLAB Coder App” on
page 5-16.
• To generate a MATLAB function with input arguments that are a combination of scalar and vector
variables, specify the Vars name-value argument as a cell array. For examples, see “Specify Input
Arguments for Generated Function” on page 7-1025 and “Generate Function with Vector Input
Arguments” on page 7-1026.
Version History
Introduced in R2008b
See Also
ccode | daeFunction | fortran | rehash | matlabFunctionBlock | odeFunction |
simscapeEquation | subs | sym2poly
Topics
“Generate MATLAB Functions from Symbolic Expressions” on page 5-3
“Generate C Code from Symbolic Expressions Using the MATLAB Coder App” on page 5-16
“Deploy Generated MATLAB Functions from Symbolic Expressions with MATLAB Compiler” on page
5-10
“Using Symbolic Mathematics with Optimization Toolbox Solvers” on page 5-37
7-1033
7 Functions
matlabFunctionBlock
Convert symbolic expression to MATLAB function block
Syntax
matlabFunctionBlock(block,f)
matlabFunctionBlock(block,f1,...,fN)
matlabFunctionBlock( ___ ,Name,Value)
Description
matlabFunctionBlock(block,f) converts f to a MATLAB function block that you can use in
Simulink models. Here, f can be a symbolic expression, function, or a vector of symbolic expressions
or functions.
block specifies the name of the block that you create or modify.
Examples
Create a new model and convert a symbolic expression to a MATLAB function block. Include
comments in the block by specifying the Comments option.
new_system('my_system')
open_system('my_system')
syms x y z
f = x^2 + y^2 + z^2;
Use matlabFunctionBlock to create the block my_block containing the symbolic expression.
matlabFunctionBlock overwrites existing blocks.
matlabFunctionBlock('my_system/my_block',f)
7-1034
matlabFunctionBlock
Double-click the generated block to open and edit the function defining the block.
function f = my_block(x,y,z)
%#codegen
% This function was generated by the Symbolic Math Toolbox version 7.3.
% 01-Jan-2017 00:00:00
f = x.^2+y.^2+z.^2;
function f = my_block(x,y,z)
...
%Version: 1.1
f = x.^2+y.^2+z.^2;
Create a new model and convert a symbolic function to a MATLAB function block.
7-1035
7 Functions
syms x y z
f(x,y,z) = x^2 + y^2 + z^2;
Convert f to a MATLAB function block. Double-click the block to see the function.
matlabFunctionBlock('my_system/my_block',f)
function f = my_block(x,y,z)
%#codegen
f = x.^2+y.^2+z.^2;
Convert several symbolic expressions to a MATLAB function block with multiple output ports.
new_system('my_system')
open_system('my_system')
syms x y z
f = x^2;
g = y^2;
h = z^2;
Convert them to a MATLAB function block. matlabFunctionBlock creates a block with three
output ports. Double-click the block to see the function.
matlabFunctionBlock('my_system/my_block',f,g,h)
Specify the name of the function defining the generated MATLAB function block.
new_system('my_system')
open_system('my_system')
syms x y z
f = x^2 + y^2 + z^2;
7-1036
matlabFunctionBlock
Generate a block and set the function name to my_function. Double-click the block to see the
function.
matlabFunctionBlock('my_system/my_block',f,...
'FunctionName','my_function')
function f = my_function(x,y,z)
%#codegen
f = x.^2+y.^2+z.^2;
Use matlabFunctionBlock to create the block my_block containing the symbolic expression.
Double-click the block to see the function defining the block. By default, matlabFunctionBlock
creates a file containing the optimized code.
matlabFunctionBlock('my_system/my_block',r)
function r = my_block(x)
%#codegen
t2 = x.^2;
r = t2.*(t2+1.0);
function r = my_block(x)
%#codegen
r = x.^2.*(x.^2+1.0);
Specify the order of the input variables that form the input ports in a generated block.
7-1037
7 Functions
function f = my_block(x,y,z)
%#codegen
f = x.^2+y.^2+z.^2;
Use the Vars argument to specify the order of the input ports.
matlabFunctionBlock('my_system/my_block',f,...
'Vars',[y z x])
function f = my_block(y,z,x)
%#codegen
f = x.^2+y.^2+z.^2;
Create a symbolic variable u and a 3-by-1 vector of symbolic variables x. The following command also
automatically generates the symbolic variables x1, x2, and x3 in the MATLAB workspace.
syms u
syms x [3 1]
whos
u 1x1 8 sym
x 3x1 8 sym
x1 1x1 8 sym
x2 1x1 8 sym
x3 1x1 8 sym
xdot =
x2
x3
3*u - x1 - x2 - 2*x3
7-1038
matlabFunctionBlock
Convert the xdot expression to a MATLAB function block. Because the elements of xdot contain the
variable u and the automatically generated variables x1, x2, and x3, specify the Vars argument in
terms of these variables explicitly instead of using u and x.
matlabFunctionBlock('my_system/my_block',xdot,'Vars',{u,x1,x2,x3})
When generating a block, rename the output variables and the corresponding ports.
new_system('my_system')
open_system('my_system')
syms x y z
f = x^2 + y^2 + z^2;
Convert the expression to a MATLAB function block and specify the names of the output variables
and ports. Double-click the block to see the function defining the block.
new_system('my_system')
open_system('my_system')
7-1039
7 Functions
syms x y z
f = x^2 + y^2 + z^2;
Call matlabFunctionBlock using the name-value pair arguments to specify the function name, the
order of the input ports, and the names of the output ports. Double-click the block to see the function
defining the block.
new_system('my_system')
open_system('my_system')
syms x
f = sqrt(x);
matlabFunctionBlock('my_system/my_block',f,'FunctionName','sqrt_block')
Because the square root function generates a complex result when the input x is negative, you need
to manually specify a complex input in the generated block. Otherwise, you can encounter an error
when running the function block with a negative input.
Double-click the block to see the function defining the block. Add the line x = complex(x); to
specify a complex input. Starting in R2023a, matlabFunctionBlock provides this line and you can
uncomment it. The generated function block now accepts a complex input and returns a complex
output.
function f = sqrt_block(x)
%#codegen
x = complex(x); % required to enforce complex operations on x
f = sqrt(x);
end
7-1040
matlabFunctionBlock
As an alternative, you can also insert the Complex to Real-Imag and Real-Imag to Complex blocks
from the Simulink > Math Operations library. Add these blocks to convert the input signal that
goes into x to a complex signal.
Input Arguments
block — Block to create or modify
character vector
Symbolic input to be converted to a MATLAB function block with N outputs, specified as several
symbolic expressions, functions, vectors, or matrices, separated by commas.
7-1041
7 Functions
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: matlabFunctionBlock('my_system/my_block',f,'FunctionName','myfun')
Comments to include in the file header, specified as a character vector, cell array of character
vectors, or string vector.
When writing to a file, matlabFunctionBlock optimizes the code using intermediate variables
named t0, t1, ....
Vars — Order of input variables and corresponding input ports of generated block
character vector | vector of symbolic variables | one-dimensional cell array of character vectors | one-
dimensional cell array of symbolic variables | one-dimensional cell array of vectors of symbolic
variables
Order of input variables and corresponding input ports of the generated block, specified as a
character vector, a vector of symbolic variables, or a one-dimensional cell array of character vectors,
symbolic variables, or vectors of symbolic variables.
The number of specified input ports must equal or exceed the number of free variables in f. Do not
use the same names for the input ports specified by Vars and the output ports specified by Outputs.
By default, when you convert symbolic expressions, the order is alphabetical. When you convert
symbolic functions, their input arguments appear in front of other variables, and all other variables
are sorted alphabetically.
7-1042
matlabFunctionBlock
Names of output ports, specified as a one-dimensional cell array of character vectors. If you do not
specify the output port names, matlabFunctionBlock uses names that consist of the word out
followed by output port numbers, for example, out3.
Do not use the same names for the input ports specified by Vars and the output ports specified by
Outputs. See “Specify Output Ports” on page 7-1039.
Limitations
• Some symbolic functions that have no corresponding MATLAB functions operating on the double
data type, such as simplify and solve, are kept as symbolic functions in the generated MATLAB
function block. The converted function block that consists of these functions cannot be used in
Simulink models. You need to create your own functions with the double data type to replace
these symbolic functions. If you are interested in a symbolic function that cannot be used in
Simulink models, please contact MathWorks Technical Support.
Version History
Introduced in R2009a
See Also
ccode | fortran | matlabFunction | simscapeEquation | subs | sym2poly
Topics
“Implement MATLAB Functions in Simulink with MATLAB Function Blocks” (Simulink)
“Generate MATLAB Function Blocks from Symbolic Expressions” on page 5-6
7-1043
7 Functions
max
Maximum elements of symbolic input
Syntax
M = max(A)
M = max(A,[],nanflag)
M = max(A,[],dim)
M = max(A,[],dim,nanflag)
M = max(A,[],'all')
M = max(A,[],'all',nanflag)
C = max(A,B)
C = max(A,B,nanflag)
Description
M = max(A) returns the maximum elements of a symbolic input.
For an input A that contains symbolic expression, the symbolic max function returns an unevaluated
expression that is reduced by eliminating arguments that do not represent maximum values. The
output may have another argument that represents the condition for the symbolic variable. For
example, syms x; max([1 x]) returns the output max([1, x], [], 2, 'Omitnan', ~in(x,
'real')) in the Command Window since x is complex.
M = max(A,[],nanflag) specifies whether to include or omit NaN values in the calculation. For
example, max(A,[],'includenan') includes all NaN values in A while max(A,[],'omitnan')
ignores them.
M = max(A,[],dim) returns the maximum element along dimension dim. For example, if A is a
matrix, then max(A,[],2) is a column vector containing the maximum value of each row.
M = max(A,[],dim,nanflag) also specifies the dimension to operate along when using the
nanflag option.
M = max(A,[],'all',nanflag) computes the maximum over all elements of A when using the
nanflag option.
Examples
7-1044
max
Create a symbolic vector of real elements. Find the largest real element using the symbolic max
function.
syms x real
A = [23 42 37 18 x];
M = max(A)
The symbolic max function returns an unevaluated expression. The expression is reduced by
eliminating arguments that do not represent maximum values.
Create a symbolic vector and compute its maximum, excluding NaN values.
syms x positive
A = [1.75 x 3.25 -2.5 NaN 0.5 NaN 0.2 -4*x];
M = max(A,[],'omitnan')
M =
13
max , x , , 2, "omitnan", symfalse
4
max(A) will also produce this result since 'omitnan' is the default option.
M = NaN
Create a symbolic matrix and find the largest element in each column.
syms x real
A = [1 x -0.5; -2 2 x]
A =
1
1 x −
2
−2 2 x
M = max(A)
M =
1
1 max 2, x , , 2, "omitnan", symfalse max − , x , , 2, "omitnan", symfalse
2
7-1045
7 Functions
Create a symbolic matrix and find the largest element in each row.
syms x real
A = [1 x -0.5; -2 2 x]
A =
1
1 x −
2
−2 2 x
M = max(A,[],2)
M =
max 1, x , , 2, "omitnan", symfalse
max 2, x , , 2, "omitnan", symfalse
Maximum of Matrix
syms x real
A = [1 x -0.5; -2 2 x]
A =
1
1 x −
2
−2 2 x
To find the maximum over all dimensions of a matrix, use the 'all' option.
M = max(A,[],'all')
Create two symbolic matrices with complex elements. Find the largest elements taken from the two
matrices, which are complex values with the largest magnitude.
syms x y
A = [x 2+1i; 3 4i; -5 y]
A =
x 2+ i
3 4 i
−5 y
B = [1 y; 2i 1+1i; -3 x]
B =
7-1046
max
1 y
2 i 1+ i
−3 x
C = max(A,B)
C =
max 1, x , , 2, "omitnan", x ∉ ℝ max 2 + i , y , , 2, "omitnan", symtrue
3 4 i
−5 max x, y , , 2, "omitnan", x ∉ ℝ ∨ y ∉ ℝ
Define the following expression by using the symbolic max function. Assume that the variable x is
real.
x−1 x>1
f x =
0 x<1
syms x real
f(x) = sqrt(max(x,1) - 1)
f(x) =
max 1, x , , 2, "omitnan", symfalse − 1
fplot(f,[-5 5])
7-1047
7 Functions
Input Arguments
A — Input array
symbolic expression | vector of symbolic expressions | matrix of symbolic expressions
• If A is complex, then max(A) returns the complex value with the largest magnitude. If magnitudes
are equal, then max(A) returns the value with the largest magnitude and the largest phase angle.
• If A is a scalar, then max(A) returns A.
• If A is a 0-by-0 empty array, then max(A) is an empty array as well.
• 'omitnan' — Ignore all NaN values in the input. If all elements are NaN, then max returns the
first one.
• 'includenan' — Include the NaN values in the input for the calculation.
7-1048
max
Dimension to operate along, specified as a positive integer scalar. If no value is specified, then the
default is the first array dimension whose size does not equal 1.
Dimension dim indicates the dimension whose length reduces to 1. The size(M,dim) is 1, while the
sizes of all other dimensions remain the same, unless size(A,dim) is 0. If size(A,dim) is 0, then
max(A,dim) returns an empty array with the same size as A.
• If dim = 1, then max(A,[],1) returns a row vector containing the smallest element in each
column.
• If dim = 2, then max(A,[],2) returns a column vector containing the smallest element in each
row.
Additional input array, specified as a symbolic expression, vector, or matrix of symbolic expressions.
Inputs A and B must either be the same size or have sizes that are compatible (for example, A is an M-
by-N matrix and B is a scalar or 1-by-N row vector). For more information, see “Compatible Array
Sizes for Basic Operations”.
Data Types: sym | single | double
7-1049
7 Functions
Output Arguments
M — Maximum values
symbolic expression | vector of symbolic expressions | matrix of symbolic expressions
Version History
Introduced in R2021a
The max function can now operate on symbolic expressions involving symbolic variables, where they
threw an error in previous releases.
See Also
sort | min
Topics
“Array Indexing”
7-1050
meijerG
meijerG
Meijer G-function
Syntax
meijerG(a,b,c,d,z)
Description
meijerG(a,b,c,d,z) returns the “Meijer G-Function” on page 7-1054. meijerG is element-wise in
z. The input parameters a, b, c, and d are vectors that can be empty, as in meijerG([], [], 3.2,
[], 1).
Examples
syms x
meijerG(3, [], [], 2, 5)
ans =
25
a = 2;
z = [1 2 3];
meijerG(a, [], [], [], z)
ans =
0.3679 1.2131 2.1496
Convert numeric input to symbolic form using sym, and find the Meijer G-function. For certain
symbolic inputs, meijerG returns exact symbolic output using other functions.
ans =
3*exp(-1/3)
ans =
(2^(4/5)*3^(1/2)*gamma(1/10))/80
7-1051
7 Functions
For symbolic variables or expressions, meijerG returns an output in terms of simple or special
functions.
syms a b c d z
f = meijerG(a,b,c,d,z)
f =
(gamma(c - a + 1)*(1/z)^(1 - a)*hypergeom([c - a + 1, d - a + 1],...
b - a + 1, 1/z))/(gamma(b - a + 1)*gamma(a - d))
Substitute values for the variables by using subs, and convert values to double by using double.
fVal = subs(f, [a b c d z], [1.2 3 5 7 9])
fVal =
(266*9^(1/5)*hypergeom([24/5, 34/5], 14/5, 1/9))/(25*gamma(-29/5))
double(fVal)
ans =
5.7586e+03
ans =
5758.5946416377834597597497022199
Show relations between meijerG and simpler functions for given parameter values.
Show that when a, b, and d are empty, and c = 0, then meijerG reduces to exp(-z).
syms z
meijerG([], [], 0, [], z)
ans =
exp(-z)
Show that when a, b, and d are empty, and c = [1/2 -1/2], then meijerG reduces to 2Kv(1,2z1/2).
meijerG([], [], [1/2 -1/2], [], z)
ans =
2*besselk(1, 2*z^(1/2))
Plot the real and imaginary values of the Meijer G-function for values of b and z, where a = [-2 2]
and c and d are empty. Fill the contours by setting Fill to on.
syms b z
f = meijerG([-2 2], b, [], [], z);
subplot(2,2,1)
fcontour(real(f),'Fill','on')
7-1052
meijerG
subplot(2,2,2)
fcontour(imag(f),'Fill','on')
title('Imag. Values of Meijer G')
xlabel('b')
ylabel('z')
Input Arguments
a — Input
number | vector | symbolic number | symbolic variable | symbolic vector | symbolic function |
symbolic expression
Input, specified as a number or vector, or a symbolic number, variable, vector, function, or expression.
b — Input
number | vector | symbolic number | symbolic variable | symbolic vector | symbolic function |
symbolic expression
Input, specified as a number or vector, or a symbolic number, variable, vector, function, or expression.
c — Input
number | vector | symbolic number | symbolic variable | symbolic vector | symbolic function |
symbolic expression
7-1053
7 Functions
Input, specified as a number or vector, or a symbolic number, variable, vector, function, or expression.
d — Input
number | vector | symbolic number | symbolic variable | symbolic vector | symbolic function |
symbolic expression
Input, specified as a number or vector, or a symbolic number, variable, vector, function, or expression.
z — Input
number | vector | symbolic number | symbolic variable | symbolic vector | symbolic matrix | symbolic
multidimensional array | symbolic function | symbolic expression
Input, specified as a number or vector, or a symbolic number, variable, vector, function, or expression.
More About
Meijer G-Function
∏ ∏
m n
Γ bj − s Γ 1 − aj + s
a1, …, ap j=1 j=1
m, n
Gp, q z =
1
∫ zsds .
∏ ∏
b1, …, bq 2πi q p
Γ 1 − bj + s Γ aj − s
j=m+1 j=n+1
Algorithms
For the Meijer G-function meijerG([a1,…,an], [an + 1,…,ap], [b1,…,bm], [bm + 1,…,bq], z),
for ai ∊ (a1,…,an) and bj ∊ (b1,…,bm), no pair of parameters ai − bj should differ by a positive integer.
The Meijer G-function involves a complex contour integral with one of the following types of
integration paths:
• The contour goes from - i ∞ to i ∞ so that all poles of Γ b j − s , j = 1, …, m lie to the right of the
path, and all poles of Γ 1 − ak + s , k = 1, …, n lie to the left of the path. The integral converges if
p+q
c=m+n− > 0, |arg(z)| < c π. If |arg(z)| = c π, c ≥ 0, the integral converges absolutely
2
q p
you choose the contour so that the contour points near i ∞ and - i ∞ have a real part σ satisfying
q−p
q − p σ > ℜ(ψ) + 1 − .
2
• The contour is a loop beginning and ending at ∞ and encircling all poles of Γ b j − s , j = 1, …, m
moving in the negative direction, but none of the poles of Γ 1 − ak + s , k = 1, …, n. The integral
converges if q ≥ 1 and either p < q or p = q and |z| < 1.
7-1054
meijerG
• The contour is a loop beginning and ending at - ∞ and encircling all poles of Γ 1 − ak + s , k = 1,
…, n moving in the positive direction, but none of the poles of Γ b j + s , j = 1, …, m. The integral
converges if p ≥ 1 and either p > q or p = q and |z| > 1.
The integral represents an inverse Laplace transform or, more specifically, a Mellin-Barnes type of
integral.
For a given set of parameters, the contour chosen in the definition of the Meijer G-function is the one
for which the integral converges. If the integral converges for several contours, all contours lead to
the same function.
The Meijer G-function satisfies a differential equation of order max(p, q) with respect to a variable z:
−1)
m+n−p
z ∏
i=1
z
d
dz
− ai − 1 − ∏
q
j=1
z
d
dz
− b j Gp, q
a , …, ap
m, n 1
b1, …, bp
z = 0.
If p < q, this differential equation has a regular singularity at z = 0 and an irregular singularity at z =
∞. If p = q, the points z = 0 and z = ∞ are regular singularities, and there is an additional regular
singularity at z = (−1)m + n - p.
The Meijer G-function represents an analytic continuation of the hypergeometric function [1]. For
particular choices of parameters, you can express the Meijer G-function through the hypergeometric
function. For example, if no two of the bh terms, h = 1, …, m, differ by an integer or zero and all poles
are simple, then
a1, …, ap m ∏ Γ b j − bh ∏ Γ 1 + bh − a j
m, n j = 1…m, j ≠ h j=1
Gp, q
b1, …, bp
z = ∑ q p
zbhpFq − 1
h=1
∏ Γ 1 + bh − b j ∏ Γ a j − bh
j=m+1 j=n+1
p−m−n
Ah; Bh; −1 z .
Ah = 1 + bh − a1, …, 1 + bh − ap .
Bh denotes
Meijer G-functions with different parameters can represent the same function.
• The Meijer G-function is symmetric with respect to the parameters. Changing the order inside
each of the following lists of vectors does not change the resulting Meijer G-function: [a1, …, an],
[an + 1, …, ap], [b1, …, bm], [bm + 1, …, bq].
• If z is not a negative real number and z ≠ 0, the function satisfies the following identity:
7-1055
7 Functions
m, n
a1, …, ap n, m
1 − b1, …, 1 − bp 1
Gp, q z = Gq, p .
b1, …, bq 1 − a1, …, 1 − ap z
.
• If 0 < n < p and r = a1 - ap is an integer, the function satisfies the following identity:
m, n
a1, a2, …, ap − 1, ap m, n
ap, a2, …, ap − 1, a1
Gp, q z = Gp, q z .
b1, b2, …, bq − 1, bq b1, b2, …, bq − 1, bq
.
• If 0 < m < q and r = b1 - bq is an integer, the function satisfies the following identity:
m, n
a1, a2, …, ap − 1, ap γ m, n a1, a2, …, ap − 1, ap
Gp, q z = −1 Gp, q z .
b1, b2, …, bq − 1, bq bq, b2, …, bq − 1, b1
According to these rules, the meijerG function call can return meijerG with modified input
parameters.
Version History
Introduced in R2017b
References
[1] Luke, Y. L., The Special Functions and Their Approximations. Vol. 1. New York: Academic Press,
1969.
[2] Prudnikov, A. P., Yu. A. Brychkov, and O. I. Marichev, Integrals and Series. Vol 3: More Special
Functions. Gordon and Breach, 1990.
[3] Abramowitz, M., I. A. Stegun, Handbook of Mathematical Functions. 9th printing. New York:
Dover Publications, 1970.
See Also
hypergeom
7-1056
min
min
Minimum elements of symbolic input
Syntax
M = min(A)
M = min(A,[],nanflag)
M = min(A,[],dim)
M = min(A,[],dim,nanflag)
M = min(A,[],'all')
M = min(A,[],'all',nanflag)
C = min(A,B)
C = min(A,B,nanflag)
Description
M = min(A) returns the minimum elements of a symbolic input.
For an input A that contains symbolic expression, the symbolic min function returns an unevaluated
expression that is reduced by eliminating arguments that do not represent minimum values. The
output may have another argument that represents the condition for the symbolic variable. For
example, syms x; min([1 x]) returns the output min([1, x], [], 2, 'Omitnan', ~in(x,
'real')) in the Command Window since x is complex.
M = min(A,[],nanflag) specifies whether to include or omit NaN values in the calculation. For
example, min(A,[],'includenan') includes all NaN values in A while min(A,[],'omitnan')
ignores them.
M = min(A,[],dim) returns the minimum element along dimension dim. For example, if A is a
matrix, then min(A,[],2) is a column vector containing the minimum value of each row.
M = min(A,[],dim,nanflag) also specifies the dimension to operate along when using the
nanflag option.
M = min(A,[],'all',nanflag) computes the minimum over all elements of A when using the
nanflag option.
Examples
7-1057
7 Functions
Create a symbolic vector of real elements. Find the smallest real element using the symbolic min
function.
syms x real
A = [23 42 37 18 x];
M = min(A)
The symbolic min function returns an unevaluated expression. The expression is reduced by
eliminating arguments that do not represent minimum values.
Create a symbolic vector and compute its minimum, excluding NaN values.
syms x positive
A = [1.75 x 3.25 -2.5 NaN 0.5 NaN 0.2 -4*x];
M = min(A,[],'omitnan')
M =
5
min − , −4 x , , 2, "omitnan", symfalse
2
min(A) will also produce this result since 'omitnan' is the default option.
M = NaN
Create a symbolic matrix and find the smallest element in each column.
syms x real
A = [1 x -0.5; -2 1 x]
A =
1
1 x −
2
−2 1 x
M = min(A)
M =
1
−2 min 1, x , , 2, "omitnan", symfalse min − , x , , 2, "omitnan", symfalse
2
7-1058
min
Create a symbolic matrix and find the smallest element in each row.
syms x real
A = [1 x -0.5; -2 1 x]
A =
1
1 x −
2
−2 1 x
M = min(A,[],2)
M =
1
min − , x , , 2, "omitnan", symfalse
2
min −2, x , , 2, "omitnan", symfalse
Minimum of Matrix
syms x real
A = [1 x -0.5; -2 1 x]
A =
1
1 x −
2
−2 1 x
To find the minimum over all dimensions of a matrix, use the 'all' option.
M = min(A,[],'all')
Create two symbolic matrices with complex elements. Find the smallest elements taken from the two
matrices, which are complex values with the smallest magnitude.
syms x y
A = [x 2+1i; 3 4i; -5 y]
A =
x 2+ i
3 4 i
−5 y
B = [1 y; 2i 1+1i; -3 x]
B =
7-1059
7 Functions
1 y
2 i 1+ i
−3 x
C = min(A,B)
C =
min 1, x , , 2, "omitnan", x ∉ ℝ min 2 + i , y , , 2, "omitnan", symtrue
2 i 1+ i
−3 min x, y , , 2, "omitnan", x ∉ ℝ ∨ y ∉ ℝ
Define the following expression by using the symbolic min function. Assume that the variable x is
real.
0 x>1
f x =
1−x x<1
syms x real
f(x) = sqrt(1 - min(x,1))
f(x) =
1 − min 1, x , , 2, "omitnan", symfalse
fplot(f,[-5 5])
7-1060
min
Input Arguments
A — Input array
symbolic expression | vector of symbolic expressions | matrix of symbolic expressions
• If A is complex, then min(A) returns the complex number with the smallest magnitude. If
magnitudes are equal, then min(A) returns the value with the smallest magnitude and the
smallest phase angle.
• If A is a scalar, then min(A) returns A.
• If A is a 0-by-0 empty array, then min(A) is an empty array as well.
• 'omitnan' — Ignore all NaN values in the input. If all elements are NaN, then min returns the
first one.
7-1061
7 Functions
• 'includenan' — Include the NaN values in the input for the calculation.
Dimension to operate along, specified as a positive integer scalar. If no value is specified, then the
default is the first array dimension whose size does not equal 1.
Dimension dim indicates the dimension whose length reduces to 1. The size(M,dim) is 1, while the
sizes of all other dimensions remain the same, unless size(A,dim) is 0. If size(A,dim) is 0, then
min(A,dim) returns an empty array with the same size as A.
• If dim = 1, then min(A,[],1) returns a row vector containing the smallest element in each
column.
• If dim = 2, then min(A,[],2) returns a column vector containing the smallest element in each
row.
Additional input array, specified as a symbolic expression, vector, or matrix of symbolic expressions.
Inputs A and B must either be the same size or have sizes that are compatible (for example, A is an M-
by-N matrix and B is a scalar or 1-by-N row vector). For more information, see “Compatible Array
Sizes for Basic Operations”.
7-1062
min
Output Arguments
M — Minimum values
symbolic expression | vector of symbolic expressions | matrix of symbolic expressions
Version History
Introduced in R2021a
The min function can now operate on symbolic expressions involving symbolic variables, where they
threw an error in previous releases.
See Also
sort | max
Topics
“Array Indexing”
7-1063
7 Functions
minpoly
Minimal polynomial of matrix
Syntax
minpoly(A)
minpoly(A,var)
Description
minpoly(A) returns a vector of the coefficients of the minimal polynomial on page 7-1065 of A. If A
is a symbolic matrix, minpoly returns a symbolic vector. Otherwise, it returns a vector with elements
of type double.
Examples
Compute Minimal Polynomial of Matrix
syms x
A = sym([1 1 0; 0 1 0; 0 0 1]);
minpoly(A, x)
ans =
x^2 - 2*x + 1
To find the coefficients of the minimal polynomial of A, call minpoly with one argument. Since A is
numeric, minpoly returns coefficients as double-precision values:
A = sym([1 1 0; 0 1 0; 0 0 1]);
minpoly(A)
ans =
[ 1, -2, 1]
Find the coefficients of the minimal polynomial of the symbolic matrix A. For this matrix, minpoly
returns the symbolic vector of coefficients:
A = sym([0 2 0; 0 0 2; 2 0 0]);
P = minpoly(A)
P =
[ 1, 0, 0, -8]
7-1064
minpoly
Input Arguments
A — Input
numeric matrix | symbolic matrix
var — Input
symbolic variable
Input, specified as a symbolic variable. If you do not specify var, minpoly returns a vector of
coefficients of the minimal polynomial instead of returning the polynomial itself.
More About
Minimal Polynomial of a Matrix
The minimal polynomial of a square matrix A is the monic polynomial p(x) of the least degree, such
that p(A) = 0.
Version History
Introduced in R2012b
See Also
charpoly | eig | jordan | poly2sym | sym2poly
7-1065
7 Functions
minus, -
Symbolic subtraction
Syntax
-A
A - B
minus(A,B)
Description
-A returns the negation of A.
Examples
Subtract Scalar from Array
syms x
A = [x 1;-2 sin(x)];
A - 2
ans =
[ x - 2, -1]
[ -4, sin(x) - 2]
syms x y z
M = [0 x; y z];
M - eye(2)
ans =
[ -1, x]
[ y, z - 1]
Subtract one number from another. Because these are not symbolic objects, you receive floating-point
results.
11/6 - 5/4
ans =
0.5833
7-1066
minus, -
sym(11/6) - sym(5/4)
ans =
7/12
minus(sym(11/6),sym(5/4))
ans =
7/12
Subtract Matrices
A = sym([3 4; 2 1]);
B = sym([8 1; 5 2]);
C = sym([6 3; 4 9]);
Y = A - B - C
Y =
[ -11, 0]
[ -7, -10]
-Y
ans =
[ 11, 0]
[ 7, 10]
Subtract Functions
y(x) =
2*x - g(x) + sin(x)
Input Arguments
A — Input
symbolic scalar variable | symbolic matrix variable | symbolic function | symbolic matrix function |
symbolic expression | symbolic vector | symbolic matrix | symbolic array
Input, specified as a symbolic scalar variable, matrix variable, function, matrix function, expression,
or vector, matrix, or array of symbolic scalar variables.
B — Input
symbolic scalar variable | symbolic matrix variable | symbolic function | symbolic matrix function |
symbolic expression | symbolic vector | symbolic matrix | symbolic array
7-1067
7 Functions
Input, specified as a symbolic scalar variable, matrix variable, function, matrix function, expression,
or vector, matrix, or array of symbolic scalar variables.
Tips
• All nonscalar arguments must have the same size. If one input argument is nonscalar, then minus
expands the scalar into an array of the same size as the nonscalar argument, with all elements
equal to the corresponding scalar.
Version History
Introduced before R2006a
See Also
ctranspose | ldivide | mldivide | mpower | mrdivide | mtimes | plus | power | rdivide |
times | transpose
7-1068
mixedUnits
mixedUnits
Split unit into sum of units
Syntax
mixedUnits(quantity,units)
Description
mixedUnits(quantity,units) splits the physical quantity quantity into a linear combination of
the units in units.
Examples
Split 8000 seconds into hours, minutes, and seconds by using mixedUnits. The result is 2 hours, 13
minutes, and 20 seconds.
u = symunit;
t = 8000*u.s;
tunits = [u.hour u.minute u.second];
tSplit = mixedUnits(t,tunits)
tSplit =
[ 2, 13, 20]
ans =
"2 hours + 13 minutes + 20.0 seconds"
Convert the geographic coordinate 15.352° into degrees (°), arcminutes ('), and arcseconds (''). The
result is 15° 21' 36/5''.
gCoord = 15.352*u.degree;
gUnits = [u.degree u.arcmin u.arcsec];
gCoordSplit = mixedUnits(gCoord,gUnits)
gCoordSplit =
[ 15, 21, 36/5]
gCoordDbl = double(gCoordSplit)
7-1069
7 Functions
gCoordDbl =
15.0000 21.0000 7.2000
Reconstruct the original coordinate by summing the split units and rewriting the result to degrees.
mixedUnits returns an exact symbolic result instead of a numeric approximation. For details, see
“Choose Numeric or Symbolic Arithmetic” on page 2-32.
gOrig = sum(gCoordSplit.*gUnits);
gOrig = rewrite(gOrig,u.degree)
gOrig =
(1919/125)*[deg]
Input Arguments
quantity — Input
symbolic expression with units
Input, specified as a symbolic expression with units. quantity must not contain symbolic variables.
Units in quantity and units must be compatible.
Units to represent input as, specified as a vector of symbolic units. Units must be in descending order
of magnitude. Units in quantity and units must be compatible.
Version History
Introduced in R2018a
See Also
symunit | unitConversionFactor
Topics
“Units of Measurement Tutorial” on page 2-47
“Unit Conversions and Unit Systems” on page 2-53
“Units and Unit Systems List” on page 2-60
7-1070
mldivide, \
mldivide, \
Symbolic matrix left division
Syntax
X = A\B
X = mldivide(A,B)
Description
X = A\B solves the symbolic system of linear equations in matrix form, A*X = B for X.
If the solution does not exist or if it is not unique, the \ operator issues a warning.
A can be a rectangular matrix, but the equations must be consistent. The symbolic operator \ does
not compute least-squares solutions.
Examples
System of Equations in Matrix Form
Solve a system of linear equations specified by a square matrix of coefficients and a vector of right
sides of equations.
Create a matrix containing the coefficient of equation terms, and a vector containing the right sides
of equations.
A = sym(pascal(4))
b = sym([4; 3; 2; 1])
A =
[ 1, 1, 1, 1]
[ 1, 2, 3, 4]
[ 1, 3, 6, 10]
[ 1, 4, 10, 20]
b =
4
3
2
1
X =
5
-1
0
0
7-1071
7 Functions
Rank-Deficient System
Create a matrix containing the coefficients of equation terms, and a vector containing the right sides
of equations.
A = sym(magic(4))
b = sym([0; 1; 1; 0])
A =
[ 16, 2, 3, 13]
[ 5, 11, 10, 8]
[ 9, 7, 6, 12]
[ 4, 14, 15, 1]
b =
0
1
1
0
Find the rank of the system. This system contains four equations, but its rank is 3. Therefore, the
system is rank-deficient. This means that one variable of the system is not independent and can be
expressed in terms of other variables.
rank(horzcat(A,b))
ans =
3
Try to solve this system using the symbolic \ operator. Because the system is rank-deficient, the
returned solution is not unique.
A\b
ans =
1/34
19/34
-9/17
0
Inconsistent System
Create a matrix containing the coefficient of equation terms, and a vector containing the right sides
of equations.
A = sym(magic(4))
b = sym([0; 1; 2; 3])
A =
[ 16, 2, 3, 13]
[ 5, 11, 10, 8]
[ 9, 7, 6, 12]
[ 4, 14, 15, 1]
b =
0
7-1072
mldivide, \
1
2
3
Try to solve this system using the symbolic \ operator. The operator issues a warning and returns a
vector with all elements set to Inf because the system of equations is inconsistent, and therefore, no
solution exists. The number of elements in the resulting vector equals the number of equations (rows
in the coefficient matrix).
A\b
ans =
Inf
Inf
Inf
Inf
Find the reduced row echelon form of this system. The last row shows that one of the equations
reduced to 0 = 1, which means that the system of equations is inconsistent.
rref(horzcat(A,b))
ans =
[ 1, 0, 0, 1, 0]
[ 0, 1, 0, 3, 0]
[ 0, 0, 1, -3, 0]
[ 0, 0, 0, 0, 1]
Input Arguments
A — Coefficient matrix
symbolic number | symbolic scalar variable | symbolic matrix variable | symbolic function | symbolic
matrix function | symbolic expression | symbolic vector | symbolic matrix
Coefficient matrix, specified as a symbolic number, scalar variable, matrix variable, function, matrix
function, expression, or vector or matrix of symbolic scalar variables.
B — Right side
symbolic number | symbolic scalar variable | symbolic matrix variable | symbolic function | symbolic
matrix function | symbolic expression | symbolic vector | symbolic matrix
Right side, specified as a symbolic number, scalar variable, matrix variable, function, matrix function,
expression, or vector or matrix of symbolic scalar variables.
Output Arguments
X — Solution
symbolic number | symbolic scalar variable | symbolic matrix variable | symbolic function | symbolic
matrix function | symbolic expression | symbolic vector | symbolic matrix
Solution, returned as a symbolic number, scalar variable, matrix variable, function, matrix function,
expression, or vector or matrix of symbolic scalar variables.
7-1073
7 Functions
Tips
• Matrix computations involving many symbolic variables can be slow. To increase the
computational speed, reduce the number of symbolic variables by substituting the given values for
some variables.
• When dividing by zero, mldivide considers the numerator’s sign and returns Inf or -Inf
accordingly.
syms x
[sym(0)\sym(1), sym(0)\sym(-1), sym(0)\x]
ans =
[ Inf, -Inf, Inf*x]
Version History
Introduced before R2006a
See Also
ctranspose | ldivide | minus | mpower | mrdivide | mtimes | plus | power | rdivide | times |
transpose
7-1074
mod
mod
Symbolic modulus after division
Note Starting in R2020b, mod no longer finds the modulus for each coefficient of a symbolic
polynomial. For more information, see “Compatibility Considerations”.
Syntax
m = mod(a,b)
Description
m = mod(a,b) finds the modulus on page 7-1078 after division. To find the remainder, use rem.
If a is a polynomial expression, then mod(a,b) returns the unevaluated modulus of the polynomial.
Examples
Find the modulus after division when both the dividend and divisor are integers.
m = 3 −1 1 −3
Find the modulus after division when the dividend is a rational number, and the divisor is an integer.
m =
7 1 13
−
3 2 2
Find the modulus after division when the dividend is a polynomial expression, and the divisor is an
integer. If the dividend is a polynomial expression, then mod returns a symbolic expression without
evaluating the modulus.
7-1075
7 Functions
syms x
a = x^3 - 2*x + 999;
mUneval = mod(a,10)
To evaluate the modulus for each polynomial coefficient, first extract the coefficients of each term
using coeffs.
[c,t] = coeffs(a)
c = 1 −2 999
t = x3 x 1
Next, find the modulus of each coefficient in c divided by 10. Reconstruct a new polynomial using the
evaluated coefficients.
cMod10 = mod(c,10);
mEval = sum(cMod10.*t)
mEval = x3 + 8 x + 9
For vectors and matrices, mod finds the modulus after division element-wise. When both arguments
are nonscalar, they must have the same size. If one argument is a scalar, the mod function expands
the scalar input into an array of the same size as the other input.
Find the modulus after division for the elements of two matrices.
A = sym([27,28; 29,30]);
B = sym([2,3; 4,5]);
M = mod(A,B)
M =
11
10
Find the modulus after division for the elements of matrix A and the value 9. Here, mod expands 9
into the 2-by-2 matrix with all elements equal to 9.
M = mod(A,9)
M =
01
23
7-1076
mod
Define the sawtooth wave with period T = 2 and amplitude A = 1.5. Create a symbolic function
y(x). Use mod functions to define the sawtooth wave for each period. The sawtooth wave increases
linearly for a full period, and it drops back to zero at the start of another period.
T = 2;
A = 1.5;
syms y(x);
y(x) = A*mod(x,T)/T;
fplot(y,[-6 6])
Next, create another sawtooth wave that is symmetrical within a single period. Use piecewise to
define the sawtooth wave that is increasing linearly for the first half of a period, and then decreasing
linearly for the second half of a period.
fplot(y,[-6 6])
7-1077
7 Functions
Input Arguments
a — Dividend (numerator)
number | symbolic number | symbolic variable | polynomial expression | vector | matrix
b — Divisor (denominator)
number | symbolic number | vector | matrix
More About
Modulus
a
mod a, b = a − b · floor ,
b
7-1078
mod
where floor rounds (a / b) toward negative infinity. For example, the modulus of –8 and –3 is –2, but
the modulus of –8 and 3 is 1.
Tips
• Calling mod for numbers that are not symbolic objects invokes the MATLAB mod function.
Version History
Introduced before R2006a
R2020b: mod no longer finds the modulus for each coefficient of a symbolic polynomial
Behavior changed in R2020b
Starting in R2020b, mod no longer finds the modulus for each coefficient of a symbolic polynomial.
Instead, mod(a,b) returns an unevaluated symbolic expression if a is a symbolic polynomial and b is
a real number. To find the modulus for each coefficient of the polynomial a, use [c,t] =
coeffs(a); sum(mod(c,b).*t). You can now create periodic symbolic functions by defining the
periodicity using mod. For example, see “Create Periodic Sawtooth Waves” on page 7-1076.
See Also
powermod | quorem | rem | coeffs
7-1079
7 Functions
mpower, ^
Symbolic matrix power
Syntax
A^B
mpower(A,B)
Description
A^B computes A to the B power.
Examples
Matrix Base and Scalar Exponent
A = sym('a%d%d', [2 2])
A =
[ a11, a12]
[ a21, a22]
Find A^2.
A^2
ans =
[ a11^2 + a12*a21, a11*a12 + a12*a22]
[ a11*a21 + a21*a22, a22^2 + a12*a21]
A = sym(magic(2))
A =
[ 1, 3]
[ 4, 2]
Find πA.
sym(pi)^A
ans =
[ (3*pi^7 + 4)/(7*pi^2), (3*(pi^7 - 1))/(7*pi^2)]
[ (4*(pi^7 - 1))/(7*pi^2), (4*pi^7 + 3)/(7*pi^2)]
7-1080
mpower, ^
Input Arguments
A — Base
number | symbolic number | symbolic scalar variable | symbolic function | symbolic matrix function |
symbolic expression | square symbolic matrix variable | square matrix of symbolic scalar variables
Base, specified as a number or a symbolic number, scalar variable, function, matrix function,
expression, square symbolic matrix variable, or square matrix of symbolic scalar variables. A and B
must be one of the following:
B — Exponent
number | symbolic number | symbolic scalar variable | symbolic function | symbolic expression |
square matrix of symbolic scalar variables
Version History
Introduced before R2006a
See Also
ctranspose | ldivide | minus | mldivide | mrdivide | mtimes | plus | power | rdivide |
times | transpose
7-1081
7 Functions
mrdivide, /
Symbolic matrix right division
Syntax
X = B/A
X = mrdivide(B,A)
Description
X = B/A solves the symbolic system of linear equations in matrix form, X*A = B for X. The matrices
A and B must contain the same number of columns. The right division of matrices B/A is equivalent to
(A'\B')'.
If the solution does not exist or if it is not unique, the / operator issues a warning.
A can be a rectangular matrix, but the equations must be consistent. The symbolic operator / does
not compute least-squares solutions.
Examples
System of Equations in Matrix Form
Solve a system of linear equations specified by a square matrix of coefficients and a vector of right
sides of equations.
Create a matrix containing the coefficient of equation terms, and a vector containing the right sides
of equations.
A = sym(pascal(4))
b = sym([4 3 2 1])
A =
[ 1, 1, 1, 1]
[ 1, 2, 3, 4]
[ 1, 3, 6, 10]
[ 1, 4, 10, 20]
b =
[ 4, 3, 2, 1]
X = b/A
X =
[ 5, -1, 0, 0]
7-1082
mrdivide, /
Rank-Deficient System
Create a matrix containing the coefficient of equation terms, and a vector containing the right sides
of equations.
A = sym(magic(4))'
b = sym([0 1 1 0])
A =
[ 16, 5, 9, 4]
[ 2, 11, 7, 14]
[ 3, 10, 6, 15]
[ 13, 8, 12, 1]
b =
[ 0, 1, 1, 0]
Find the rank of the system. This system contains four equations, but its rank is 3. Therefore, the
system is rank-deficient. This means that one variable of the system is not independent and can be
expressed in terms of other variables.
rank(vertcat(A,b))
ans =
3
Try to solve this system using the symbolic / operator. Because the system is rank-deficient, the
returned solution is not unique.
b/A
ans =
[ 1/34, 19/34, -9/17, 0]
Inconsistent System
Create a matrix containing the coefficient of equation terms, and a vector containing the right sides
of equations.
A = sym(magic(4))'
b = sym([0 1 2 3])
A =
[ 16, 5, 9, 4]
[ 2, 11, 7, 14]
[ 3, 10, 6, 15]
[ 13, 8, 12, 1]
b =
[ 0, 1, 2, 3]
Try to solve this system using the symbolic / operator. The operator issues a warning and returns a
vector with all elements set to Inf because the system of equations is inconsistent, and therefore, no
solution exists. The number of elements equals the number of equations (rows in the coefficient
matrix).
b/A
7-1083
7 Functions
ans =
[ Inf, Inf, Inf, Inf]
Find the reduced row echelon form of this system. The last row shows that one of the equations
reduced to 0 = 1, which means that the system of equations is inconsistent.
rref(vertcat(A,b)')
ans =
[ 1, 0, 0, 1, 0]
[ 0, 1, 0, 3, 0]
[ 0, 0, 1, -3, 0]
[ 0, 0, 0, 0, 1]
Input Arguments
A — Coefficient matrix
symbolic number | symbolic scalar variable | symbolic matrix variable | symbolic function | symbolic
matrix function | symbolic expression | symbolic vector | symbolic matrix
Coefficient matrix, specified as a symbolic number, scalar variable, matrix variable, function, matrix
function, expression, or vector or matrix of symbolic scalar variables.
B — Right side
symbolic number | symbolic scalar variable | symbolic matrix variable | symbolic function | symbolic
matrix function | symbolic expression | symbolic vector | symbolic matrix
Right side, specified as a symbolic number, scalar variable, matrix variable, function, matrix function,
expression, or vector or matrix of symbolic scalar variables.
Output Arguments
X — Solution
symbolic number | symbolic scalar variable | symbolic matrix variable | symbolic function | symbolic
matrix function | symbolic expression | symbolic vector | symbolic matrix
Solution, returned as a symbolic number, scalar variable, matrix variable, function, matrix function,
expression, or vector or matrix of symbolic scalar variables.
Tips
• Matrix computations involving many symbolic variables can be slow. To increase the
computational speed, reduce the number of symbolic variables by substituting the given values for
some variables.
• When dividing by zero, mrdivide considers the numerator’s sign and returns Inf or -Inf
accordingly.
syms x
[sym(1)/sym(0), sym(-1)/sym(0), x/sym(0)]
ans =
[ Inf, -Inf, Inf*x]
7-1084
mrdivide, /
Version History
Introduced before R2006a
See Also
ctranspose | ldivide | minus | mldivide | mpower | mtimes | plus | power | rdivide | times |
transpose
7-1085
7 Functions
mtimes, *
Symbolic matrix multiplication
Syntax
A*B
mtimes(A,B)
Description
A*B is the matrix product of A and B. If A is an m-by-p and B is a p-by-n matrix, then the result is an m-
by-n matrix C defined as
p
C i, j = ∑ A i, k B k, j
k=1
For nonscalar A and B, the number of columns of A must equal the number of rows of B. Matrix
multiplication is not universally commutative for nonscalar inputs. That is, typically A*B is not equal
to B*A. If at least one input is scalar, then A*B is equivalent to A.*B and is commutative.
Examples
Multiply Two Vectors
syms x
A = [x, 2*x^2, 3*x^3, 4*x^4]
B = [1/x; 2/x^2; 3/x^3; 4/x^4]
A =
[ x, 2*x^2, 3*x^3, 4*x^4]
B =
1/x
2/x^2
3/x^3
4/x^4
A*B
ans =
30
7-1086
mtimes, *
A = sym('a%d%d', [4 3])
B = sym('b%d%d', [3 2])
A =
[ a11, a12, a13]
[ a21, a22, a23]
[ a31, a32, a33]
[ a41, a42, a43]
B =
[ b11, b12]
[ b21, b22]
[ b31, b32]
Multiply A by B.
A*B
ans =
[ a11*b11 + a12*b21 + a13*b31, a11*b12 + a12*b22 + a13*b32]
[ a21*b11 + a22*b21 + a23*b31, a21*b12 + a22*b22 + a23*b32]
[ a31*b11 + a32*b21 + a33*b31, a31*b12 + a32*b22 + a33*b32]
[ a41*b11 + a42*b21 + a43*b31, a41*b12 + a42*b22 + a43*b32]
H = sym(hilb(4))
H =
[ 1, 1/2, 1/3, 1/4]
[ 1/2, 1/3, 1/4, 1/5]
[ 1/3, 1/4, 1/5, 1/6]
[ 1/4, 1/5, 1/6, 1/7]
Multiply H by eπ.
C = H*exp(sym(pi))
C =
[ exp(pi), exp(pi)/2, exp(pi)/3, exp(pi)/4]
[ exp(pi)/2, exp(pi)/3, exp(pi)/4, exp(pi)/5]
[ exp(pi)/3, exp(pi)/4, exp(pi)/5, exp(pi)/6]
[ exp(pi)/4, exp(pi)/5, exp(pi)/6, exp(pi)/7]
Use vpa and digits to approximate symbolic results with the required number of digits. For
example, approximate it with five-digit accuracy.
old = digits(5);
vpa(C)
digits(old)
ans =
[ 23.141, 11.57, 7.7136, 5.7852]
[ 11.57, 7.7136, 5.7852, 4.6281]
[ 7.7136, 5.7852, 4.6281, 3.8568]
[ 5.7852, 4.6281, 3.8568, 3.3058]
7-1087
7 Functions
Input Arguments
A — Input
symbolic number | symbolic scalar variable | symbolic matrix variable | symbolic function | symbolic
matrix function | symbolic expression | symbolic vector | symbolic matrix
Input, specified as a symbolic number, scalar variable, matrix variable, function, matrix function,
expression, or vector or matrix of symbolic scalar variables. Inputs A and B must be the same size
unless one is a scalar. A scalar value expands into an array of the same size as the other input.
B — Input
symbolic number | symbolic scalar variable | symbolic matrix variable | symbolic function | symbolic
matrix function | symbolic expression | symbolic vector | symbolic matrix
Input, specified as a symbolic number, scalar variable, matrix variable, function, matrix function,
expression, or vector or matrix of symbolic scalar variables. Inputs A and B must be the same size
unless one is a scalar. A scalar value expands into an array of the same size as the other input.
Version History
Introduced before R2006a
See Also
ctranspose | ldivide | minus | mldivide | mpower | mrdivide | plus | power | rdivide |
times | transpose
7-1088
mupad
mupad
(Removed) Start MuPAD notebook
Note
MuPAD® notebook has been removed. Use MATLAB® Live Editor instead.
To convert a MuPAD notebook file to a MATLAB live script file, see convertMuPADNotebook.
MATLAB live scripts support most MuPAD functionality, although there are some differences. For
more information, see “Convert MuPAD Notebooks to MATLAB Live Scripts”.
Syntax
mupad filename
Description
mupad filename opens the MuPAD notebook named filename. The file name must be a full path
unless the file is in the current folder.
Examples
When you open an existing MuPAD notebook, you can choose to convert the notebook to MATLAB live
script instead.
Input Arguments
filename — Name of file
character vector
Name of file, specified as a character vector. The extension of filename must be .mn.
7-1089
7 Functions
Example: 'C:\MuPAD_Notebooks\myFile.mn'
Version History
Introduced in R2008b
The mupad command errors. MuPAD notebook has been removed. Use MATLAB live scripts instead.
To convert a MuPAD notebook file to a MATLAB live script file, see convertMuPADNotebook.
MATLAB live scripts support most MuPAD functionality, although there are some differences. For
more information, see “Convert MuPAD Notebooks to MATLAB Live Scripts” on page 6-3.
See Also
convertMuPADNotebook
Topics
“Convert MuPAD Notebooks to MATLAB Live Scripts” on page 6-3
“Troubleshoot MuPAD to MATLAB Translation Errors” on page 6-8
“Troubleshoot MuPAD to MATLAB Translation Warnings” on page 6-15
7-1090
nchoosek
nchoosek
Binomial coefficient
Syntax
b = nchoosek(n,k)
C = nchoosek(v,k)
Description
b = nchoosek(n,k) returns the binomial coefficient of n and k, defined as n!/(k!(n - k)!).
This is the number of combinations of n items taken k at a time.
C = nchoosek(v,k) returns a matrix containing all possible combinations of the elements of vector
v taken k at a time. Matrix C has k columns and n!/(k!(n - k)!) rows, where n is length(v). In
this syntax, k must be a nonnegative integer.
Examples
Binomial Coefficients for Numeric and Symbolic Arguments
syms n
[nchoosek(n, n), nchoosek(n, n + 1), nchoosek(n, n - 1)]
ans =
[ 1, 0, n]
If one or both parameters are negative numbers, convert these numbers to symbolic objects.
ans =
[ -1, 28, 1]
If one or both parameters are complex numbers, convert these numbers to symbolic objects.
ans =
[ 1/2 + 1i/6, 1, 0]
Many functions, such as diff and expand, can handle expressions containing nchoosek.
syms n k
diff(nchoosek(n, 2))
7-1091
7 Functions
ans =
-(psi(n - 1) - psi(n + 1))*nchoosek(n, 2)
expand(nchoosek(n, k))
ans =
-(n*gamma(n))/(k^2*gamma(k)*gamma(n - k) - k*n*gamma(k)*gamma(n - k))
Pascal Triangle
m = 5;
for n = 0:m
C = sym([]);
for k = 0:n
C = horzcat(C, nchoosek(n, k));
end
disp(C)
end
1
[ 1, 1]
[ 1, 2, 1]
[ 1, 3, 3, 1]
[ 1, 4, 6, 4, 1]
[ 1, 5, 10, 10, 5, 1]
Find all combinations of elements of a 1-by-5 symbolic row vector taken three and four at a time.
Create a 1-by-5 symbolic vector with the elements x1, x2, x3, x4, and x5.
v =
[ x1, x2, x3, x4, x5]
C = nchoosek(v, 3)
C =
[ x1, x2, x3]
[ x1, x2, x4]
[ x1, x3, x4]
[ x2, x3, x4]
[ x1, x2, x5]
[ x1, x3, x5]
[ x2, x3, x5]
[ x1, x4, x5]
[ x2, x4, x5]
[ x3, x4, x5]
C = nchoosek(v, 4)
7-1092
nchoosek
C =
[ x1, x2, x3, x4]
[ x1, x2, x3, x5]
[ x1, x2, x4, x5]
[ x1, x3, x4, x5]
[ x2, x3, x4, x5]
Input Arguments
n — Number of possible choices
symbolic number | symbolic variable | symbolic expression | symbolic function
Number of selected choices, specified as a symbolic number, variable, expression, or function. If the
first argument is a symbolic vector v, then k must be a nonnegative integer.
Set of all choices, specified as a vector of symbolic numbers, variables, expressions, or functions.
Output Arguments
b — Binomial coefficient
nonnegative scalar value
C — All combinations of v
matrix
More About
Binomial Coefficient
n n!
=
k k! n − k !
For complex numbers, the binomial coefficient is defined via the gamma function:
n Γ n+1
=
k Γ k+1 Γ n−k+1
7-1093
7 Functions
Tips
• Calling nchoosek for numbers that are not symbolic objects invokes the MATLAB nchoosek
function.
• If one or both parameters are complex or negative numbers, convert these numbers to symbolic
objects using sym, and then call nchoosek for those symbolic objects.
Algorithms
If k < 0 or n – k < 0, nchoosek(n,k) returns 0.
If one or both arguments are complex, nchoosek uses the formula representing the binomial
coefficient via the gamma function.
Version History
Introduced in R2012a
See Also
beta | gamma | factorial | psi
7-1094
ne
ne
Define inequality
Syntax
A ~= B
ne(A,B)
Description
A ~= B creates a symbolic inequality.
ne(A,B) is equivalent to A ~= B.
Examples
Set and Use Assumption Using Not Equal
Use assume and the relational operator ~= to set the assumption that x does not equal to 5:
syms x
assume(x ~= 5)
Solve this equation. The solver takes into account the assumption on variable x, and therefore returns
only one solution.
solve((x - 5)*(x - 6) == 0, x)
ans =
6
Input Arguments
A — Input
number | vector | matrix | array | symbolic number | symbolic scalar variable | symbolic matrix
variable | symbolic array | symbolic function | symbolic matrix function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, scalar variable, matrix
variable, array, function, matrix function, or expression.
B — Input
number | vector | matrix | array | symbolic number | symbolic scalar variable | symbolic matrix
variable | symbolic array | symbolic function | symbolic matrix function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, scalar variable, matrix
variable, array, function, matrix function, or expression.
7-1095
7 Functions
Tips
• Calling ~= or ne for non-symbolic A and B invokes the MATLAB ne function. This function returns
a logical array with elements set to logical 1 (true) where A is not equal to B; otherwise, it
returns logical 0 (false).
• If both A and B are arrays, then these arrays must have the same dimensions. A ~= B returns an
array of inequalities A(i,j,...) ~= B(i,j,...)
• If one input is scalar and the other an array, then the scalar input is expanded into an array of the
same dimensions as the other array. In other words, if A is a variable (for example, x), and B is an
m-by-n matrix, then A is expanded into m-by-n matrix of elements, each set to x.
Alternatives
You can also define inequality using eq (or its shortcut ==) and the logical negation not (or ~). Thus,
A ~= B is equivalent to ~(A == B).
Version History
Introduced in R2012a
See Also
eq | ge | gt | isAlways | le | lt
Topics
“Use Assumptions on Symbolic Variables” on page 1-41
7-1096
newUnit
newUnit
Define new unit
Syntax
c = newUnit(name,definition)
Description
c = newUnit(name,definition) defines the new unit name using the expression definition.
The definition must be in terms of existing symbolic units. You cannot redefine a predefined unit or
any of its alternate names.
Examples
Define New Unit and Rewrite Unit
Load the collection of symbolic units by using symunit. Find information on the predefined unit
u.c_0 for the speed of light.
u = symunit;
unitInfo(u.c_0)
Show that the exact value of the speed of light in SI is 299792458 metres per second.
c = unitConvert(u.c_0,'SI')
c =
299792458*([m]/[s])
Define the new unit speedOfLightApprox for the approximate value of the speed of light as 3e8
meters per second.
u = symunit;
c = newUnit('speedOfLightApprox',3e8*u.m/u.s)
c =
[speedOfLightApprox]
syms mass
m = mass*u.kg;
E = m*c^2
E =
mass*[kg]*[speedOfLightApprox]^2
7-1097
7 Functions
E = rewrite(E,u.m/u.s)
E =
90000000000000000*mass*(([kg]*[m]^2)/[s]^2)
Since the standard unit of energy is the joule, rewrite E in terms of Joule.
E = rewrite(E,u.Joule)
E =
90000000000000000*mass*[J]
Input Arguments
name — Name of new unit
character vector | string
Name of the new unit, specified as a character vector or string. You cannot redefine a predefined unit
or any of its alternate names.
Definition of the new unit, specified as a symbolic expression of units. The new unit must be defined
in terms of existing symbolic units. For example, newUnit('workday',8*u.hour), where u =
symunit, defines workday as a unit representing 8 hours.
Version History
Introduced in R2017a
See Also
checkUnits | isUnit | removeUnit | separateUnits | symunit | str2symunit | symunit2str |
unitConversionFactor
Topics
“Units of Measurement Tutorial” on page 2-47
“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)
7-1098
newUnitSystem
newUnitSystem
Define unit system
Syntax
newUnitSystem(name,baseUnits)
newUnitSystem(name,baseUnits,derivedUnits)
Description
newUnitSystem(name,baseUnits) defines a new “Unit System” on page 7-1101 with the name
name and the base units baseUnits. Now, you can convert units into the new unit system by using
rewrite. By default, available unit systems include SI, CGS, and US. For all unit systems, see “Unit
Systems List” on page 2-71.
Examples
A unit system is a collection of units to express quantities. The easiest way to define a new unit
system is to modify a default unit system, such as SI, CGS, or US.
Modify SI to use kilometer for length and hour for time by getting the base units using baseunits
and modifying them by using subs.
u = symunit;
SIUnits = baseUnits('SI')
SIUnits =
[ [kg], [s], [m], [A], [cd], [mol], [K]]
newUnits =
[ [kg], [h], [km], [A], [cd], [mol], [K]]
Note Do not define a variable called baseUnits because the variable will prevent access to the
baseUnits function.
Define the new unit system SI_km_hr using the new base units.
newUnitSystem('SI_km_hr',newUnits)
ans =
"SI_km_hr"
7-1099
7 Functions
Rewrite 5 meter/second to the SI_km_hr unit system. As expected, the result is in terms of
kilometers and hours.
rewrite(5*u.m/u.s,'SI_km_hr')
ans =
18*([km]/[h])
Specify a new unit system by specifying the base and derived units directly. A unit system has up to 7
base units. For details, see “Unit System” on page 7-1101.
Define a new unit system with these base units: gram, hour, meter, ampere, candela, mol, and celsius.
Specify these derived units: kilowatt, newton, and volt.
u = symunit;
sysName = 'myUnitSystem';
bunits = [u.g u.hr u.m u.A u.cd u.mol u.Celsius];
dunits = [u.kW u.N u.V];
newUnitSystem(sysName,bunits,dunits)
ans =
"myUnitSystem"
Rewrite 2000 Watts to the new system. By default, rewrite uses base units, which can be hard to
read.
rewrite(2000*u.W,sysName)
ans =
93312000000000000*(([g]*[m]^2)/[h]^3)
Instead, for readability, rewrite 2000 Watts to derived units of myUnitSystem by specifying
'Derived' as the third argument. Converting to the derived units of a unit system attempts to select
convenient units. The result uses the derived unit, kilowatt, instead of base units. For more
information, see “Unit Conversions and Unit Systems” on page 2-53.
rewrite(2000*u.W,sysName,'Derived')
ans =
2*[kW]
Input Arguments
name — Name of unit system
string | character vector
7-1100
newUnitSystem
Base units of unit system, specified as a vector of symbolic units. The base units must be independent
in terms of the dimensions mass, time, length, electric current, luminous intensity, amount of
substance, and temperature. Thus, in a unit system, there are up to 7 base units.
Derived units of unit system, specified as a vector of symbolic units. Derived units are optional and
added for convenience of representation.
More About
Unit System
A unit system is a collection of base units and derived units that follows these rules:
• 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.
• 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').
Version History
Introduced in R2017b
See Also
baseUnits | derivedUnits | newUnit | removeUnitSystem | rewrite | symunit | unitSystems
Topics
“Units of Measurement Tutorial” on page 2-47
“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)
7-1101
7 Functions
nextprime
Next prime number
Syntax
nextprime(n)
Description
nextprime(n) returns the next prime number greater than or equal to n. If n is a vector or matrix,
then nextprime acts element-wise on n.
Examples
Find Next Prime Number
nextprime(100)
ans =
101
Find the next prime numbers greater than 1000, 10000, and 100000 by specifying the input as a
vector.
ans =
1009 10007 100003
When finding large prime numbers, return exact symbolic integers by using symbolic input. Further,
if your input has 15 or more digits, then use quotation marks and wrap the number in sym to
represent the number accurately. For more information, see “Numeric to Symbolic Conversion” on
page 2-29.
nextprime(10^sym(18))
ans =
1000000000000000003
nextprime(sym('823572345728582545'))
ans =
823572345728582623
7-1102
nextprime
Input Arguments
n — Input
number | vector | matrix | array | symbolic number | symbolic array
Version History
Introduced in R2016b
See Also
isprime | nthprime | prevprime | primes
7-1103
7 Functions
norm
Norm of symbolic vector or matrix
Syntax
n = norm(v)
n = norm(v,p)
n = norm(A)
n = norm(A,P)
n = norm(X,"fro")
Description
n = norm(v) returns the 2-norm of symbolic vector v.
n = norm(A) returns the 2-norm of symbolic matrix A. Because symbolic variables are assumed to
be complex by default, the norm can contain unresolved calls to conj and abs.
Examples
A =
53 13 23
−
360 90 360
11 1 19
−
180 45 180
7 17 37
− −
360 90 360
norm2 = norm(A)
norm2 =
3
6
7-1104
norm
norm2_vpa = 0.28867513459481288225
Compute the norm of [x y] and simplify the result. Because symbolic scalar variables are assumed
to be complex by default, the calls to abs do not simplify.
syms x y
n = simplify(norm([x y]))
2 2
n = x + y
Assume x and y are real, and repeat the calculation. Now, the result is simplified.
assume([x y],"real")
n = simplify(norm([x y]))
n = x2 + y2
Remove assumptions on x for further calculations. For details, see “Use Assumptions on Symbolic
Variables” on page 1-41.
assume(x,"clear")
Compute the 1-norm, Frobenius norm, and infinity norm of the inverse of the 3-by-3 magic square A.
A = inv(sym(magic(3)))
A =
53 13 23
−
360 90 360
11 1 19
−
180 45 180
7 17 37
− −
360 90 360
norm1 = norm(A,1)
norm1 =
16
45
normf = norm(A,"fro")
normf =
391
60
normi = norm(A,Inf)
normi =
16
45
7-1105
7 Functions
norm1_vpa = vpa(norm1,20)
norm1_vpa = 0.35555555555555555556
normf_vpa = vpa(normf,20)
normf_vpa = 0.32956199888808647519
normi_vpa = vpa(normi,20)
normi_vpa = 0.35555555555555555556
Compute the 1-norm, 2-norm, and 3-norm of the column vector V = [Vx; Vy; Vz].
syms Vx Vy Vz
V = [Vx; Vy; Vz];
norm1 = norm(V,1)
norm1 = Vx + Vy + Vz
norm2 = norm(V)
2 2 2
norm2 = Vx + Vy + Vz
norm3 = norm(V,3)
3 3 3 1/3
norm3 = Vx + Vy + Vz
Compute the infinity norm, negative infinity norm, and Frobenius norm of V.
normi = norm(V,Inf)
normi = max Vx , Vy , Vz
normni = norm(V,-Inf)
normni = min Vx , Vy , Vz
normf = norm(V,"fro")
2 2 2
normf = Vx + Vy + Vz
Input Arguments
v — Input vector
vector of symbolic scalar variables | symbolic matrix variable | symbolic function | symbolic matrix
function
Input vector, specified as a vector of symbolic scalar variables, symbolic matrix variable, function, or
matrix function that represents a vector.
7-1106
norm
p — Input
2 (default) | 1 | positive integer scalar | Inf | -Inf | "fro"
A — Input matrix
matrix of symbolic scalar variables | symbolic matrix variable | symbolic function | symbolic matrix
function
Input matrix, specified as a matrix of symbolic scalar variables, symbolic matrix variable, function, or
matrix function that represents a matrix.
P — Input
2 (default) | 1 | Inf | "fro"
X — Input array
multidimensional array of symbolic scalar variables
More About
1-Norm of a Matrix
2-Norm of a Matrix
H
A 2 = max eigenvalue of A A
7-1107
7 Functions
n n n
A ∞ = max ∑ A1 j , ∑ A2 j , …, ∑ Am j
j=1 j=1 j=1
m n
2
A F = ∑ ∑ Ai j
i=1 j=1
l m n
2
X F = ∑ ∑ ∑ Xi jk
i=1 j=1 k=1
P-Norm of a Vector
n 1P
P
V P= ∑ Vi
i=1
n
2
V F = ∑ Vi
i=1
Tips
• Calling norm for a numeric matrix that is not a symbolic object invokes the MATLAB norm
function.
Version History
Introduced in R2012b
7-1108
norm
The norm function accepts a symbolic multidimensional array as its input argument. Use the syntax
norm(X,"fro") to return the Frobenius norm of a symbolic array X.
See Also
cond | equationsToMatrix | inv | linsolve | rank
7-1109
7 Functions
not
Logical NOT for symbolic expressions
Syntax
~A
not(A)
Description
~A represents the logical NOT. ~A is true when A is false and false when A is true.
Examples
syms x y
cond = ~(x > y);
assume(cond)
assumptions
ans =
~y < x
Specify a range for x by creating a condition using the logical operators ~ and &.
syms x
range = abs(x) < 1 & ~(abs(x)<1/3);
Return the conditions at 0 and 2/3 by substituting for x using subs. The subs function does not
evaluate the conditions automatically.
x1 = subs(range,x,0)
x2 = subs(range,x,2/3)
x1 =
0 < 1 & ~0 < 1/3
x2 =
2/3 < 1 & ~2/3 < 1/3
7-1110
not
isAlways(x1)
isAlways(x2)
ans =
logical
0
ans =
logical
1
Input Arguments
A — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
Tips
• If you call simplify for a logical expression containing symbolic subexpressions, you can get the
symbolic constants symtrue and symfalse. These two constants are not the same as logical 1
(true) and logical 0 (false). To convert symbolic symtrue and symfalse to logical values, use
logical.
Version History
Introduced in R2012a
See Also
all | and | any | isAlways | or | piecewise | xor
7-1111
7 Functions
nthprime
nth prime number
Syntax
nthprime(n)
Description
nthprime(n) returns the nth prime number. nthprime acts element-wise on array inputs.
Examples
nthprime(223)
ans =
1409
For large prime numbers, return exact symbolic integers by using symbolic input.
n = sym(223222222);
nthprime(n)
ans =
4738278383
ans =
29 541 7919
Generate a random prime number between the 100,000th and 200,000th prime numbers.
7-1112
nthprime
ans =
2476423
Input Arguments
n — Input
number | vector | matrix | array | symbolic number | symbolic array
Input, specified as a number, vector, matrix, array, or a symbolic number or array. n must be a
positive integer.
Version History
Introduced in R2018a
See Also
nextprime | prevprime
7-1113
7 Functions
nthroot
Nth root of symbolic numbers
Syntax
y = nthroot(x,n)
Description
y = nthroot(x,n) returns the nth root of x with the phase angle closest to the phase of x. The
output y has symbolic data type if any input argument is symbolic. The variables satisfy y.^n = x.
Examples
y =
1
−
3
ans = −27
1/4
y = 1+ i
ans = 1 + i
7-1114
nthroot
x = sym([-27,-8,-4
27,64,-12])
x =
−27 −8 −4
27 64 −12
n = sym([3,3,4
3,2,-2])
n =
33 4
3 2 −2
y = nthroot(x,n)
y =
3/4 1/4
−3 −2 −1 4
12 i
3 8 −
12
ans =
−27 −8 −4
27 64 −12
y =
1
−
27
syms x n
y = diff(nthroot(x,n),x)
y =
n
x
nx
Input Arguments
x — Input array for taking root
symbolic array | numeric array
Input array for taking root, specified as a symbolic or numeric array. When taking the root, the
function acts element-wise.
If both x and n are nonscalar arrays, they must have the same size. If any element of x or n is
symbolic and some elements are numeric, nthroot converts numeric arguments to symbolic before
processing.
7-1115
7 Functions
Example: [sym(-8),sym(8);sym(-27),sym(27)]
Input array for order of root, specified as a symbolic array or real array.
• If an element of x is not real and positive, meaning it is either negative or has a nonzero imaginary
part, then the corresponding element of n must be a nonzero integer.
• If an element of x is real and positive, then the corresponding element of n can have any nonzero
real value.
If both x and n are nonscalar arrays, they must have the same size. If any element of x or n are
symbolic and some elements are numeric, nthroot converts numeric arguments to symbolic before
processing.
Example: sym(-3)
Version History
Introduced in R2018b
See Also
power
7-1116
null
null
Form basis for null space of matrix
Syntax
Z = null(A)
Description
Z = null(A) returns a list of vectors that form the basis for the null space of a matrix A. The
product A*Z is zero. size(Z, 2) is the nullity of A. If A has full rank, Z is empty.
Examples
Find the basis for the null space and the nullity of the magic square of symbolic numbers. Verify that
A*Z is zero.
A = sym(magic(4));
Z = null(A)
nullityOfA = size(Z, 2)
A*Z
Z =
-1
-3
3
1
nullityOfA =
1
ans =
0
0
0
0
Find the basis for the null space of the matrix B that has full rank.
B = sym(hilb(3))
Z = null(B)
B =
[ 1, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
7-1117
7 Functions
Z =
Empty sym: 1-by-0
Input Arguments
A — Input
numeric matrix | symbolic matrix
Version History
Introduced before R2006a
See Also
rank | rref | svd
7-1118
numden
numden
Extract numerator and denominator
Syntax
[N,D] = numden(A)
Description
[N,D] = numden(A) converts A to a rational form where the numerator and denominator are
relatively prime polynomials with integer coefficients. The function returns the numerator and
denominator of the rational form of an expression.
If A is a symbolic or a numeric matrix, then N is the symbolic matrix of numerators, and D is the
symbolic matrix of denominators. Both N and D are matrices of the same size as A.
Examples
Numerators and Denominators of Symbolic Numbers
n =
4
d =
5
n =
x^2 + y^2
d =
x*y
n =
[ a, 1]
[ 1, 1]
7-1119
7 Functions
d =
[ b, b]
[ a, a*b]
Input Arguments
A — Input
symbolic number | symbolic expression | symbolic function | symbolic vector | symbolic matrix
Output Arguments
N — Numerator
symbolic number | symbolic expression | symbolic function | symbolic vector | symbolic matrix
D — Denominator
symbolic number | symbolic expression | symbolic function | symbolic vector | symbolic matrix
Version History
Introduced before R2006a
See Also
divisors | partfrac | simplifyFraction
Topics
“Extract Numerators and Denominators of Rational Expressions” on page 3-127
7-1120
odeFunction
odeFunction
Convert symbolic expressions to function handle for ODE solvers
Syntax
f = odeFunction(expr,vars)
f = odeFunction(expr,vars,p1,...,pN)
f = odeFunction( ___ ,Name,Value)
Description
f = odeFunction(expr,vars) converts a system of symbolic algebraic expressions to a MATLAB
function handle. This function handle can be used as input to the numerical MATLAB ODE solvers,
except for ode15i. The argument vars specifies the state variables of the system.
Examples
Convert a system of symbolic differential algebraic equations to a function handle suitable for the
MATLAB ODE solvers. Then solve the system by using the ode15s solver.
syms y(t);
eqn = diff(y(t),t,2) == (1-y(t)^2)*diff(y(t),t) - y(t);
[eqs,vars] = reduceDifferentialOrder(eqn,y(t))
eqs =
diff(Dyt(t), t) + y(t) + Dyt(t)*(y(t)^2 - 1)
Dyt(t) - diff(y(t), t)
vars =
y(t)
Dyt(t)
Set initial conditions for y(t) and its derivative Dy(t) to 2 and 0 respectively.
initConditions = [2 0];
7-1121
7 Functions
Find the mass matrix M of the system and the right sides of the equations F.
[M,F] = massMatrixForm(eqs,vars)
M =
[ 0, 1]
[ -1, 0]
F =
- y(t) - Dyt(t)*(y(t)^2 - 1)
-Dyt(t)
f = M\F
f =
Dyt(t)
- Dyt(t)*y(t)^2 - y(t) + Dyt(t)
Convert f to a MATLAB function handle by using odeFunction. The resulting function handle is
input to the MATLAB ODE solver ode15s.
odefun = odeFunction(f,vars);
ode15s(odefun, [0 10], initConditions)
7-1122
odeFunction
Convert a system of symbolic differential equations containing both state variables and symbolic
parameters to a function handle suitable for the MATLAB ODE solvers.
Create the system of differential algebraic equations. Here, the symbolic functions x1(t) and x2(t)
represent the state variables of the system. The system also contains constant symbolic parameters a,
b, and the parameter function r(t). These parameters do not represent state variables. Specify the
equations and state variables as two symbolic vectors: equations as a vector of symbolic equations,
and variables as a vector of symbolic function calls.
syms x1(t) x2(t) a b r(t)
eqs = [diff(x1(t),t) == a*x1(t) + b*x2(t)^2,...
x1(t)^2 + x2(t)^2 == r(t)^2];
vars = [x1(t) x2(t)];
Find the mass matrix M and vector of the right side F for this system. M and F refer to the form
M t, x t ẋ t = F t, x t ..
[M,F] = massMatrixForm(eqs,vars)
M =
[ 1, 0]
[ 0, 0]
F =
b*x2(t)^2 + a*x1(t)
r(t)^2 - x1(t)^2 - x2(t)^2
Use odeFunction to generate MATLAB function handles from M and F. The function handle F
contains symbolic parameters.
M = odeFunction(M,vars)
F = odeFunction(F,vars,a,b,r(t))
M =
function_handle with value:
@(t,in2)reshape([1.0,0.0,0.0,0.0],[2,2])
F =
function_handle with value:
@(t,in2,param1,param2,param3)[param1.*in2(1,:)+...
param2.*in2(2,:).^2;param3.^2-in2(1,:).^2-in2(2,:).^2]
7-1123
7 Functions
Create an option set that contains the mass matrix M of the system and vector yp0 of initial conditions
for the derivatives.
opt = odeset('mass',M,'InitialSlope',yp0);
Write the generated function handles to files by using the File option. When writing to files,
odeFunction optimizes the code using intermediate variables named t0, t1, .… Include comments
the files by specifying the Comments option.
Define the system of differential equations. Find the mass matrix M and the right side F.
Write the MATLAB code for M and F to the files myfileM and myfileF. odeFunction overwrites
existing files. Include the comment Version: 1.1 in the files You can open and edit the output files.
7-1124
odeFunction
M = odeFunction(M,vars,'File','myfileM','Comments','Version: 1.1');
% This function was generated by the Symbolic Math Toolbox version 7.3.
% 01-Jan-2017 00:00:00
%Version: 1.1
expr = reshape([1.0,0.0,2.0,0.0],[2, 2]);
F = odeFunction(F,vars,'File','myfileF','Comments','Version: 1.1');
% This function was generated by the Symbolic Math Toolbox version 7.3.
% 01-Jan-2017 00:00:00
%Version: 1.1
x = in2(1,:);
y = in2(2,:);
expr = [y.*(1.0./1.0e1);-x+y+cos(t)-t.*sin(x).*(1.0./5.0)];
Specify consistent initial values for x(t) and y(t) and their first derivatives.
Create an option set that contains the mass matrix M, initial conditions xyp0, and numerical
tolerances for the numerical search.
7-1125
7 Functions
Sparse Matrices
Use the name-value pair argument 'Sparse',true when converting sparse symbolic matrices to
MATLAB function handles.
Create the system of differential algebraic equations. Here, the symbolic functions x1(t) and x2(t)
represent the state variables of the system. Specify the equations and state variables as two symbolic
vectors: equations as a vector of symbolic equations, and variables as a vector of symbolic function
calls.
a = -0.6;
b = -0.1;
r = @(t) cos(t)/(1 + t^2);
Find the mass matrix M and vector of the right side F for this system. M and F refer to the form
M t, x t ẋ t = F t, x t ..
[M,F] = massMatrixForm(eqs,vars)
7-1126
odeFunction
M =
[ 1, 0]
[ 0, 0]
F =
- (3*x1(t))/5 - x2(t)^2/10
cos(t)^2/(t^2 + 1)^2 - x1(t)^2 - x2(t)^2
Generate MATLAB function handles from M and F. Because most of the elements of the mass matrix M
are zeros, use the Sparse argument when converting M.
M = odeFunction(M,vars,'Sparse',true)
F = odeFunction(F,vars)
M =
function_handle with value:
@(t,in2)sparse([1],[1],[1.0],2,2)
F =
function_handle with value:
@(t,in2)[in2(1,:).*(-3.0./5.0)-in2(2,:).^2./1.0e+1;...
cos(t).^2.*1.0./(t.^2+1.0).^2-in2(1,:).^2-in2(2,:).^2]
t0 = 0;
y0 = [-r(t0)*sin(0.1); r(t0)*cos(0.1)];
yp0= [a*y0(1) + b*y0(2)^2; 1.234];
Create an option set that contains the mass matrix M of the system and vector yp0 of initial conditions
for the derivatives.
7-1127
7 Functions
Input Arguments
expr — System of algebraic expressions
vector of symbolic expressions
State variables, specified as a vector of symbolic functions or function calls, such as x(t).
Example: [x(t),y(t)] or [x(t);y(t)]
Parameters of the system, specified as symbolic variables, functions, or function calls, such as f(t).
You can also specify parameters of the system as a vector or matrix of symbolic variables, functions,
or function calls. If expr contains symbolic parameters other than the variables specified in vars,
you must specify these additional parameters as p1,...,pN.
7-1128
odeFunction
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: odeFunction(expr,vars,'File','myfile')
Comments to include in the file header, specified as a character vector, cell array of character
vectors, or string vector.
Path to the file containing generated code, specified as a character vector. The generated file accepts
arguments of type double, and can be used without Symbolic Math Toolbox. If the value is empty,
odeFunction generates an anonymous function. If the character vector does not end in .m, the
function appends .m.
By default, odeFunction with the File argument generates a file containing optimized code.
Optimized means intermediate variables are automatically generated to simplify or speed up the
code. MATLAB generates intermediate variables as a lowercase letter t followed by an automatically
generated number, for example t32. To disable code optimization, use the Optimize argument.
Flag preventing optimization of code written to a function file, specified as false or true.
By default, odeFunction with the File argument generates a file containing optimized code.
Optimized means intermediate variables are automatically generated to simplify or speed up the
code. MATLAB generates intermediate variables as a lowercase letter t followed by an automatically
generated number, for example t32.
odeFunction without the File argument (or with a file path specified by an empty character vector)
creates a function handle. In this case, the code is not optimized. If you try to enforce code
optimization by setting Optimize to true, then odeFunction throws an error.
Sparse — Flag that switches between sparse and dense matrix generation
false (default) | true
Flag that switches between sparse and dense matrix generation, specified as true or false. When
you specify 'Sparse',true, the generated function represents symbolic matrices by sparse numeric
matrices. Use 'Sparse',true when you convert symbolic matrices containing many zero elements.
Often, operations on sparse matrices are more efficient than the same operations on dense matrices.
See “Sparse Matrices” on page 7-1126.
7-1129
7 Functions
Output Arguments
f — Function handle that is input to numerical MATLAB ODE solvers, except ode15i
MATLAB function handle
Function handle that can serve as input argument to all numerical MATLAB ODE solvers, except for
ode15i, returned as a MATLAB function handle.
odeFunction returns a function handle suitable for the ODE solvers such as ode45, ode15s,
ode23t, and others. The only ODE solver that does not accept this function handle is the solver for
fully implicit differential equations, ode15i. To convert the system of equations to a function handle
suitable for ode15i, use daeFunction.
Version History
Introduced in R2015a
See Also
findDecoupledBlocks | daeFunction | decic | incidenceMatrix | isLowIndexDAE |
massMatrixForm | matlabFunction | ode15i | ode15s | ode45 | ode23t | reduceDAEIndex |
reduceDAEToODE | reduceDifferentialOrder | reduceRedundancies
Topics
“Solve DAEs Using Mass Matrix Solvers” on page 3-77
7-1130
odeToVectorField
odeToVectorField
Reduce order of differential equations to first-order
Syntax
V = odeToVectorField(eqn1,...,eqnN)
[V,S] = odeToVectorField(eqn1,...,eqnN)
Description
V = odeToVectorField(eqn1,...,eqnN) converts higher-order differential equations
eqn1,...,eqnN to a system of first-order differential equations, returned as a symbolic vector.
Examples
2
d y
2
+ y2t = 3t .
dt
V =
Y2
3 t − t Y 12
The elements of V represent the system of first-order differential equations, where V[i] = Y i′ and
Y 1 = y. Here, the output V represents these equations:
dY 1
= Y2
dt
dY 2
= 3t − tY 12 .
dt
For details on the relation between the input and output, see “Algorithms” on page 7-1134.
7-1131
7 Functions
When reducing the order of differential equations, return the substitutions that odeToVectorField
makes by specifying a second output argument.
V =
Y2
Y1 + Y3
Y3 − Y1
S =
f
Df
g
The elements of V represent the system of first-order differential equations, where V[i] = Y i′. The
output S shows the substitutions being made, S[1] = Y 1 = f , S[2] = Y 2 = diff(f), and S[3] = Y 3 = g.
Solve a higher-order differential equation numerically by reducing the order of the equation,
generating a MATLAB® function handle, and then finding the numerical solution using the ode45
function.
2
d y dy
= 1 − y2 − y.
dt2 dt
syms y(t)
eqn = diff(y,2) == (1-y^2)*diff(y)-y;
V = odeToVectorField(eqn)
V =
Y2
2
− Y1 − 1 Y2 − Y1
M = matlabFunction(V,'vars',{'t','Y'})
7-1132
odeToVectorField
Specify the solution interval to be [0 20] and the initial conditions to be y′(0) = 2 and y′′(0) = 0.
Solve the system of first-order differential equations by using ode45.
interval = [0 20];
yInit = [2 0];
ySol = ode45(M,interval,yInit);
Next, plot the solution y(t) within the interval t = [0 20]. Generate the values of t by using
linspace. Evaluate the solution for y(t), which is the first index in ySol, by calling the deval
function with an index of 1. Plot the solution using plot.
tValues = linspace(0,20,100);
yValues = deval(ySol,tValues,1);
plot(tValues,yValues)
Convert the second-order differential equation y′′(x) = x with the initial condition y(0) = a to a first-
order system.
syms y(x) a
eqn = diff(y,x,2) == x;
cond = y(0) == a;
V = odeToVectorField(eqn,cond)
7-1133
7 Functions
V =
Y2
x
Input Arguments
eqn1,...,eqnN — Higher-order differential equations
symbolic differential equation | array of symbolic differential equations
syms y(t)
eqn = diff(y,2) == t*y;
Output Arguments
V — First-order differential equations
symbolic expression | vector of symbolic expressions
Tips
• To solve the resulting system of first-order differential equations, generate a MATLAB function
handle using matlabFunction with V as an input. Then, use the generated MATLAB function
handle as an input for the MATLAB numerical solver ode23 or ode45.
• odeToVectorField can convert only quasi-linear differential equations. That is, the highest-
order derivatives must appear linearly. For example, odeToVectorField can convert y*y″(t) = –t2
because it can be rewritten as y″(t) = –t2/y. However, it cannot convert y″(t)2 = –t2 or sin(y″(t)) = –
t2.
Algorithms
To convert an nth-order differential equation
7-1134
odeToVectorField
Y1 = y
Y 2 = y′
Y 3 = y″
…
Y n − 1 = y(n − 2)
Y n = y(n − 1)
Using the new variables, it rewrites the equation as a system of n first-order differential equations:
Y 1′ = y′ = Y 2
Y 2′ = y″ = Y 3
…
Y n − 1′ = y(n − 1) = Y n
an − 1 t an − 2 t a1 t a0 t rt
Y n′ = − Yn − Y n − 1 − ... − Y − Y +
an t an t an t 2 an t 1 an t
odeToVectorField returns the right sides of these equations as the elements of vector V and the
substitutions made as the second output S.
Version History
Introduced in R2012a
odeToVectorField will not accept equations as strings or character vectors in a future release.
Instead, use symbolic expressions or sym objects to define differential equations. For example,
replace inputs such as odeToVectorField('D2y=x') with syms y(x),
odeToVectorField(diff(y,x,2)==x).
See Also
dsolve | matlabFunction | odeFunction | ode23 | ode45
7-1135
7 Functions
or
Logical OR for symbolic expressions
Syntax
A | B
or(A,B)
Description
A | B represents the logical OR. A | B is true when either A or B is true, or when both A and B are
true.
or(A,B) is equivalent to A | B.
Examples
syms x y
xy = x>=0 | y>=0;
assume(xy)
assumptions
ans =
0 <= x | 0 <= y
Substitute x with 0 and 10. Although the inequalities have values, subs does not evaluate them to
logical 1 or 0.
x1 = subs(range,x,10)
x2 = subs(range,x,0)
x1 =
1 < 10 | 10 < -1
x2 =
0 < -1 | 1 < 0
7-1136
or
ans =
logical
1
isAlways(x2)
ans =
logical
0
Combine multiple conditions by applying or to the conditions using the fold function.
ans =
x == 1 | x == 2 | x == 3 | x == 4 | x == 5 |...
x == 6 | x == 7 | x == 8 | x == 9 | x == 10
Input Arguments
A, B — Operands
symbolic equations | symbolic inequalities | symbolic expressions | symbolic arrays
Operands, specified as symbolic equations, inequalities, expressions, or arrays. Inputs A and B must
either be the same size or have sizes that are compatible (for example, A is an M-by-N matrix and B is
a scalar or 1-by-N row vector). For more information, see “Compatible Array Sizes for Basic
Operations”.
Tips
• If you call simplify for a logical expression containing symbolic subexpressions, you can get the
symbolic constants symtrue and symfalse. These two constants are not the same as logical 1
(true) and logical 0 (false). To convert symbolic symtrue and symfalse to logical values, use
logical.
Version History
Introduced in R2012a
Starting in R2016b with the addition of implicit expansion, some combinations of arguments for basic
operations that previously returned errors now produce results. For example, you previously could
7-1137
7 Functions
not add a row and a column vector, but those operands are now valid for addition. In other words, an
expression like [1 2] + [1; 2] previously returned a size mismatch error, but now it executes.
If your code uses element-wise operators and relies on the errors that MATLAB previously returned
for mismatched sizes, particularly within a try/catch block, then your code might no longer catch
those errors.
For more information on the required input sizes for basic array operations, see “Compatible Array
Sizes for Basic Operations”.
See Also
all | and | any | isAlways | not | piecewise | xor
7-1138
orth
orth
Orthonormal basis for range of symbolic matrix
Syntax
orth(A)
orth(A,'real')
orth(A,'skipnormalization')
orth(A,'real','skipnormalization')
Description
orth(A) computes an orthonormal basis on page 7-1141 for the range of A.
Examples
Compute Orthonormal Basis
Compute an orthonormal basis of the range of this matrix. Because these numbers are not symbolic
objects, you get floating-point results.
B =
-0.9859 -0.1195 0.1168
0.0290 -0.8108 -0.5846
0.1646 -0.5729 0.8029
Now, convert this matrix to a symbolic object, and compute an orthonormal basis:
B =
[ (2*5^(1/2))/5, -6^(1/2)/6, -(2^(1/2)*15^(1/2))/30]
[ 5^(1/2)/5, 6^(1/2)/3, (2^(1/2)*15^(1/2))/15]
[ 0, 6^(1/2)/6, -(2^(1/2)*15^(1/2))/6]
You can use double to convert this result to the double-precision numeric form. The resulting matrix
differs from the matrix returned by the MATLAB orth function because these functions use different
versions of the Gram-Schmidt orthogonalization algorithm:
7-1139
7 Functions
double(B)
ans =
0.8944 -0.4082 -0.1826
0.4472 0.8165 0.3651
0 0.4082 -0.9129
B'*B
ans =
[ 1, 0, 0]
[ 0, 1, 0]
[ 0, 0, 1]
norm(B(:, 1))
norm(B(:, 2))
norm(B(:, 3))
ans =
1
ans =
1
ans =
1
Compute an orthonormal basis of this matrix using 'real' to avoid complex conjugates:
syms a
A = [a 1; 1 a];
B = orth(A,'real')
B =
[ a/(a^2 + 1)^(1/2), -(a^2 - 1)/((a^2 + 1)*((a^2 -...
1)^2/(a^2 + 1)^2 + (a^2*(a^2 - 1)^2)/(a^2 + 1)^2)^(1/2))]
[ 1/(a^2 + 1)^(1/2), (a*(a^2 - 1))/((a^2 + 1)*((a^2 -...
1)^2/(a^2 + 1)^2 + (a^2*(a^2 - 1)^2)/(a^2 + 1)^2)^(1/2))]
Compute an orthogonal basis of this matrix using 'skipnormalization'. The lengths of the
resulting vectors (the columns of matrix B) are not required to be 1
syms a
A = [a 1; 1 a];
B = orth(A,'skipnormalization')
B =
[ a, -(a^2 - 1)/(a*conj(a) + 1)]
[ 1, -(conj(a) - a^2*conj(a))/(a*conj(a) + 1)]
7-1140
orth
syms a
A = [a 1; 1 a];
B = orth(A,'skipnormalization','real')
B =
[ a, -(a^2 - 1)/(a^2 + 1)]
[ 1, (a*(a^2 - 1))/(a^2 + 1)]
Input Arguments
A — Input
symbolic matrix
More About
Orthonormal Basis
Tips
• Calling orth for numeric arguments that are not symbolic objects invokes the MATLAB orth
function. Results returned by MATLAB orth can differ from results returned by orth because
these two functions use different algorithms to compute an orthonormal basis. The Symbolic Math
Toolbox orth function uses the classic Gram-Schmidt orthogonalization algorithm. The MATLAB
orth function uses the modified Gram-Schmidt algorithm because the classic algorithm is
numerically unstable.
• Using 'skipnormalization' to compute an orthogonal basis instead of an orthonormal basis
can speed up your computations.
Algorithms
orth uses the classic Gram-Schmidt orthogonalization algorithm.
Version History
Introduced in R2013a
See Also
norm | null | orth | rank | svd
7-1141
7 Functions
pade
Pade approximant
Syntax
pade(f,var)
pade(f,var,a)
pade( ___ ,Name,Value)
Description
pade(f,var) returns the third-order Padé approximant of the expression f at var = 0. For details,
see “Padé Approximant” on page 7-1146.
If you do not specify var, then pade uses the default variable determined by symvar(f,1).
pade(f,var,a) returns the third-order Padé approximant of expression f at the point var = a.
pade( ___ ,Name,Value) uses additional options specified by one or more Name,Value pair
arguments. You can specify Name,Value after the input arguments in any of the previous syntaxes.
Examples
Find Padé Approximant for Symbolic Expressions
Find the Padé approximant of sin(x). By default, pade returns a third-order Padé approximant.
syms x
pade(sin(x))
ans =
-(x*(7*x^2 - 60))/(3*(x^2 + 20))
If you do not specify the expansion variable, symvar selects it. Find the Padé approximant of sin(x)
+ cos(y). The symvar function chooses x as the expansion variable.
syms x y
pade(sin(x) + cos(y))
ans =
(- 7*x^3 + 3*cos(y)*x^2 + 60*x + 60*cos(y))/(3*(x^2 + 20))
Specify the expansion variable as y. The pade function returns the Padé approximant with respect to
y.
pade(sin(x) + cos(y),y)
ans =
(12*sin(x) + y^2*sin(x) - 5*y^2 + 12)/(y^2 + 12)
7-1142
pade
Find the value of tan(3*pi/4). Use pade to find the Padé approximant for tan(x) and substitute
into it using subs to find tan(3*pi/4).
syms x
f = tan(x);
P = pade(f);
y = subs(P,x,3*pi/4)
y =
(pi*((9*pi^2)/16 - 15))/(4*((9*pi^2)/8 - 5))
vpa(y)
ans =
-1.2158518789569086447244881326842
You can increase the accuracy of the Padé approximant by increasing the order. If the expansion point
is a pole or a zero, the accuracy can also be increased by setting OrderMode to relative. The
OrderMode option has no effect if the expansion point is not a pole or zero.
Find the Padé approximant of tan(x) using pade with an expansion point of 0 and Order of [1 1].
Find the value of tan(1/5) by substituting into the Padé approximant using subs, and use vpa to
convert 1/5 into a numeric value.
syms x
p11 = pade(tan(x),x,0,'Order',[1 1])
p11 = subs(p11,x,vpa(1/5))
p11 =
x
p11 =
0.2
Find the approximation error by subtracting p11 from the actual value of tan(1/5).
y = tan(vpa(1/5));
error = y - p11
error =
0.0027100355086724833213582716475345
Increase the accuracy of the Padé approximant by increasing the order using Order. Set Order to [2
2], and find the error.
p22 =
-(3*x)/(x^2 - 3)
error =
0.0000073328059697806186555689448317799
7-1143
7 Functions
If the expansion point is a pole or zero, the accuracy of the Padé approximant decreases. Setting the
OrderMode option to relative compensates for the decreased accuracy. For details, see “Padé
Approximant” on page 7-1146. Because the tan function has a zero at 0, setting OrderMode to
relative increases accuracy. This option has no effect if the expansion point is not a pole or zero.
p22Rel =
(x*(x^2 - 15))/(3*(2*x^2 - 5))
error =
0.0000000084084014806113311713765317725998
The accuracy increases if the expansion point is a pole or zero and OrderMode is set to relative.
Plot the difference between exp(x) and its Padé approximants of orders [1 1] through [4 4]. Use
axis to focus on the region of interest. The plot shows that accuracy increases with increasing order
of the Padé approximant.
syms x
expr = exp(x);
hold on
grid on
for i = 1:4
fplot(expr - pade(expr,'Order',i))
end
axis([-4 4 -4 4])
legend('Order [1,1]','Order [2,2]','Order [3,3]','Order [4,4]',...
'Location','Best')
title('Difference Between exp(x) and its Pade Approximant')
ylabel('Error')
7-1144
pade
Input Arguments
f — Input to approximate
symbolic number | symbolic variable | symbolic vector | symbolic matrix | symbolic multidimensional
array | symbolic function | symbolic expression
Expansion variable, specified as a symbolic variable. If you do not specify var, then pade uses the
default variable determined by symvar(f,1).
a — Expansion point
number | symbolic number | symbolic variable | symbolic function | symbolic expression
Expansion point, specified as a number, or a symbolic number, variable, function, or expression. The
expansion point cannot depend on the expansion variable. You also can specify the expansion point as
a Name,Value pair argument. If you specify the expansion point both ways, then the Name,Value
pair argument takes precedence.
7-1145
7 Functions
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: pade(f,'Order',[2 2]) returns the Padé approximant of f of order m = 2 and n = 2.
Expansion point, specified as a number, or a symbolic number, variable, function, or expression. The
expansion point cannot depend on the expansion variable. You can also specify the expansion point
using the input argument a. If you specify the expansion point both ways, then the Name,Value pair
argument takes precedence.
Order of the Padé approximant, specified as an integer, a vector of two integers, or a symbolic
integer, or vector of two integers. If you specify a single integer, then the integer specifies both the
numerator order m and denominator order n producing a Padé approximant with m = n. If you
specify a vector of two integers, then the first integer specifies m and the second integer specifies n.
By default, pade returns a Padé approximant with m = n = 3.
OrderMode — Flag that selects absolute or relative order for Padé approximant
'absolute' (default) | 'relative'
Flag that selects absolute or relative order for Padé approximant, specified as 'absolute' or
'relative'. The default value of 'absolute' uses the standard definition of the Padé
approximant. If you set 'OrderMode' to 'relative', it only has an effect when there is a pole or a
zero at the expansion point a. In this case, to increase accuracy, pade multiplies the numerator by
(var - a)p where p is the multiplicity of the zero or pole at the expansion point. For details, see
“Padé Approximant” on page 7-1146.
More About
Padé Approximant
By default, pade approximates the function f(x) using the standard form of the Padé approximant of
order [m, n] around x = x0 which is
m
a0 + a1 x − x0 + ... + am x − x0
n
.
1 + b1 x − x0 + ... + bn x − x0
When OrderMode is relative, and a pole or zero exists at the expansion point x = x0, the pade
function uses this form of the Padé approximant
p m
x − x0 a0 + a1 x − x0 + ... + am x − x0
n
.
1 + b1 x − x0 + ... + bn x − x0
7-1146
pade
The parameters p and a0 are given by the leading order term f = a0 (x - x0)p + O((x - x0)p + 1) of the
series expansion of f around x = x0. Thus, p is the multiplicity of the pole or zero at x0.
Tips
• If you use both the third argument a and ExpansionPoint to specify the expansion point, the
value specified via ExpansionPoint prevails.
Algorithms
• The parameters a1,…,bn are chosen such that the series expansion of the Padé approximant
coincides with the series expansion of f to the maximal possible order.
• The expansion points ±∞ and ±i∞ are not allowed.
• When pade cannot find the Padé approximant, it returns the function call.
• For pade to return the Padé approximant, a Taylor or Laurent series expansion of f must exist at
the expansion point.
Version History
Introduced in R2014b
See Also
series | taylor
Topics
“Padé Approximant” on page 3-202
7-1147
7 Functions
partfrac
Partial fraction decomposition
Syntax
partfrac(expr,var)
partfrac(expr,var,Name,Value)
Description
partfrac(expr,var) finds the partial fraction decomposition of expr with respect to var. If you
do not specify var, then partfrac uses the variable determined by symvar.
Examples
Partial Fraction Decomposition of Symbolic Expressions
First, find partial fraction decomposition of univariate expressions. For expressions with one variable,
you can omit specifying the variable.
syms x
partfrac(x^2/(x^3 - 3*x + 2))
ans =
5/(9*(x - 1)) + 1/(3*(x - 1)^2) + 4/(9*(x + 2))
Find partial fraction decomposition of a multivariate expression with respect to a particular variable.
syms a b
partfrac(a^2/(a^2 - b^2),a)
ans =
b/(2*(a - b)) - b/(2*(a + b)) + 1
partfrac(a^2/(a^2 - b^2),b)
ans =
a/(2*(a + b)) + a/(2*(a - b))
If you do not specify the variable, then partfrac computes partial fraction decomposition with
respect to a variable determined by symvar.
symvar(a^2/(a^2 - b^2),1)
partfrac(a^2/(a^2 - b^2))
ans =
b
7-1148
partfrac
ans =
a/(2*(a + b)) + a/(2*(a - b))
Factorization Modes
Find the partial fraction decomposition without specifying the factorization mode. By default,
partfrac uses factorization over rational numbers. In this mode, partfrac keeps numbers in their
exact symbolic form.
syms x
f = 1/(x^3 + 2);
partfrac(f,x)
ans =
1/(x^3 + 2)
Repeat the decomposition with numeric factorization over real numbers. In this mode, partfrac
factors the denominator into linear and quadratic irreducible polynomials with real coefficients. This
mode converts all numeric values to floating-point numbers.
partfrac(f,x,'FactorMode','real')
ans =
0.2099868416491455274612017678797/(x + 1.2599210498948731647672106072782) -...
(0.2099868416491455274612017678797*x - 0.52913368398939982491723521309077)/(x^2 -...
1.2599210498948731647672106072782*x + 1.5874010519681994747517056392723)
Repeat the decomposition with factorization over complex numbers. In this mode, partfrac reduces
quadratic polynomials in the denominator to linear expressions with complex coefficients. This mode
converts all numbers to floating point.
partfrac(f,x,'FactorMode','complex')
ans =
0.2099868416491455274612017678797/(x + 1.2599210498948731647672106072782) +...
(- 0.10499342082457276373060088393985 - 0.18185393932862023392667876903163i)/...
(x - 0.62996052494743658238360530363911 - 1.0911236359717214035600726141898i) +...
(- 0.10499342082457276373060088393985 + 0.18185393932862023392667876903163i)/...
(x - 0.62996052494743658238360530363911 + 1.0911236359717214035600726141898i)
Find the partial fraction decomposition of this expression using the full factorization mode. In this
mode, partfrac factors the denominator into linear expressions, reducing quadratic polynomials to
linear expressions with complex coefficients. This mode keeps numbers in their exact symbolic form.
pfFull = partfrac(f,x,'FactorMode','full')
pfFull =
2^(1/3)/(6*(x + 2^(1/3))) +...
(2^(1/3)*((3^(1/2)*1i)/2 - 1/2))/(6*(x + 2^(1/3)*((3^(1/2)*1i)/2 - 1/2))) -...
(2^(1/3)*((3^(1/2)*1i)/2 + 1/2))/(6*(x - 2^(1/3)*((3^(1/2)*1i)/2 + 1/2)))
Approximate the result with floating-point numbers by using vpa. Because the expression does not
contain any symbolic parameters besides the variable x, the result is the same as in complex
factorization mode.
vpa(pfFull)
ans =
0.2099868416491455274612017678797/(x + 1.2599210498948731647672106072782) +...
7-1149
7 Functions
(- 0.10499342082457276373060088393985 - 0.18185393932862023392667876903163i)/...
(x - 0.62996052494743658238360530363911 - 1.0911236359717214035600726141898i) +...
(- 0.10499342082457276373060088393985 + 0.18185393932862023392667876903163i)/...
(x - 0.62996052494743658238360530363911 + 1.0911236359717214035600726141898i)
In the complex mode, partfrac factors only those expressions in the denominator whose coefficients
can be converted to floating-point numbers. Show this by replacing 2 in f with a symbolic variable
and find the partial fraction decomposition in complex mode. partfrac returns the expression
unchanged.
syms a
f = subs(f,2,a);
partfrac(f,x,'FactorMode','complex')
ans =
1/(x^3 + a)
When you use the full factorization mode, partfrac factors expressions in the denominator
symbolically. Thus, partfrac in the full factorization mode factors the expression.
partfrac(1/(x^3 + a), x, 'FactorMode', 'full')
ans =
1/(3*(-a)^(2/3)*(x - (-a)^(1/3))) -...
((3^(1/2)*1i)/2 + 1/2)/(3*(-a)^(2/3)*(x + (-a)^(1/3)*((3^(1/2)*1i)/2 + 1/2))) +...
((3^(1/2)*1i)/2 - 1/2)/(3*(-a)^(2/3)*(x - (-a)^(1/3)*((3^(1/2)*1i)/2 - 1/2)))
In full factorization mode, partfrac represents coefficients using root when it is not
mathematically possible to find the coefficients as exact symbolic numbers. Show this behavior.
syms x
s = partfrac(1/(x^3 + x - 3), x, 'FactorMode','full')
s =
symsum(-((6*root(z^3 + z - 3, z, k)^2)/247 +...
(27*root(z^3 + z - 3, z, k))/247 +...
4/247)/(root(z^3 + z - 3, z, k) - x), k, 1, 3)
ans =
0.1846004942289254798185772017286/(x - 1.2134116627622296341321313773815) +...
(- 0.092300247114462739909288600864302 + 0.11581130283490645120989658654914i)/...
(x + 0.60670583138111481706606568869074 - 1.450612249188441526515442203395i) +...
(- 0.092300247114462739909288600864302 - 0.11581130283490645120989658654914i)/...
(x + 0.60670583138111481706606568869074 + 1.450612249188441526515442203395i)
Return a vector of numerators and a vector of denominators of the partial fraction decomposition.
P =
5/(9*(x - 1)) + 1/(3*(x - 1)^2) + 4/(9*(x + 2))
7-1150
partfrac
Partial fraction decomposition is a sum of fractions. Use the children function to return a vector
containing the terms of that sum. Then, use numden to extract the numerators and denominators of
the terms.
C = children(P);
C = [C{:}];
[N,D] = numden(C)
N =
[ 5, 1, 4]
D =
[ 9*x - 9, 3*(x - 1)^2, 9*x + 18]
Reconstruct the partial fraction decomposition from the vectors of numerators and denominators.
P1 = sum(N./D)
P1 =
1/(3*(x - 1)^2) + 5/(9*x - 9) + 4/(9*x + 18)
Verify that the reconstructed expression, P1, is equivalent to the original partial fraction
decomposition, P.
isAlways(P1 == P)
ans =
logical
1
Input Arguments
expr — Rational expression
symbolic expression | symbolic function
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: partfrac(1/(x^3 - 2),x,'FactorMode','real')
Factorization mode, specified as the comma-separated pair consisting of 'FactorMode' and one of
these character vectors.
7-1151
7 Functions
More About
Partial Fraction Decomposition
px
f x =gx + ,
qx
Where the denominator of the expression can be written as q x = q1 x q2 x …, the partial fraction
decomposition is an expression of this form.
pj x
f x =gx +∑
j
qj x
Here, the denominators q j x are irreducible polynomials or powers of irreducible polynomials. The
numerators p j x are polynomials of smaller degrees than the corresponding denominators q j x .
Partial fraction decomposition can simplify integration by integrating each term of the returned
expression separately.
Version History
Introduced in R2015a
See Also
children | coeffs | collect | combine | compose | divisors | expand | factor | horner |
numden | rewrite | simplify | simplifyFraction
Topics
“Choose Function to Rearrange Expression” on page 3-119
7-1152
pdeCoefficients
pdeCoefficients
Extract coefficients of partial differential equation
Syntax
coeffs = pdeCoefficients(pdeeq,u)
symCoeffs = pdeCoefficients(pdeeq,u,'Symbolic',true)
Description
coeffs = pdeCoefficients(pdeeq,u) extracts the coefficients of a partial differential equation
(PDE) as a structure of double-precision numbers and function handles, which can be used as input of
the specifyCoefficients function in Partial Differential Equation Toolbox™.
pdeeq is a scalar PDE or a PDE system in symbolic form that is a function of u. The
pdeCoefficients function converts pdeeq into a system of equations of the form
∂2 u ∂u
m +d − ∇ · c ⊗ ∇u + au = f
∂t 2 ∂t
and returns the structure coeffs that contains the coefficients m, d, c, a, and f. For more
information, see “Equations You Can Solve Using PDE Toolbox” (Partial Differential Equation
Toolbox).
If pdeCoefficients cannot convert a PDE into the divergence form above, then it issues a warning
message and writes all remaining gradients to the f coefficient. PDE Toolbox will be unable to solve
this type of PDE.
Examples
Create a symbolic PDE that represents the Laplacian of the variable u(x,y).
syms u(x,y)
pdeeq = laplacian(u,[x y]) == -3
pdeeq(x, y) =
∂2 ∂2
2
u x, y + u x, y = −3
∂x ∂y2
7-1153
7 Functions
c: [4x1 double]
m: 0
d: 0
f: -3
pdeCoefficients converts the symbolic PDE into a scalar PDE equation of the form
∂2 u ∂u
m +d − ∇ ⋅ (c ∇u) + au = f
∂t 2 ∂t
and extracts the coefficients m, d, c, a, and f into the structure coeffs. For 2-D systems of N
equations, c is a tensor with 4N2 elements. For more information, see “c Coefficient for
specifyCoefficients” (Partial Differential Equation Toolbox). In this case, N = 1, so the coefficient c is
a 4-by-1 column vector that represents cxx, cxy, cyx, and cyy.
coeffs.c
ans = 4×1
-1
0
0
-1
Solve a 2-D homogenous Laplace's equation in the domain bounded by a unit circle. Use the
pdeCoefficients function to extract the coefficients of the Laplace's equation.
model = createpde;
geometryFromEdges(model,@circleg);
Plot the geometry and display the edge labels for use in the boundary condition definition.
figure
pdegplot(model,'EdgeLabels','on')
axis equal
7-1154
pdeCoefficients
syms u(x,y)
pdeeq = laplacian(u,[x y])
pdeeq(x, y) =
∂2 ∂2
2
u x, y + u x, y
∂x ∂y2
coeffs = pdeCoefficients(pdeeq,u)
specifyCoefficients(model,'m',coeffs.m,'d',coeffs.d, ...
'c',coeffs.c,'a',coeffs.a,'f',coeffs.f);
Apply the Dirichlet boundary condition u(x, y) = x4 + y4 at all 4 edges that form the circle.
7-1155
7 Functions
Solve a 2-D Poisson's equation in the domain bounded by a unit circle. The divergence form of the
PDE has nonconstant f coefficient. You can solve the PDE by extracting the coefficients using
pdeCoefficients and specifying the coefficients in the PDE model using specifyCoefficients.
7-1156
pdeCoefficients
pdeeq(x, y) =
∂2 1 ∂2
u x, y − + u x, y
∂x2 x2 + y2 ∂y2
coeffs = pdeCoefficients(pdeeq,u)
coeffs.f('show')
ans =
1
x2 + y2
specifyCoefficients(model,'m',coeffs.m,'d',coeffs.d, ...
'c',coeffs.c,'a',coeffs.a,'f',coeffs.f);
Apply the Dirichlet boundary condition u(x, y) = 0 at all 4 edges that form the circle.
applyBoundaryCondition(model,'dirichlet','Edge',1:4,'u',0);
generateMesh(model);
Solve the PDE. Plot the nodal solution using the option 'XYData' in the pdeplot function.
results = solvepde(model);
pdeplot(model,'XYData',results.NodalSolution)
7-1157
7 Functions
Plot the gradient of the solution at the nodal locations using the option 'FlowData'.
pdeplot(model,'FlowData',[results.XGradients results.YGradients])
7-1158
pdeCoefficients
pdeeq(x, y) =
∂ ∂ ∂2
2 cos x + y ∂y ∂x u x, y u x, y
∂ ∂y2
u x, y + +
∂x2 4 2
Extract its coefficients. When pdeCoefficients cannot convert a PDE into the divergence form
∂2 u ∂u
m +d − ∇ ⋅ (c ⊗ ∇u) + au = f ,
∂t 2 ∂t
Warning: After extracting m, d, and c, some gradients remain. Writing all remaining terms to f.
7-1159
7 Functions
c: @makeCoefficient/coefficientFunction
m: 0
d: 0
f: @makeCoefficient/coefficientFunction
To show the function handles in the extracted coefficients c and f, use the option 'show'. All
remaining gradients in the PDE are written to the f coefficient.
coeffs.c('show')
ans =
−1
1 cos x + y
−
8 4
1 cos x + y
−
8 4
1
−
2
coeffs.f('show')
ans =
∂ ∂ ∂ ∂ ∂ ∂
sin x + y ∂x u x, y sin x + y ∂y u x, y cos x + y ∂y ∂x u x, y ∂y ∂x
u x, y
+ − +
4 4 4 4
Since the PDE has no divergence form required by the PDE Toolbox, the toolbox will be unable to
solve this PDE.
Solve a time-dependent wave equation in the domain bounded by a unit circle. The wave equation is a
PDE with a scalar function u(t, x, y) that depends on time t and coordinates x and y.
model = createpde(1);
geometryFromEdges(model,@circleg);
syms u(t,x,y)
pdeeq = diff(u,t,t) - laplacian(u,[x y])
pdeeq(t, x, y) =
∂2 ∂2 ∂2
u t, x, y − u t, x, y − u t, x, y
∂t2 ∂x2 ∂y2
coeffs = pdeCoefficients(pdeeq,u)
7-1160
pdeCoefficients
c: [4x1 double]
m: 1
d: 0
f: 0
specifyCoefficients(model,'m',coeffs.m,'d',coeffs.d, ...
'c',coeffs.c,'a',coeffs.a,'f',coeffs.f);
Set the initial conditions of the time-dependent problem on the entire geometry.
setInitialConditions(model,0,1);
Apply the Dirichlet boundary condition u(x, y) = 0 at all 4 edges that form the circle.
applyBoundaryCondition(model,'dirichlet','Edge',1:4,'u',0);
generateMesh(model);
Find the solutions of the time-dependent PDE at a time range from 0s to 50s with a 2s interval.
results = solvepde(model,linspace(0,2,50));
figure;
for k = 1:10
subplot(5,2,k);
pdeplot(model,'XYData',results.NodalSolution(:,k*5))
axis equal
end
7-1161
7 Functions
Solve a system of two second-order PDEs. You can solve the PDE system by extracting the PDE
coefficients symbolically using pdeCoefficients, converting the coefficients to double-precision
numbers using pdeCoefficientsToDouble, and specifying the coefficients in the PDE model using
specifyCoefficients.
The system of PDEs represents the deflection of a clamped structural plate under a uniform pressure
load. The system of PDEs with the dependent variables u1 and u2 is given by
− ∇2 u1 + u2 = 0,
−D ∇2 u2 = p,
3
Eh
D= ,
12(1 − ν2)
and E is the modulus of elasticity, ν is Poisson's ratio, h is the plate thickness, u1 is the transverse
deflection of the plate, and p is the pressure load.
7-1162
pdeCoefficients
model = createpde(2);
Create a square geometry. Specify the side length of the square. Then include the geometry in the
PDE model.
len = 10.0;
gdm = [3 4 0 len len 0 0 0 len len]';
g = decsg(gdm,'S1',('S1')');
geometryFromEdges(model,g);
Specify the values of the physical parameters of the system. Let the external pressure p be a symbolic
variable pres that can take any value.
E = 1.0e6;
h_thick = 0.1;
nu = 0.3;
D = E*h_thick^3/(12*(1 - nu^2));
syms pres
Declare the PDE system as a system symbolic equations. Extract the coefficients of the PDE and
return them in symbolic form.
structfun(@disp,symCoeffs)
01
00
10 0 0
01 0 0
25000
00 0
273
25000
00 0
273
0
pres
7-1163
7 Functions
Substitute a value for pres using the subs function. Since the outputs of subs are symbolic objects,
use the pdeCoefficientsToDouble function to convert the coefficients to the double data type,
which makes them valid inputs for the PDE Toolbox.
symCoeffs = subs(symCoeffs,pres,2);
coeffs = pdeCoefficientsToDouble(symCoeffs)
specifyCoefficients(model,'m',coeffs.m,'d',coeffs.d, ...
'c',coeffs.c,'a',coeffs.a,'f',coeffs.f);
Specify spring stiffness. Specify boundary conditions by defining distributed springs on all four edges.
k = 1e7;
bOuter = applyBoundaryCondition(model,'neumann','Edge',(1:4), ...
'g',[0 0],'q',[0 0; k 0]);
Specify the mesh size of the geometry and generate a mesh for the PDE model.
hmax = len/20;
generateMesh(model,'Hmax',hmax);
res = solvepde(model);
u = res.NodalSolution;
numNodes = size(model.Mesh.Nodes,2);
figure;
pdeplot(model,'XYData',u(1:numNodes),'contour','on')
title 'Transverse Deflection'
7-1164
pdeCoefficients
wMax = -0.2763
Compare the result with the deflection at the plate center computed analytically.
pres = 2;
wMax = -.0138*pres*len^4/(E*h_thick^3)
wMax = -0.2760
Input Arguments
pdeeq — PDE in symbolic form
symbolic equation | symbolic expression | symbolic vector
Dependent variables of PDE, specified as a symbolic function. u must contain stationary or time-
dependent variables in two or three dimensions. For example, create the variable u using one of these
statements:
7-1165
7 Functions
• syms u(x,y)
• syms u(t,x,y)
• syms u(x,y,z)
• syms u(t,x,y,z)
Output Arguments
coeffs — Coefficients of PDE operating on doubles
structure of doubles and function handles
When pdeCoefficients returns a coefficient as a function handle, the function handle takes two
structures as input arguments, location and state, and returns double-precision output. The
function handle is displayed as @makeCoefficient/coefficientFunction in the Command
Window. To display the formula of the function handle in coeffs.f in symbolic form, use
coeffs.f('show').
In some cases, not all generated coefficients can be used by specifyCoefficients. For example,
the d coefficient must take a special matrix form when m is nonzero. For more details, see “d
Coefficient When m Is Nonzero” (Partial Differential Equation Toolbox).
Version History
Introduced in R2021a
See Also
syms | diff | laplacian | pdeCoefficientsToDouble | specifyCoefficients
Topics
“Solve Partial Differential Equation of Nonlinear Heat Transfer” on page 3-260
7-1166
pdeCoefficientsToDouble
pdeCoefficientsToDouble
Convert symbolic PDE coefficients to double format
Syntax
coeffs = pdeCoefficientsToDouble(symCoeffs)
coeffs = pdeCoefficientsToDouble(symCoeffs,u)
Description
coeffs = pdeCoefficientsToDouble(symCoeffs) converts the symbolic objects of the
structure symCoeffs to double-precision numbers or function handles. The output is a structure
coeffs that can then be used to define the coefficients of a PDE model by calling
specifyCoefficients in Partial Differential Equation Toolbox.
The structure coeffs contains the coefficients m, d, c, a, and f for the PDE system with the form
∂2 u ∂u
m +d − ∇ · c ⊗ ∇u + au = f
∂t2 ∂t
that can be solved in Partial Differential Equation Toolbox. For more information, see “Equations You
Can Solve Using PDE Toolbox” (Partial Differential Equation Toolbox).
Examples
Create a symbolic PDE that represents the Laplacian of the variable u(x,y).
syms u(x,y) f
pdeeq = laplacian(u,[x y]) == f
pdeeq(x, y) =
∂2 ∂2
2
u x, y + u x, y = f
∂x ∂y2
Extract the coefficients of the PDE as symbolic expressions and display their values.
symCoeffs = pdeCoefficients(pdeeq,u,'Symbolic',true);
structfun(@disp,symCoeffs)
−1 0
0 −1
7-1167
7 Functions
pdeCoefficients converts the symbolic PDE into a scalar PDE equation of the form
∂2 u ∂u
m +d − ∇ ⋅ (c ∇u) + au = f ,
∂t 2 ∂t
Choose a value for f. Since symCoeffs are symbolic objects, use pdeCoefficientsToDouble to
convert the coefficients to double data type. The coefficients with double data type are valid inputs
for the specifyCoefficients function in the PDE Toolbox.
symCoeffs = subs(symCoeffs,f,-3);
coeffs = pdeCoefficientsToDouble(symCoeffs)
Solve a system of two second-order PDEs. You can solve the PDE system by extracting the PDE
coefficients symbolically using pdeCoefficients, converting the coefficients to double-precision
numbers using pdeCoefficientsToDouble, and specifying the coefficients in the PDE model using
specifyCoefficients.
The system of PDEs represents the deflection of a clamped structural plate under a uniform pressure
load. The system of PDEs with the dependent variables u1 and u2 is given by
− ∇2 u1 + u2 = 0,
−D ∇2 u2 = p,
3
Eh
D= ,
12(1 − ν2)
and E is the modulus of elasticity, ν is Poisson's ratio, h is the plate thickness, u1 is the transverse
deflection of the plate, and p is the pressure load.
model = createpde(2);
7-1168
pdeCoefficientsToDouble
Create a square geometry. Specify the side length of the square. Then include the geometry in the
PDE model.
len = 10.0;
gdm = [3 4 0 len len 0 0 0 len len]';
g = decsg(gdm,'S1',('S1')');
geometryFromEdges(model,g);
Specify the values of the physical parameters of the system. Let the external pressure p be a symbolic
variable pres that can take any value.
E = 1.0e6;
h_thick = 0.1;
nu = 0.3;
D = E*h_thick^3/(12*(1 - nu^2));
syms pres
Declare the PDE system as a system symbolic equations. Extract the coefficients of the PDE and
return them in symbolic form.
structfun(@disp,symCoeffs)
01
00
10 0 0
01 0 0
25000
00 0
273
25000
00 0
273
0
pres
Substitute a value for pres using the subs function. Since the outputs of subs are symbolic objects,
use the pdeCoefficientsToDouble function to convert the coefficients to the double data type,
which makes them valid inputs for the PDE Toolbox.
7-1169
7 Functions
symCoeffs = subs(symCoeffs,pres,2);
coeffs = pdeCoefficientsToDouble(symCoeffs)
specifyCoefficients(model,'m',coeffs.m,'d',coeffs.d, ...
'c',coeffs.c,'a',coeffs.a,'f',coeffs.f);
Specify spring stiffness. Specify boundary conditions by defining distributed springs on all four edges.
k = 1e7;
bOuter = applyBoundaryCondition(model,'neumann','Edge',(1:4), ...
'g',[0 0],'q',[0 0; k 0]);
Specify the mesh size of the geometry and generate a mesh for the PDE model.
hmax = len/20;
generateMesh(model,'Hmax',hmax);
res = solvepde(model);
u = res.NodalSolution;
numNodes = size(model.Mesh.Nodes,2);
figure;
pdeplot(model,'XYData',u(1:numNodes),'contour','on')
title 'Transverse Deflection'
7-1170
pdeCoefficientsToDouble
wMax = min(u(1:numNodes,1))
wMax = -0.2763
Compare the result with the deflection at the plate center computed analytically.
pres = 2;
wMax = -.0138*pres*len^4/(E*h_thick^3)
wMax = -0.2760
Create a PDE system of four equations with four dependent variables, A, E, P, and T .
pdeeq(x, y, z, t) =
7-1171
7 Functions
∂
A x, y, z, t = σ2
∂t
∂
P x, y, z, t = σ1
∂t
∂
E x, y, z, t = σ2 + σ1
∂t
∂ ∂2 ∂2 ∂2
T x, y, z, t = T x, y, z, t + T x, y, z, t + 2 T x, y, z, t − σ2 − σ1
∂t ∂x 2 ∂y 2 ∂z
where
σ1 = eT x, y, z, t E x, y, z, t P x, y, z, t
σ2 = eT x, y, z, t A x, y, z, t E x, y, z, t
Extract the coefficients of the PDE system as symbolic expressions. Specify the variable u to
represent the dependent variables.
u = [A E P T];
symCoeffs = pdeCoefficients(pdeeq,u,'Symbolic',true)
structfun(@disp,symCoeffs)
0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
−σ2 0 00
0 σ1 00
−σ2 σ1 00
σ2 eT x, y, z, t P x, y, z, t 0 0
where
σ1 = − eT x, y, z, t P x, y, z, t
σ2 = eT x, y, z, t E x, y, z, t
7-1172
pdeCoefficientsToDouble
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 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 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 0 0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 0 0 1
0
0
0
0
1 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
Convert the coefficients to the double data type so that they are valid inputs for the
specifyCoefficients function in Partial Differential Equation Toolbox. Because the a coefficient
in symCoeffs contains the dependent variables and is not constant, calling
pdeCoefficientsToDouble(symCoeffs) without the second input argument can return an error.
Instead, specify the second argument as the dependent variables u when using
pdeCoefficientsToDouble.
coeffs = pdeCoefficientsToDouble(symCoeffs,u)
Input Arguments
symCoeffs — Coefficients of PDE in symbolic form
structure of symbolic expressions
Dependent variables of PDE, specified as a symbolic function. The argument u must contain
stationary or time-dependent variables in two or three dimensions.
7-1173
7 Functions
Output Arguments
coeffs — Coefficients of PDE operating on doubles
structure of doubles and function handles
In some cases, not all generated coefficients can be used by specifyCoefficients. For example,
the d coefficient must take a special matrix form when m is nonzero. For more details, see “d
Coefficient When m Is Nonzero” (Partial Differential Equation Toolbox).
Version History
Introduced in R2021a
You can specify the dependent variables u of a PDE system as the second input argument of
pdeCoefficientsToDouble when converting symbolic coefficients of the PDE system to double-
precision numbers or function handles. For example, see “Specify Dependent Variables of PDE
System” on page 7-1171.
See Also
syms | diff | laplacian | pdeCoefficients | specifyCoefficients
Topics
“Solve Partial Differential Equation of Nonlinear Heat Transfer” on page 3-260
7-1174
piecewise
piecewise
Conditionally defined expression or function
Syntax
pw = piecewise(cond1,val1,cond2,val2,...)
pw = piecewise(cond1,val1,cond2,val2,...,otherwiseVal)
Description
pw = piecewise(cond1,val1,cond2,val2,...) returns the piecewise expression or function
pw whose value is val1 when condition cond1 is true, is val2 when cond2 is true, and so on. If no
condition is true, the value of pw is NaN.
Examples
−1 x < 0
y=
1 x>0
syms x
y = piecewise(x < 0,-1,x > 0,1)
y =
−1 if x < 0
1 if 0 < x
Evaluate y at -2, 0, and 2 by using subs to substitute for x. Because y is undefined at x = 0, the
value is NaN.
subs(y,x,[-2 0 2])
ans = −1 NaN 1
−1 x < 0
yx =
1 x>0
7-1175
7 Functions
syms y(x)
y(x) = piecewise(x < 0,-1,x > 0,1)
y(x) =
−1 if x < 0
1 if 0 < x
Because y(x) is a symbolic function, you can directly evaluate it for values of x. Evaluate y(x) at -2,
0, and 2. Because y(x) is undefined at x = 0, the value is NaN. For details, see “Create Symbolic
Functions” on page 1-9.
y([-2 0 2])
ans = −1 NaN 1
Set the value of a piecewise function when no condition is true (called otherwise value) by specifying
an additional input argument. If an additional argument is not specified, the default otherwise value
of the function is NaN.
−2 x < − 2
y = 0 −2 < x < 0
1 otherwise .
syms y(x)
y(x) = piecewise(x < -2,-2,(-2 < x) & (x < 0),0,1)
y(x) =
−2 if x < −2
0 if x ∈ −2, 0
1 otherwise
Evaluate y(x) between -3 and 1 by generating values of x using linspace. At -2 and 0, y(x)
evaluates to 1 because the other conditions are not true.
xvalues = linspace(-3,1,5)
xvalues = 1×5
-3 -2 -1 0 1
yvalues = y(xvalues)
yvalues = −2 1 0 1 1
7-1176
piecewise
−2 x < − 2
y = x −2 < x < 2 .
2 x>2
syms x
y = piecewise(x < -2,-2,-2 < x < 2,x,x > 2,2);
fplot(y)
On creation, a piecewise expression applies existing assumptions. Apply assumptions set after
creating the piecewise expression by using simplify on the expression.
Assume x > 0. Then define a piecewise expression with the same condition x > 0. piecewise
automatically applies the assumption to simplify the condition.
syms x
assume(x > 0)
pw = piecewise(x < 0,-1,x > 0,1)
pw = 1
7-1177
7 Functions
Create a piecewise expression pw with the condition x > 0. Then set the assumption that x > 0.
Apply the assumption to pw by using simplify.
pw = piecewise(x < 0,-1,x > 0,1);
assume(x > 0)
pw = simplify(pw)
pw = 1
Differentiate, integrate, and find limits of a piecewise expression by using diff, int, and limit
respectively.
1/x x< −1
y=
sin x /x x ≥ − 1
syms x
y = piecewise(x < -1,1/x,x >= -1,sin(x)/x);
diffy = diff(y,x)
diffy =
1
− 2 if x < −1
x
cos x sin x
− if −1 < x
x x2
inty =
log x if x < −1
sinint x if −1 ≤ x
ans = 1
Find the right- and left-sided limits of y at -1. For details, see limit.
limit(y,x,-1,'right')
ans = sin 1
limit(y,x,-1,'left')
ans = −1
7-1178
piecewise
Add, subtract, divide, and multiply two piecewise expressions. The resulting piecewise expression is
only defined where the initial piecewise expressions are defined.
syms x
pw1 = piecewise(x < -1,-1,x >= -1,1);
pw2 = piecewise(x < 0,-2,x >= 0,2);
add = pw1+pw2
add =
−3 if x < −1
−1 if x ∈ −1, 0
3 if 0 ≤ x
sub = pw1-pw2
sub =
1 if x < −1
3 if x ∈ −1, 0
−1 if 0 ≤ x
mul = pw1*pw2
mul =
2 if x < −1
−2 if x ∈ −1, 0
2 if 0 ≤ x
div = pw1/pw2
div =
1
if x < −1
2
1
− if x ∈ −1, 0
2
1
if 0 ≤ x
2
Modify a piecewise expression by replacing part of the expression using subs. Extend a piecewise
expression by specifying the expression as the otherwise value of a new piecewise expression. This
action combines the two piecewise expressions. piecewise does not check for overlapping or
conflicting conditions. Instead, like an if-else ladder, piecewise returns the value for the first true
condition.
7-1179
7 Functions
pw =
−1 if x < 0
1 if 0 < x
Add the condition x > 5 with the value 1/x to pw by creating a new piecewise expression with pw as
the otherwise value.
pw =
1
if 5 < x
x
−1 if x < 0
1 if 0 < x
Input Arguments
cond — Condition
symbolic condition | symbolic variable
Value when condition is satisfied, specified as a number, vector, matrix, or multidimensional array, or
as a symbolic number, variable, vector, matrix, multidimensional array, function, or expression.
Value if no conditions are true, specified as a number, vector, matrix, or multidimensional array, or as
a symbolic number, variable, vector, matrix, multidimensional array, function, or expression. If
otherwiseVal is not specified, its value is NaN.
Output Arguments
pw — Piecewise expression or function
symbolic expression | symbolic function
7-1180
piecewise
Tips
• piecewise does not check for overlapping or conflicting conditions. A piecewise expression
returns the value of the first true condition and disregards any following true expressions. Thus,
piecewise mimics an if-else ladder.
Version History
Introduced in R2016b
See Also
and | assume | assumeAlso | assumptions | if | in | isAlways | not | or
7-1181
7 Functions
pinv
Moore-Penrose inverse (pseudoinverse) of symbolic matrix
Syntax
X = pinv(A)
Description
X = pinv(A) returns the pseudoinverse of A. Pseudoinverse is also called the Moore-Penrose
inverse.
Examples
Compute Pseudoinverse of Matrix
Compute the pseudoinverse of this matrix. Because these numbers are not symbolic objects, you get
floating-point results.
A = [1 1i 3; 1 3 2];
X = pinv(A)
X =
0.0729 + 0.0312i 0.0417 - 0.0312i
-0.2187 - 0.0521i 0.3125 + 0.0729i
0.2917 + 0.0625i 0.0104 - 0.0938i
Now, convert this matrix to a symbolic object, and compute the pseudoinverse.
A = sym([1 1i 3; 1 3 2]);
X = pinv(A)
X =
[ 7/96 + 1i/32, 1/24 - 1i/32]
[ - 7/32 - 5i/96, 5/16 + 7i/96]
[ 7/24 + 1i/16, 1/96 - 3i/32]
isAlways(A*X*A == A)
ans =
2×3 logical array
1 1 1
1 1 1
isAlways(X*A*X == X)
ans =
3×2 logical array
1 1
1 1
1 1
7-1182
pinv
isAlways(A*X == (A*X)')
ans =
2×2 logical array
1 1
1 1
isAlways(X*A == (X*A)')
ans =
3×3 logical array
1 1 1
1 1 1
1 1 1
syms a
A = [1 a; -a 1];
X = pinv(A)
X =
[ (a*conj(a) + 1)/(a^2*conj(a)^2 + a^2 + conj(a)^2 + 1) -...
(conj(a)*(a - conj(a)))/(a^2*conj(a)^2 + a^2 + conj(a)^2 + 1),
- (a - conj(a))/(a^2*conj(a)^2 + a^2 + conj(a)^2 + 1) -...
(conj(a)*(a*conj(a) + 1))/(a^2*conj(a)^2 + a^2 + conj(a)^2 + 1)]
[ (a - conj(a))/(a^2*conj(a)^2 + a^2 + conj(a)^2 + 1) +...
(conj(a)*(a*conj(a) + 1))/(a^2*conj(a)^2 + a^2 + conj(a)^2 + 1),
(a*conj(a) + 1)/(a^2*conj(a)^2 + a^2 + conj(a)^2 + 1) -...
(conj(a)*(a - conj(a)))/(a^2*conj(a)^2 + a^2 + conj(a)^2 + 1)]
assume(a,'real')
A = [1 a; -a 1];
X = pinv(A)
X =
[ 1/(a^2 + 1), -a/(a^2 + 1)]
[ a/(a^2 + 1), 1/(a^2 + 1)]
syms a
Input Arguments
A — Input
symbolic matrix
7-1183
7 Functions
Output Arguments
X — Pseudoinverse of matrix
symbolic matrix
Pseudoinverse of matrix, returned as a symbolic matrix, such that A*X*A = A and X*A*X = X.
More About
Moore-Penrose Pseudoinverse
The pseudoinverse of an m-by-n matrix A is an n-by-m matrix X, such that A*X*A = A and X*A*X =
X. The matrices A*X and X*A must be Hermitian.
Tips
• Calling pinv for numeric arguments that are not symbolic objects invokes the MATLAB pinv
function.
• For an invertible matrix A, the Moore-Penrose inverse X of A coincides with the inverse of A.
Version History
Introduced in R2013a
See Also
inv | rank | pinv | svd
7-1184
playAnimation
playAnimation
Play animation objects in a MATLAB figure window
Syntax
playAnimation
playAnimation(fig)
playAnimation( ___ ,Name,Value)
Description
playAnimation plays animation objects in a MATLAB figure window. The animation objects must be
created using the fanimator function.
By default, the variable t = sym('t') is the time parameter of the animation objects.
playAnimation plays the animation with 10 frames per unit interval of t within the range of t from
0 to 10.
playAnimation( ___ ,Name,Value) plays the animation objects with the specified Name,Value
pair arguments. Use this option with any of the input argument combinations in the previous
syntaxes.
Examples
Create two symbolic variables, t and x. The variable t defines the time parameter of the animation.
Use t to set the center of the circle at (t,1) and x to parameterize the perimeter of the circle within
the range [-pi pi]. Set the x-axis and y-axis to be equal length.
syms t x
fanimator(@fplot,cos(x)+t,sin(x)+1,[-pi pi])
axis equal
7-1185
7 Functions
7-1186
playAnimation
By default, playAnimation plays an animation with 10 generated frames per unit time within the
range of t from 0 to 10.
Create two symbolic variables, t and x. The variable t defines the time parameter of the animation.
syms t x
Create a circle animation object using fanimator. Use t to set the center of the circle at (t,1) and
x to parameterize the perimeter of the circle within the range [-pi pi]. Set the x-axis and y-axis to
be equal length.
fanimator(@fplot,cos(x)+t,sin(x)+1,[-pi pi])
axis equal
7-1187
7 Functions
Add a piece of text to count the elapsed time by using the text function. Use num2str to convert the
time parameter to a string.
hold on
fanimator(@(t) text(9,3,"Timer: "+num2str(t,2)))
hold off
7-1188
playAnimation
By default, playAnimation plays the animation with 10 generated frames per unit time within the
range of t from 0 to 10. Change the range of the time parameter to [4 8] using the
'AnimationRange' property. Change the frame rate per unit time to 4 using the 'FrameRate'
property. Play the animation in the current figure by entering the following command.
playAnimation(gcf,'AnimationRange',[4 8],'FrameRate',4)
7-1189
7 Functions
fig = uifigure;
ax = uiaxes(fig);
7-1190
playAnimation
Add an animation object to the UI axes using fanimator. Create two symbolic variables, x and t.
Plot a curve that grows exponentially as a function of time t within the interval [0 3].
syms x t;
fanimator(ax,@fplot,exp(x),[0 t],'r','AnimationRange',[0 3])
7-1191
7 Functions
Play the animation in the UI figure fig by entering the command playAnimation(fig).
Alternatively, you can also use the command playAnimation(ax.Parent).
7-1192
playAnimation
Input Arguments
fig — Target figure
Figure object
Target figure, specified as a Figure object. For more information about Figure objects, see figure.
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: 'Backwards',true,'FrameRate',25
Range of the animation time parameter, specified as a two-element row vector. The two elements
must be real values that are increasing.
Example: [-2 4.5]
7-1193
7 Functions
Frame rate, specified as a positive value. The frame rate defines the number of frames per unit time
when playing the animation objects.
Example: 30
Backward option, specified as a logical value (boolean). If you specify the option true, then the
function plays the animation backwards.
Example: true
Speed factor, specified as a real nonzero value. The speed factor sets the ratio of one unit interval of
the animation time parameter to one second of clock time.
• If you specify a negative value for 'SpeedFactor' and keep the default value 0 (false) for
'Backwards' option, then the function plays the animation backwards with the specified speed
factor. For example, playAnimation('SpeedFactor',-1) launches the same animation as
playAnimation('Backwards',true).
• If you specify a zero value for 'SpeedFactor', then playAnimation('SpeedFactor',0)
launches a still frame indefinitely and does not play any animation.
Example: 2
Tips
• When you create a graph by using a plotting function, such as fplot, MATLAB creates a series of
graphics objects. You can then animate a specific property of the graphics objects by using the
fanimator and the playAnimation functions. Note that some functions, such as title and
xlabel, create text objects that cannot be animated. Instead, use the text function to create text
objects that can be animated.
Version History
Introduced in R2019a
See Also
animationToFrame | fanimator | rewindAnimation | writeAnimation
7-1194
plus, +
plus, +
Symbolic addition
Syntax
A + B
plus(A,B)
Description
A + B adds A and B.
plus(A,B) is equivalent to A + B.
Examples
Add Scalar to Array
syms x
A = [x sin(x) 3];
A + x
ans =
[ 2*x, x + sin(x), x + 3]
syms x
M = [x x^2;Inf 0];
M + eye(2)
ans =
[ x + 1, x^2]
[ Inf, 1]
plus(M,eye(2))
ans =
[ x + 1, x^2]
[ Inf, 1]
7-1195
7 Functions
g(x) = 3*x - 2;
h = f + g
h(x) =
x^2 + 8*x + 4
syms f(x)
f(x) = x^2 + 3*x + 2;
expr = x^2 - 2;
f(x) = f(x) + expr
f(x) =
2*x^2 + 3*x
Input Arguments
A — Input
symbolic scalar variable | symbolic matrix variable | symbolic function | symbolic matrix function |
symbolic expression | symbolic vector | symbolic matrix | symbolic array
Input, specified as a symbolic scalar variable, matrix variable, function, matrix function, expression,
or vector, matrix, or array of symbolic scalar variables.
B — Input
symbolic scalar variable | symbolic matrix variable | symbolic function | symbolic matrix function |
symbolic expression | symbolic vector | symbolic matrix | symbolic array
Input, specified as a symbolic scalar variable, matrix variable, function, matrix function, expression,
or vector, matrix, or array of symbolic scalar variables.
Tips
• All nonscalar arguments must be the same size. If one input argument is nonscalar, then plus
expands the scalar into an array of the same size as the nonscalar argument, with all elements
equal to the scalar.
Version History
Introduced before R2006a
7-1196
plus, +
See Also
ctranspose | ldivide | minus | mldivide | mpower | mrdivide | mtimes | power | rdivide |
times | transpose
7-1197
7 Functions
pochhammer
Pochhammer symbol
Syntax
pochhammer(x,n)
Description
pochhammer(x,n) returns the “Pochhammer Symbol” on page 7-1200 (x)n.
Examples
Find Pochhammer Symbol for Numeric and Symbolic Inputs
pochhammer(3,2)
ans =
12
Find the Pochhammer symbol for the symbolic input x at n = 3. The pochhammer function does not
automatically return the expanded form of the expression. Use expand to force pochhammer to
return the form of the expanded expression.
syms x
P = pochhammer(x, 3)
P = expand(P)
P =
pochhammer(x, 3)
P =
x^3 + 3*x^2 + 2*x
syms n x
assume(x>0)
assume(n>0)
P = pochhammer(x, n);
P = expand(P)
P =
gamma(n + x)/gamma(x)
To use the variables in further computations, clear their assumptions by recreating them using syms.
syms n x
7-1198
pochhammer
P = expand(pochhammer(x, 4));
P = factor(P)
P =
[ x, x + 3, x + 2, x + 1]
syms n x
diff(pochhammer(x,n),x)
ans =
pochhammer(x, n)*(psi(n + x) - psi(x))
diff(pochhammer(x,n),n,2)
ans =
pochhammer(x, n)*psi(n + x)^2 + pochhammer(x, n)*psi(1, n + x)
Use taylor to find the Taylor series expansion of pochhammer with n = 3 around the expansion
point x = 2.
syms x
taylor(pochhammer(x,3),x,2)
ans =
26*x + 9*(x - 2)^2 + (x - 2)^3 - 28
Plot the Pochhammer symbol from n = 0 to n = 4 for x. Use axis to display the region of interest.
syms x
fplot(pochhammer(x,0:4))
axis([-4 4 -4 4])
grid on
legend('n = 0','n = 1','n = 2','n = 3','n = 4','Location','Best')
title('Pochhammer symbol (x)_n for n=0 to n=4')
7-1199
7 Functions
Input Arguments
x — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
n — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
More About
Pochhammer Symbol
Γ x+n
x n = ,
Γx
7-1200
pochhammer
x n = x x + 1 ... x + n − 1
Algorithms
• If x and n are numerical values, then an explicit numerical result is returned. Otherwise, a
symbolic function call is returned.
• If both x and x + n are nonpositive integers, then
n Γ 1−x
x n = −1 .
Γ 1−x−n
• The following special cases are implemented.
x 0 =1
x 1 =x
1
x −1 =
x−1
1 n= Γ n+1
2 n = Γ n+2
• If n is a positive integer, then expand(pochhammer(x,n)) returns the expanded polynomial
x x + 1 ... x + n − 1 .
• If n is not an integer, then expand(pochhammer(x,n)) returns a representation in terms of
gamma.
Version History
Introduced in R2014b
See Also
factorial | gamma
7-1201
7 Functions
poles
Poles of expression or function
Syntax
P = poles(f,var)
P = poles(f,var,a,b)
[P,N] = poles( ___ )
[P,N,R] = poles( ___ )
Description
P = poles(f,var) finds the poles of f with respect to variable var.
[P,N,R] = poles( ___ ) returns the poles of f, their orders, and residues in R.
Examples
syms x
poles(1/(x-1i))
ans =
1i
poles(sin(x)/(x-1))
ans =
1
Find the poles of this expression. If you do not specify a variable, poles uses the default variable
determined by symvar.
syms x a
f = 1/((x-1)*(a-2));
poles(f)
ans =
1
7-1202
poles
syms x a
poles(f,a)
ans =
2
Find the poles of the tangent function in the interval (-pi, pi).
syms x
poles(tan(x), x, -pi, pi)
ans =
-pi/2
pi/2
The tangent function has an infinite number of poles. If you do not specify the interval, poles cannot
find all of them. It issues a warning and returns an empty symbolic object.
syms x
poles(tan(x))
If poles can prove that the input does not have poles in the interval, it returns empty without issuing
a warning.
syms x
poles(tan(x), x, -1, 1)
ans =
Empty sym: 0-by-1
Return orders along with poles by using two output arguments. Restrict the search interval to (-pi,
pi).
syms x
[Poles, Orders] = poles(tan(x)/(x-1)^3, x, -pi, pi)
Poles =
-pi/2
pi/2
1
Orders =
1
1
3
7-1203
7 Functions
Return the residues and orders along with the poles by specifying three output arguments.
syms x a
[Poles, Orders, Residues] = poles(a/(x^2*(x-1)), x)
Poles =
1
0
Orders =
1
2
Residues =
a
-a
Input Arguments
f — Input
symbolic expression | symbolic function.
Search interval for poles, specified as a vector of two real numeric or symbolic numbers (including
infinities).
Tips
• If poles cannot find all nonremovable singularities and cannot prove that they do not exist, it
issues a warning and returns an empty symbolic object.
• If poles can prove that the input does not have poles (in the specified interval or complex plane),
it returns empty without issuing a warning.
• a and b must be real numbers or infinities. If you provide complex numbers, poles uses an empty
interval and returns an empty symbolic object.
Version History
Introduced in R2012b
See Also
limit | solve | symvar | vpasolve
7-1204
poly2sym
poly2sym
Create symbolic polynomial from vector of coefficients
Syntax
p = poly2sym(c)
p = poly2sym(c,var)
Description
p = poly2sym(c) creates the symbolic polynomial expression p from the vector of coefficients c.
The polynomial variable is x. If c = [c1,c2,...,cn], then p = poly2sym(c) returns
c1xn − 1 + c2xn − 2 + ... + cn.
This syntax does not create the symbolic variable x in the MATLAB Workspace.
p = poly2sym(c,var) uses var as a polynomial variable when creating the symbolic polynomial
expression p from the vector of coefficients c.
Examples
Create Polynomial Expression
Create a polynomial expression from a symbolic vector of coefficients. If you do not specify a
polynomial variable, poly2sym uses x.
syms a b c d
p = poly2sym([a, b, c, d])
p =
a*x^3 + b*x^2 + c*x + d
p =
x^2/2 - x/3 + 1/4
Create a polynomial expression from a numeric vector of floating-point coefficients. The toolbox
converts floating-point coefficients to rational numbers before creating a polynomial expression.
p =
(3*x^2)/4 - x/2 + 1/4
Create a polynomial expression from a symbolic vector of coefficients. Use t as a polynomial variable.
7-1205
7 Functions
syms a b c d t
p = poly2sym([a, b, c, d], t)
p =
a*t^3 + b*t^2 + c*t + d
p1 = subs(p, t, t^2 + 1)
p2 = subs(p, t, exp(t))
p1 =
d + a*(t^2 + 1)^3 + b*(t^2 + 1)^2 + c*(t^2 + 1)
p2 =
d + c*exp(t) + a*exp(3*t) + b*exp(2*t)
Input Arguments
c — Polynomial coefficients
numeric vector | symbolic vector
Output Arguments
p — Polynomial
symbolic expression
Tips
• When you call poly2sym for a numeric vector c, the toolbox converts the numeric vector to a
vector of symbolic numbers using the default (rational) conversion mode of sym.
Version History
Introduced before R2006a
See Also
coeffs | sym | sym2poly
7-1206
polylog
polylog
Polylogarithm
Syntax
Li = polylog(n,x)
Description
Li = polylog(n,x) returns the polylogarithm of the order n and the argument x.
Examples
Polylogarithms of Numeric and Symbolic Arguments
polylog returns floating-point numbers or exact symbolic results depending on the arguments you
use.
Compute the polylogarithms of numeric input arguments. The polylog function returns floating-
point numbers.
Li =
-0.4726 0.3408 0.7697
Compute the polylogarithms of the same input arguments by converting them to symbolic objects. For
most symbolic (exact) numbers, polylog returns unresolved symbolic calls.
symA =
[ polylog(3, -1/2), polylog(4, 1/3), polylog(5, 3/4)]
Approximate the symbolic results with the default number of 32 significant digits by using vpa.
Li = vpa(symA)
Li =
[ -0.47259784465889687461862319312655,...
0.3407911308562507524776409440122,...
0.76973541059975738097269173152535]
The polylog function also accepts noninteger values of the order n. Compute polylog for complex
arguments.
Li = polylog(-0.2i,2.5)
Li =
-2.5030 + 0.3958i
7-1207
7 Functions
If the order of the polylogarithm is 0, 1, or a negative integer, then polylog returns an explicit
expression.
syms x
Li = polylog(1,x)
Li =
-log(1 - x)
Li = polylog(0,x)
Li =
-x/(x - 1)
Li = polylog(-1,x)
Li =
x/(x - 1)^2
Li = polylog(-2,x)
Li =
-(x^2 + x)/(x - 1)^3
Li = polylog(-3,x)
Li =
(x^3 + 4*x^2 + x)/(x - 1)^4
Li = polylog(-10,x)
Li =
-(x^10 + 1013*x^9 + 47840*x^8 + 455192*x^7 + ...
1310354*x^6 + 1310354*x^5 + 455192*x^4 +...
47840*x^3 + 1013*x^2 + x)/(x - 1)^11
Special Values
If the second argument is 0, then the polylogarithm is equal to 0 for any integer value of the first
argument. If the second argument is 1, then the polylogarithm is the Riemann zeta function of the
first argument.
syms n
Li = [polylog(n,0), polylog(n,1)]
Li =
[ 0, zeta(n)]
If the second argument is -1, then the polylogarithm has a special value for any integer value of the
first argument except 1.
7-1208
polylog
assume(n ~= 1)
Li = polylog(n,-1)
Li =
zeta(n)*(2^(1 - n) - 1)
syms n
Li =
[ pi^4/90, -(15*zeta(5))/16, catalan*1i - pi^2/48]
Plot Polylogarithms
Plot the polylogarithms of the integer orders n from -3 to 1 within the interval x = [-4 0.3].
syms x
for n = -3:1
fplot(polylog(n,x),[-4 0.3])
hold on
end
title('Polylogarithm')
legend('show','Location','best')
hold off
7-1209
7 Functions
Many functions, such as diff and int, can handle expressions containing polylog.
syms n x
dLi = diff(polylog(n, x), x)
dLi = diff(x*polylog(n, x), x)
dLi =
polylog(n - 1, x)/x
dLi =
polylog(n, x) + polylog(n - 1, x)
intLi =
polylog(n + 1, x)
intLi =
x*polylog(n, x)
7-1210
polylog
Input Arguments
n — Order of polylogarithm
number | array | symbolic number | symbolic variable | symbolic function | symbolic expression |
symbolic array
Order of the polylogarithm, specified as a number, array, symbolic number, symbolic variable,
symbolic function, symbolic expression, or symbolic array.
Data Types: single | double | sym | symfun
x — Argument of polylogarithm
number | array | symbolic number | symbolic variable | symbolic function | symbolic expression |
symbolic array
Argument of the polylogarithm, specified as a number, array, symbolic number, symbolic variable,
symbolic function, symbolic expression, or symbolic array.
Data Types: single | double | sym | symfun
More About
Polylogarithm
For a complex number z of modulus |z| < 1, the polylogarithm of order n is defined as:
∞
zk
Lin z = ∑ n
.
k=1k
Analytic continuation extends this function the whole complex plane, with a branch cut along the real
interval [1, ∞) for n ≥ 1.
Tips
• polylog(2,x) is equivalent to dilog(1 - x).
• The logarithmic integral function (the integral logarithm) uses the same notation, li(x), but without
an index. The toolbox provides the logint function to compute the logarithmic integral function.
• Floating-point evaluation of the polylogarithm function can be slow for complex arguments or
high-precision numbers. To increase the computational speed, you can reduce the floating-point
precision by using the vpa and digits functions. For more information, see “Increase Speed by
Reducing Precision” on page 3-321.
• The polylogarithm function is related to other special functions. For example, it can be expressed
in terms of the Hurwitz zeta function ζ(s,a) and the gamma function Γ(z):
Here, n ≠ 0, 1, 2, ....
Version History
Introduced in R2014b
7-1211
7 Functions
References
[1] Olver, F. W. J., A. B. Olde Daalhuis, D. W. Lozier, B. I. Schneider, R. F. Boisvert, C. W. Clark, B. R.
Miller, and B. V. Saunders, eds., Chapter 25. Zeta and Related Functions, NIST Digital Library
of Mathematical Functions, Release 1.0.20, Sept. 15, 2018.
See Also
dilog | log | logint | hurwitzZeta | zeta
7-1212
polynomialDegree
polynomialDegree
Degree of polynomial
Syntax
polynomialDegree(p)
polynomialDegree(p,vars)
Description
polynomialDegree(p) returns the degree of polynomial p with respect to all variables found in p
by symvar.
Examples
Degree of Polynomial
syms x
p = x^3 + x + 1;
deg = polynomialDegree(p)
deg =
3
Specify variables as the second argument of polynomialDegree. Find the degree of the polynomial
a^2*x^3 + b^6*x with the default independent variables found by symvar, the variable x, and the
variables [a x].
When using the default variables, the degree is 7 because, by default, a and b are variables. So the
total degree of b^6*x is 7.
syms a b x
p = a^2*x^3 + b^6*x;
deg = polynomialDegree(p) % uses symvar
deg =
7
deg = polynomialDegree(p,x)
deg =
3
7-1213
7 Functions
vars = [a x];
deg = polynomialDegree(p,vars)
deg =
5
Input Arguments
p — Polynomial
symbolic expression | symbolic function
Version History
Introduced in R2018a
See Also
coeffs | polynomialReduce
7-1214
polynomialReduce
polynomialReduce
Reduce polynomials by division
Syntax
r = polynomialReduce(p,d)
r = polynomialReduce(p,d,vars)
r = polynomialReduce( ___ ,'MonomialOrder',MonomialOrder)
Description
r = polynomialReduce(p,d) returns the “Polynomial Reduction” on page 7-1218 of p by d with
respect to all variables in p determined by symvar. The input d can be a vector of polynomials.
Examples
syms x y
p = x^3 - x*y^2 + 1;
d = x + y;
[r,q] = polynomialReduce(p,d)
r =
1
q =
x^2 - y*x
Reconstruct the original polynomial from the quotient and remainder. Check that the reconstructed
polynomial equals p by using isAlways.
7-1215
7 Functions
ans =
logical
1
r =
(exp(a) + 2)*y^2 + 1
r =
-x*y
q =
[ x^3 - x*y^3, x*y^3 - x*y]
Reconstruct the original polynomial from the quotient and remainder. Check that the reconstructed
polynomial equals p by using isAlways.
pOrig = expand(q*d.' + r);
isAlways(p == pOrig)
ans =
logical
1
By default, polynomialReduce orders the terms in the polynomials with the term order
degreeInverseLexicographic. Change the term order to lexicographic or
degreeLexicographic by using the 'MonomialOrder' name-value pair argument.
7-1216
polynomialReduce
d = x - y^2;
r = polynomialReduce(p,d,'MonomialOrder','lexicographic')
r =
y^4 + y^3 + 1
r =
x^2 + y*x + 1
Input Arguments
p — Polynomial to divide
symbolic expression | symbolic function
d — Polynomials to divide by
symbolic expression or function | vector of symbolic expressions or functions
Output Arguments
r — Remainder of polynomial division
symbolic polynomial
7-1217
7 Functions
More About
Polynomial Reduction
Polynomial reduction is the division of the polynomial p by the divisor polynomials d1, d2, …, dn . The
terms of the divisor polynomials are ordered according to a certain term order. The quotients q1, q2,
…, qn and the remainder r satisfy this equation.
No term in r can be divided by the leading terms of any of the divisors d1, d2, …, dn .
Version History
Introduced in R2018a
See Also
eliminate | gbasis | polynomialDegree
7-1218
potential
potential
Potential of vector field
Syntax
potential(V,X)
potential(V,X,Y)
Description
potential(V,X) computes the potential of the vector field V with respect to the vector X in
Cartesian coordinates. The vector field V must be a gradient field.
potential(V,X,Y) computes the potential of vector field V with respect to X using Y as base point
for the integration.
Examples
Compute Potential of Vector Field
Compute the potential of this vector field with respect to the vector [x, y, z]:
syms x y z
P = potential([x, y, z*exp(z)], [x y z])
P =
x^2/2 + y^2/2 + exp(z)*(z - 1)
simplify(gradient(P, [x y z]))
ans =
x
y
z*exp(z)
Compute the potential of this vector field specifying the integration base point as [0 0 0]:
syms x y z
P = potential([x, y, z*exp(z)], [x y z], [0 0 0])
P =
x^2/2 + y^2/2 + exp(z)*(z - 1) + 1
ans =
0
7-1219
7 Functions
ans =
NaN
Input Arguments
V — Vector field
3-D symbolic vector of symbolic expressions or functions (default)
X — Input
vector of three symbolic variables
Input, specified as a vector of three symbolic variables with respect to which you compute the
potential.
Y — Input
symbolic vector
Input, specified as a symbolic vector of variables, expressions, or numbers that you want to use as a
base point for the integration. If you use this argument, potential returns P(X) such that P(Y) =
0. Otherwise, the potential is only defined up to some additive constant.
More About
Scalar Potential of Gradient Vector Field
The potential of a gradient vector field V(X) = [v1(x1,x2,...),v2(x1,x2,...),...] is the scalar P(X) such that
V X = ∇P X .
The vector field is gradient if and only if the corresponding Jacobian is symmetrical:
∂vi ∂v j
=
∂x j ∂xi
Tips
• If potential cannot verify that V is a gradient field, it returns NaN.
• Returning NaN does not prove that V is not a gradient field. For performance reasons, potential
sometimes does not sufficiently simplify partial derivatives, and therefore, it cannot verify that the
field is gradient.
7-1220
potential
• If Y is a scalar, then potential expands it into a vector of the same length as X with all elements
equal to Y.
Version History
Introduced in R2012a
See Also
curl | diff | divergence | gradient | jacobian | hessian | laplacian | vectorPotential
7-1221
7 Functions
power, .^
Symbolic array power
Syntax
A.^B
power(A,B)
Description
A.^B computes A to the B power and is an element-wise operation.
Examples
Square Each Matrix Element
A =
[ a1_1, a1_2, a1_3]
[ a2_1, a2_2, a2_3]
ans =
[ a1_1^2, a1_2^2, a1_3^2]
[ a2_1^2, a2_2^2, a2_3^2]
H =
[ 1, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
d =
[ 1, 0, 0]
[ 0, 2, 0]
[ 0, 0, 3]
Raise the elements of the Hilbert matrix to the powers of the diagonal matrix. The base and the
exponent must be matrices of the same size.
7-1222
power, .^
H.^d
ans =
[ 1, 1, 1]
[ 1, 1/9, 1]
[ 1, 1, 1/125]
Input Arguments
A — Input
number | symbolic number | symbolic scalar variable | symbolic function | symbolic matrix function |
symbolic expression | symbolic vector | symbolic matrix | symbolic array
Input, specified as a number or a symbolic number, scalar variable, matrix variable, function, matrix
function, expression, or vector, matrix, or array of symbolic scalar variables. Inputs A and B must be
the same size unless one is a scalar. A scalar value expands into an array of the same size as the other
input.
B — Input
number | symbolic number | symbolic scalar variable | symbolic function | symbolic matrix function |
symbolic expression | symbolic vector | symbolic matrix | symbolic array
Input, specified as a number or a symbolic number, scalar variable, matrix variable, function, matrix
function, expression, or vector, matrix, or array of symbolic scalar variables. Inputs A and B must be
the same size unless one is a scalar. A scalar value expands into an array of the same size as the other
input.
Version History
Introduced before R2006a
See Also
ctranspose | ldivide | minus | mldivide | mpower | mrdivide | mtimes | nthroot | plus |
rdivide | times | transpose
7-1223
7 Functions
powermod
Modular exponentiation
Syntax
c = powermod(a,b,m)
Description
c = powermod(a,b,m) returns the modular exponentiation ab mod m. The input a,b must be
integers, and m must be a nonnegative integer. For more information, see “Modular Exponentiation”
on page 7-1225.
Examples
Compute the modular exponentiation ab mod m by using powermod. The powermod function is
efficient because it does not calculate the exponential ab.
c = powermod(3,5,7)
c =
5
Fermat's little theorem states that if p is prime and a is not divisible by p, then a(p–1) mod p is 1.
p = 5;
a = 3;
c = powermod(a,p-1,p)
c =
1
Test the same case for all values of a less than p. The function powermod acts element-wise to return
a vector of ones.
p = 5;
a = 1:p-1;
c = powermod(a,p-1,p)
c =
1 1 1 1
7-1224
powermod
Fermat's little theorem states that if p is a prime number and a is not divisible by p, then a(p–1) mod p
is 1. On the contrary, if a(p–1) mod p is 1 and a is not divisible by p, then p is not always a prime
number (p can be a pseudoprime).
Test numbers from 300 to 400 for primality by using Fermat's little theorem with base 2.
p = 300:400;
remainder = powermod(2,p-1,p);
primesFermat = p(remainder == 1)
primesFermat =
307 311 313 317 331 337 341 347 349 353...
359 367 373 379 383 389 397
Find Fermat pseudoprimes by comparing the results with isprime. 341 is a Fermat pseudoprime.
primeNumbers = p(isprime(p));
setdiff(primesFermat,primeNumbers)
ans =
341
Input Arguments
a — Base
number | vector | matrix | array | symbolic number | symbolic array
Base, specified as a number, vector, matrix, array, or a symbolic number or array. a must be an
integer.
b — Exponent or power
number | vector | matrix | array | symbolic number | symbolic array
Exponent or power, specified as a number, vector, matrix, array, or a symbolic number or array. b
must be an integer.
m — Divisor
number | vector | matrix | array | symbolic number | symbolic array
Divisor, specified as a number, vector, matrix, array, or a symbolic number or array. m must be a
nonnegative integer.
More About
Modular Exponentiation
For a negative exponent b, the definition can be extended by finding the modular multiplicative
inverse d of a modulo m, that is
c = d ‒b mod m.
7-1225
7 Functions
ad mod m = 1.
Version History
Introduced in R2018a
See Also
mod | nextprime | nthprime | prevprime
7-1226
pretty
pretty
Prettyprint symbolic expressions
Note pretty is not recommended. Use Live Scripts instead. Live Scripts provide full math rendering
while pretty uses plain-text formatting. See “What Is a Live Script or Function?”
Syntax
pretty(X)
Description
pretty(X) prints X in a plain-text format that resembles typeset mathematics. For true typeset
rendering, use Live Scripts instead. See “What Is a Live Script or Function?”
Examples
A = sym(pascal(2))
B = eig(A)
pretty(B)
A =
[ 1, 1]
[ 1, 2]
B =
3/2 - 5^(1/2)/2
5^(1/2)/2 + 3/2
/ 3 sqrt(5) \
| - - ------- |
| 2 2 |
| |
| sqrt(5) 3 |
| ------- + - |
\ 2 2 /
Solve this equation, and then use pretty to represent the solutions in the format similar to typeset
mathematics. For better readability, pretty uses abbreviations when representing long expressions.
7-1227
7 Functions
syms x
s = solve(x^4 + 2*x + 1, x,'MaxDegree',3);
pretty(s)
/ -1 \
| |
| 2 1 |
| #2 - ---- + - |
| 9 #2 3 |
| |
| 1 #2 1 |
| ---- - #1 - -- + - |
| 9 #2 2 3 |
| |
| 1 #2 1 |
| #1 + ---- - -- + - |
\ 9 #2 2 3 /
where
/ 2 \
sqrt(3) | ---- + #2 | 1i
\ 9 #2 /
#1 == ------------------------
2
Input Arguments
X — Input
symbolic number | symbolic scalar variable | symbolic matrix variable | symbolic array | symbolic
function | symbolic matrix function | symbolic expression
Input, specified as a symbolic number, scalar variable, matrix variable, array, function, matrix
function, or expression.
Version History
Introduced before R2006a
7-1228
prevprime
prevprime
Previous prime number
Syntax
prevprime(n)
Description
prevprime(n) returns the largest prime number smaller than or equal to n. If n is a vector or
matrix, then prevprime acts element-wise on n.
Examples
Find Previous Prime Number
prevprime(100)
ans =
97
Find the largest prime numbers smaller than 1000, 10000, and 100000 by specifying the input as a
vector.
ans =
997 9973 99991
When finding large prime numbers, return exact symbolic integers by using symbolic input. Further,
if your input has 15 or more digits, then use quotation marks and wrap the number in sym to
represent the number accurately. For more information, see “Numeric to Symbolic Conversion” on
page 2-29.
prevprime(10^sym(18))
ans =
999999999999999989
prevprime(sym('823572345728582545'))
ans =
823572345728582543
7-1229
7 Functions
Input Arguments
n — Input
number | vector | matrix | array | symbolic number | symbolic array
Version History
Introduced in R2016b
See Also
isprime | nextprime | nthprime | primes
7-1230
psi
psi
Digamma function
Syntax
psi(x)
psi(k,x)
Description
psi(x) computes the digamma function on page 7-1233 of x.
psi(k,x) computes the polygamma function on page 7-1233 of x, which is the kth derivative of the
digamma function at x.
Examples
Compute Digamma and Polygamma for Numeric Inputs
Compute the digamma and polygamma functions for these numbers. Because these numbers are not
symbolic objects, you get the floating-point results.
ans =
-1.9635 -16.8288 -0.1248 2.0372
Compute the digamma and polygamma functions for the numbers converted to symbolic objects.
ans =
[ - eulergamma - 2*log(2), pi^2/2, - eulergamma - pi/2 - 3*log(2)]
For some symbolic (exact) numbers, psi returns unresolved symbolic calls.
psi(sym(sqrt(2)))
ans =
psi(2^(1/2))
Compute the derivatives of these expressions containing the digamma and polygamma functions.
syms x
diff(psi(1, x^3 + 1), x)
diff(psi(sin(x)), x)
ans =
3*x^2*psi(2, x^3 + 1)
7-1231
7 Functions
ans =
cos(x)*psi(1, sin(x))
syms x
expand(psi(2*x + 3))
expand(psi(x + 2)*psi(x))
ans =
psi(x + 1/2)/2 + log(2) + psi(x)/2 +...
1/(2*x + 1) + 1/(2*x + 2) + 1/(2*x)
ans =
psi(x)/x + psi(x)^2 + psi(x)/(x + 1)
Compute the limits for expressions containing the digamma and polygamma functions.
syms x
limit(x*psi(x), x, 0)
limit(psi(3, x), x, inf)
ans =
-1
ans =
0
ans =
[ Inf, Inf]
[ - eulergamma - (3*log(3))/2 - (pi*3^(1/2))/6, - eulergamma - 2*log(2)]
ans =
[ -eulergamma, Inf]
Compute the polygamma function for elements of matrix M and vector V. The psi function acts
elementwise on nonscalar inputs.
7-1232
psi
ans =
[ Inf, 0]
[ - 26*zeta(3) - (4*3^(1/2)*pi^3)/9, -14*zeta(3)]
ans =
[ -720*zeta(7), 0]
Because all elements of polyGammaV have the same value, you can replace polyGammaV by a scalar
of that value. psi expands the scalar into a nonscalar of the same size as V and computes the result.
V = sym([1, inf]);
psi(6,V)
ans =
[ -720*zeta(7), 0]
Input Arguments
x — Input
symbolic number | symbolic variable | symbolic expression | symbolic array
k — Input
nonnegative integer | nonnegative integer or vector, matrix or multidimensional array of nonnegative
integers.
More About
Digamma Function
The digamma function is the first derivative of the logarithm of the gamma function:
d Γ′ x
ψx = lnΓ x =
dx Γx
Polygamma Function
The polygamma function of the order k is the (k + 1)th derivative of the logarithm of the gamma
function:
k+1 k
d d
ψk x = k + 1
lnΓ x = k ψ x
dx dx
Tips
• Calling psi for a number that is not a symbolic object invokes the MATLAB psi function. This
function accepts real nonnegative arguments x. If you want to compute the polygamma function
for a complex number, use sym to convert that number to a symbolic object, and then call psi for
that symbolic object.
7-1233
7 Functions
Version History
Introduced in R2011b
See Also
beta | gamma | nchoosek | factorial
7-1234
qr
qr
QR decomposition of symbolic matrix
Syntax
R = qr(A)
[Q,R] = qr(A)
[Q,R,P] = qr(A)
[ ___ ] = qr(A,"econ")
[Q,R,P] = qr( ___ ,outputForm)
[ ___ ] = qr(A,0)
[C,R] = qr(A,B)
[C,R,P] = qr(A,B)
[ ___ ] = qr(A,B,"econ")
[C,R,P] = qr( ___ ,outputForm)
[ ___ ] = qr(A,B,0)
Description
R = qr(A) returns the R factor of the QR decomposition on page 7-1245 A = Q*R. Here, A is an m-
by-n symbolic matrix, R is an m-by-n upper triangular symbolic matrix, and Q is an m-by-m unitary
symbolic matrix.
[Q,R] = qr(A) returns an upper triangular matrix R and a unitary matrix Q such that A = Q*R.
[Q,R,P] = qr(A) also returns a permutation matrix P such that A*P = Q*R. If all elements of A
can be approximated by floating-point numbers, then this syntax chooses the permutation matrix P so
that abs(diag(R)) is decreasing. Otherwise, it returns P = eye(n).
[ ___ ] = qr(A,"econ") returns the economy-size decomposition using any of the previous output
argument combinations. The sizes of the outputs depend on the size of m-by-n matrix A:
• If m > n, then qr computes only the first n columns of Q and the first n rows of R.
• If m ≤ n, then the economy-size decomposition is the same as the QR decomposition without the
"econ" option.
By default, when you use "econ", qr returns the permutation information as a matrix P.
[Q,R,P] = qr( ___ ,outputForm) specifies whether to return the permutation information P as a
matrix or a vector. For example, if outputForm is "vector", then A(:,P) = Q*R. The default value
of outputForm is "matrix" such that A*P = Q*R.
[C,R] = qr(A,B) returns an upper triangular matrix R and a matrix C such that C = Q'*B and A =
Q*R. Here, A and B must have the same number of rows.
7-1235
7 Functions
[C,R,P] = qr(A,B) also returns a permutation matrix P such that A*P = Q*R. If all elements of A
can be approximated by floating-point numbers, then this syntax chooses the permutation matrix P so
that abs(diag(R)) is decreasing. Otherwise, it returns P = eye(n).
[ ___ ] = qr(A,B,"econ") returns the economy-size decomposition using any of the previous
output argument combinations. The sizes of the outputs depend on the size of m-by-n matrix A:
By default, when you use "econ", qr returns the permutation information as a matrix P.
[C,R,P] = qr( ___ ,outputForm) specifies whether to return the permutation information P as a
matrix or a vector. For example, if outputForm is "vector", then the solution of the matrix equation
A*X = B is X(P,:) = R\C. The default value of outputForm is "matrix" such that the solution to
A*X = B is X = P*(R\C).
___ = qr( ___ ,"real") assumes that the input arguments and intermediate results are real, and
therefore, suppresses calls to abs and conj. When you use this option, qr assumes that all symbolic
variables represent real numbers. All numeric arguments should be real numbers for this syntax.
Examples
Compute the upper triangular R factor of the QR decomposition of the 4-by-4 Wilkinson's eigenvalue
test matrix.
A = sym(wilkinson(4))
A =
3
1 0 0
2
1
1 1 0
2
1
0 1 1
2
3
0 0 1
2
7-1236
qr
R = qr(A)
R =
13 4 13 2 13
0
2 13 13
13 53 10 13 53 2 13 53
0
26 689 53
53 381 172 53 381
0 0
106 20193
35 381
0 0 0
762
A = sym(pascal(3))
A =
111
123
136
[Q,R] = qr(A)
Q =
3 2 6
−
3 2 6
3 6
0 −
3 3
3 2 6
3 2 6
R =
10 3
32 3
3
5 2
0 2
2
6
0 0
6
TF = isAlways(A == Q*R)
1 1 1
1 1 1
7-1237
7 Functions
1 1 1
Permuted QR Decomposition
Use permutations to improve the numerical stability of the QR decomposition for floating-point
matrices. The qr function returns permutation information either as a matrix or as a vector.
Set the number of significant decimal digits, used for variable-precision arithmetic, to 10.
Approximate the 3-by-3 symbolic Hilbert matrix with floating-point numbers.
previoussetting = digits(10);
A = vpa(hilb(3))
A =
1.0 0.5 0.3333333333
0.5 0.3333333333 0.25
0.3333333333 0.25 0.2
[Q,R] = qr(A)
Q =
0.8571428571 −0.5016049166 0.1170411472
0.4285714286 0.5684855721 −0.7022468832
0.2857142857 0.6520863915 0.7022468832
R =
1.166666667 0.6428571429 0.45
0 0.1017143303 0.1053370325
0 0 0.003901371573
Compute the difference between A and Q*R. The computed Q and R matrices do not strictly satisfy the
equality A = Q*R because of round-off errors.
E = A - Q*R
E =
−3.469446952e−18 −6.938893904e−18 −4.33680869e−18
0 −1.734723476e−18 −8.67361738e−19
0 −8.67361738e−19 −4.33680869e−19
To increase numerical stability of the QR decomposition, use permutations by specifying the syntax
with three output arguments. For matrices that do not contain symbolic variables, expressions, or
functions, this syntax triggers pivoting so that abs(diag(R)) in the returned matrix R is decreasing.
[Q,R,P] = qr(A)
Q =
0.8571428571 −0.4969293466 −0.1355261854
0.4285714286 0.5421047417 0.7228063223
0.2857142857 0.6776309272 −0.6776309272
7-1238
qr
R =
1.166666667 0.45 0.6428571429
0 0.1054092553 0.1016446391
0 0 0.003764616262
P = 3×3
1 0 0
0 0 1
0 1 0
Check the equality A*P = Q*R. QR decomposition with permutations results in smaller round-off
errors.
E = A*P - Q*R
E =
−3.469446952e−18 −4.33680869e−18 −6.938893904e−18
0 −8.67361738e−19 −1.734723476e−18
0 −4.33680869e−19 −1.734723476e−18
Now, return the permutation information as a vector by using the "vector" argument.
[Q,R,p] = qr(A,"vector")
Q =
0.8571428571 −0.4969293466 −0.1355261854
0.4285714286 0.5421047417 0.7228063223
0.2857142857 0.6776309272 −0.6776309272
R =
1.166666667 0.45 0.6428571429
0 0.1054092553 0.1016446391
0 0 0.003764616262
p = 1×3
1 3 2
E = A(:,p) - Q*R
E =
−3.469446952e−18 −4.33680869e−18 −6.938893904e−18
0 −8.67361738e−19 −1.734723476e−18
0 −4.33680869e−19 −1.734723476e−18
A = sym(hilb(3));
[Q,R] = qr(A);
E = A - Q*R
E =
7-1239
7 Functions
000
000
000
digits(previoussetting)
Solve the system of equations A*X = b, where A is a 5-by-5 symbolic matrix and b is a 5-by-1
symbolic vector.
A = sym(invhilb(5))
A =
25 −300 1050 −1400 630
−300 4800 −18900 26880 −12600
1050 −18900 79380 −117600 56700
−1400 26880 −117600 179200 −88200
630 −12600 56700 −88200 44100
b = sym([1:5]')
b =
1
2
3
4
5
[C,R] = qr(A,b);
X = R\C
X =
5
71
20
197
70
657
280
1271
630
7-1240
qr
tf = isAlways(A*X == b)
1
1
1
1
1
When solving systems of equations that contain floating-point numbers, use QR decomposition with a
permutation matrix or vector.
Solve the system of equations A*X = b, where A is a 3-by-3 symbolic matrix with variable precision
and b is a 3-by-1 symbolic vector with variable precision. Find matrices C and R such that C = Q'*b
and A = Q*R.
previoussetting = digits(10);
A = vpa([2 -3 -1; 1 1 -1; 0 1 -1]);
b = vpa([2; 0; -1]);
[C,R,P] = qr(A,b)
C =
−2.110579412
−0.2132007164
0.7071067812
R =
3.31662479 0.3015113446 −1.507556723
0 1.705605731 −1.492405014
0 0 0.7071067812
P = 3×3
0 0 1
1 0 0
0 1 0
X = P*(R\C)
X =
1.0
−0.25
0.75
[C,R,p] = qr(A,b,"vector")
7-1241
7 Functions
C =
−2.110579412
−0.2132007164
0.7071067812
R =
3.31662479 0.3015113446 −1.507556723
0 1.705605731 −1.492405014
0 0 0.7071067812
p = 1×3
2 3 1
X(p,:) = R\C
X =
1.0
−0.25
0.75
digits(previoussetting)
Economy-Size QR Decomposition
Create a matrix that consists of the first two columns of the 4-by-4 Pascal matrix.
A = sym(pascal(4));
A = A(:,1:2)
A =
1 1
1 2
1 3
1 4
[Q,R] = qr(A)
Q =
7-1242
qr
1 3 10
−σ1 0
2 10
1 5 2 3 10 6
− −
2 10 15 6
1 5 3 10 6
− −
2 10 30 3
1 3 10 6
σ1
2 15 6
where
3 5
σ1 =
10
R =
2 5
0 5
0 0
0 0
Now, compute the economy-size QR decomposition for this matrix. Because the number of rows is
greater than the number of columns in A, qr computes only the first 2 columns of Q and the first 2
rows of R.
[Q,R] = qr(A,"econ")
Q =
1 3 5
−
2 10
1 5
−
2 10
1 5
2 10
1 3 5
2 10
R =
2 5
0 5
You can avoid complex conjugates in the result of QR decomposition by using the "real" option.
syms x
A = [1 2; 3 x]
A =
12
3 x
7-1243
7 Functions
Compute the QR decomposition of this matrix. By default, qr assumes that x represents a complex
number, and therefore, the result contains expressions with the abs function.
[Q,R] = qr(A)
Q =
3x 9
10 10
−5
−
10 σ1
x 3
3 10 10
−5
10 σ1
where
x 3 2 3x 9 2
σ1 = − + −
10 5 10 5
R =
10 3 x + 2
10
10
x 3 2 3x 9 2
0 − + −
10 5 10 5
When you use the "real" option, qr assumes that all symbolic variables represent real numbers and
can return shorter results.
[Q,R] = qr(A,"real")
Q =
3x 9
10 10
−5
−
10 x2 6x 18
10
− 5 + 5
x 3
3 10 10
−5
10 x2 6x 18
10
− 5 + 5
R =
10 3 x + 2
10
10
x2 6 x 18
0 − +
10 5 5
Input Arguments
A — Symbolic input
m-by-n symbolic matrix
B — Symbolic input
symbolic vector | symbolic matrix
Symbolic input, specified as a symbolic vector or matrix. B must have the same number of rows as A.
7-1244
qr
Shape of the permutation output, specified as "matrix" or "vector". This option controls whether
the permutation output P is returned as a permutation matrix or vector. You must specify three output
arguments to qr to use this option.
Output Arguments
R — R factor of QR decomposition
upper triangular symbolic matrix
R factor of the QR decomposition, returned as an upper triangular symbolic matrix that satisfies A =
Q*R for an m-by-n matrix A.
Q — Q factor of QR decomposition
unitary symbolic matrix
Q factor of the QR decomposition, returned as a unitary symbolic matrix that satisfies A = Q*R for an
m-by-n matrix A.
P — Permutation information
matrix | vector
Linear system factor, returned as a symbolic matrix representing the solution of the matrix equation
A*X = B, such that C = Q'*B and X = R\C. If you specify the permutation output P, then the
solution is either X = P*(R\C) when outputForm is "matrix" or X(P,:) = R\C when
outputForm is "vector".
More About
QR Decomposition of Matrix
7-1245
7 Functions
Tips
• The upper triangular matrix R satisfies the condition R = chol(A'*A).
• The arguments "econ" and 0 affect only the shape of the returned matrices.
• Calling qr for numeric matrices that are not symbolic objects (not created by sym, syms, or vpa)
invokes the MATLAB qr function.
• Matrix computations involving many symbolic variables can be slow. To increase the
computational speed, reduce the number of symbolic variables by substituting the given values for
some variables.
Version History
Introduced in R2014a
See Also
chol | eig | lu | svd
7-1246
quorem
quorem
Quotient and remainder
Syntax
[Q,R] = quorem(A,B,var)
[Q,R] = quorem(A,B)
Description
[Q,R] = quorem(A,B,var) divides A by B and returns the quotient Q and remainder R of the
division, such that A = Q*B + R. This syntax regards A and B as polynomials in the variable var.
If A and B are matrices, quorem performs elements-wise division, using var as a variable. It returns
the quotient Q and remainder R of the division, such that A = Q.*B + R.
If both symvar(A,1) and symvar(B,1) are empty, then A and B must both be integers or matrices
with integer elements. In this case, quorem(A,B) returns symbolic integers Q and R, such that A =
Q*B + R. If A and B are matrices, then Q and R are symbolic matrices with integer elements, such
that A = Q.*B + R, and each element of R is smaller in absolute value than the corresponding
element of B.
Examples
Divide Multivariate Polynomials
Compute the quotient and remainder of the division of these multivariate polynomials with respect to
the variable y:
syms x y
p1 = x^3*y^4 - 2*x*y + 5*x + 1;
p2 = x*y;
[q, r] = quorem(p1, p2, y)
q =
x^2*y^3 - 2
r =
5*x + 1
Compute the quotient and remainder of the division of these univariate polynomials:
syms x
p = x^3 - 2*x + 5;
[q, r] = quorem(x^5, p)
7-1247
7 Functions
q =
x^2 + 2
r =
- 5*x^2 + 4*x - 10
Divide Integers
q =
101
r =
515
Input Arguments
A — Dividend (numerator)
symbolic integer | polynomial | symbolic vector | symbolic matrix
B — Divisor (denominator)
symbolic integer | polynomial | symbolic vector | symbolic matrix
Output Arguments
Q — Quotient of the division
symbolic integer | symbolic expression | symbolic vector | symbolic matrix
Quotient of the division, returned as a symbolic integer, expression, or a vector or matrix of symbolic
integers or expressions.
Version History
Introduced before R2006a
7-1248
quorem
See Also
deconv | mod
7-1249
7 Functions
rank
Find rank of symbolic matrix
Syntax
rank(A)
Description
rank(A) returns the rank of symbolic matrix A.
Examples
Find Rank of Matrix
syms a b c d
A = [a b; c d];
rank(A)
ans =
2
Symbolic calculations return the exact rank of a matrix while numeric calculations can suffer from
round-off errors. This exact calculation is useful for ill-conditioned matrices, such as the Hilbert
matrix. The rank of a Hilbert matrix of order n is n.
Find the rank of the Hilbert matrix of order 15 numerically. Then convert the numeric matrix to a
symbolic matrix using sym and find the rank symbolically.
H = hilb(15);
rank(H)
rank(sym(H))
ans =
12
ans =
15
The symbolic calculation returns the correct rank of 15. The numeric calculation returns an incorrect
rank of 12 due to round-off errors.
2
1 − sin x cos2 x
A= .
1 1
7-1250
rank
After simplification of 1-sin(x)^2 to cos(x)^2, the matrix has a rank of 1. However, rank returns
an incorrect rank of 2 because it does not take into account identities satisfied by special functions
occurring in the matrix elements. Demonstrate the incorrect result.
syms x
A = [1-sin(x) cos(x); cos(x) 1+sin(x)];
rank(A)
ans =
2
rank returns an incorrect result because the outputs of intermediate steps are not simplified. While
there is no fail-safe workaround, you can simplify symbolic expressions by using numeric substitution
and evaluating the substitution using vpa.
Find the correct rank by substituting x with a number and evaluating the result using vpa.
rank(vpa(subs(A,x,1)))
ans =
1
However, even after numeric substitution, rank can return incorrect results due to round-off errors.
Input Arguments
A — Input
number | vector | matrix | symbolic number | symbolic vector | symbolic matrix
Version History
Introduced before R2006a
See Also
eig | null | rref
7-1251
7 Functions
rat
Rational fraction approximation (continued fraction)
Syntax
R = rat(X)
R = rat(X,tol)
Description
R = rat(X) returns the rational fraction approximation of X to within the default tolerance,
1.e-6*norm(X(:),1). The approximation is a character array containing the simple continued
fraction on page 7-1257 with finite terms.
[N,D] = rat( ___ ) returns two arrays, N and D, such that N./D approximates X. You can use this
output syntax with any of the previous input syntaxes.
___ = rat( ___ ,Name,Value) uses additional options specified by one or more Name,Value pair
arguments to approximate X.
Examples
X = sqrt(sym(3))
X = 3
Find the rational fraction approximation (truncated continued fraction) of this number. The resulting
expression is a character vector.
R = rat(X)
R =
'2 + 1/(-4 + 1/(4 + 1/(-4 + 1/(4 + 1/(-4)))))'
A rational approximation of X is
7-1252
rat
1
2+ 1
−4 + 1
4+
1
−4 +
1
4+
−4
X = sym(pi)
X = π
Xdec = vpa(X,12)
Xdec = 3.14159265359
Find the rational fraction approximation of π using the rat function with default tolerance. The
resulting expression is a character vector.
R = rat(sym(pi))
R =
'3 + 1/(7 + 1/(16))'
Use str2sym to turn the character vector into a single fractional number.
Q = str2sym(R)
Q =
355
113
Show the decimal representation of the fractional number 355/113. This approximation agrees with π
to 6 decimal places.
Qdec = vpa(Q,12)
Qdec = 3.14159292035
R = rat(sym(pi),1e-8)
R =
'3 + 1/(7 + 1/(16 + 1/(-294)))'
Q = str2sym(R)
Q =
104348
33215
7-1253
7 Functions
Qdec = 3.14159265392
Solve the equation cos(x) + x2 + x = 42 using vpasolve. The solution is returned in decimal
representation.
syms x
sol = vpasolve(cos(x) + x^2 + x == 42)
sol = 5.9274875551262136192212919837749
R =
'6 + 1/(-14 + 1/(5 + 1/(-5)))'
To extract the coefficients in the denominator of the continued fraction, you can use the regexp
function and convert them to a character array.
S = char(regexp(R,'(-*\d+','match'))
coeffs =
−14
5
−5
Use str2sym to turn the continued fraction R into a single fractional number.
Q = str2sym(R)
Q =
1962
331
You can also return the numerator and denominator of the rational approximation by specifying two
output arguments for the rat function.
[N,D] = rat(sol)
N = 1962
7-1254
rat
D = 331
X = (sym(1) + sqrt(5))/ 2
X =
5 1
+
2 2
R = rat(X,1e-4)
R =
'2 + 1/(-3 + 1/(3 + 1/(-3 + 1/(3 + 1/(-3)))))'
To return the rational approximation with 10 coefficients, set the 'Length' option to 10. This option
ignores the specified tolerance in the approximation.
R10 = rat(X,1e-4,'Length',10)
R10 =
'2 + 1/(-3 + 1/(3 + 1/(-3 + 1/(3 + 1/(-3 + 1/(3 + 1/(-3 + 1/(3 + 1/(-3)))))))))'
To return the rational approximation with all positive coefficients, set the 'Positive' option to
true.
Rpos = rat(X,1e-4,'Positive',true)
Rpos =
'1 + 1/(1 + 1/(1 + 1/(1 + 1/(1 + 1/(1 + 1/(1 + 1/(1 + 1/(1 + 1/(1 + 1/(1))))))))))'
Input Arguments
X — Input
number | vector | matrix | array | symbolic number | symbolic array
Input, specified as a number, vector, matrix, array, symbolic number, or symbolic array.
Data Types: single | double | sym
Complex Number Support: Yes
tol — Tolerance
scalar
Tolerance, specified as a scalar. N and D approximate X, such that N./D - X < tol. The default
tolerance is 1e-6*norm(X(:),1).
7-1255
7 Functions
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: 'Length',5,'Positive',true
Number of coefficients or terms of the continued fraction, specified as a positive integer. Specifying
this option overrides the tolerance argument tol.
Example: 5
Option to return positive coefficients, specified as a logical value (boolean). If you specify true, then
rat returns a regular continued fraction expansion with all positive integers in the denominator.
Example: true
Output Arguments
R — Continued fraction
character array
• If X is an array of m elements and all elements are real numbers, then R is returned as a character
array with m rows.
• If X is an array of m elements that contains a complex number, then R is returned as a character
array with 2m+1 rows. The first m rows of R represent the continued fraction expansion of the
real parts of X, followed by ' +i* ... ' in the (m+1)-th row, and the last m rows represent the
continued fraction expansions of the imaginary parts of X.
N — Numerator
number | vector | matrix | array | symbolic number | symbolic array
Numerator, returned as a number, vector, matrix, array, symbolic number, or symbolic array. N./D
approximates X.
D — Denominator
number | vector | matrix | array | symbolic number | symbolic array
Denominator, returned as a number, vector, matrix, array, symbolic number, or symbolic array. N./D
approximates X.
7-1256
rat
Limitations
• You can only specify the Name,Value arguments, such as 'Length',5,'Positive',true, if
the array X contains a symbolic number or the data type of X is sym.
More About
Simple Continued Fraction
The rat function approximates each element of X by a simple continued fraction of the form
N 1
R= = a1 +
D a2 +
1
1
⋱ +
ak
with a finite number of integer terms a1, a2, …, ak. The accuracy of the rational approximation
increases with the number of terms.
Version History
Introduced in R2020a
See Also
format | vpa | sym
7-1257
7 Functions
rdivide, ./
Symbolic array right division
Syntax
A./B
rdivide(A,B)
Description
A./B divides A by B.
Examples
Divide Scalar by Matrix
B = sym('b', [2 3])
B =
[ b1_1, b1_2, b1_3]
[ b2_1, b2_2, b2_3]
syms a
sin(a)./B
ans =
[ sin(a)/b1_1, sin(a)/b1_2, sin(a)/b1_3]
[ sin(a)/b2_1, sin(a)/b2_2, sin(a)/b2_3]
H = sym(hilb(3))
d = diag(sym([1 2 3]))
H =
[ 1, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
d =
[ 1, 0, 0]
[ 0, 2, 0]
[ 0, 0, 3]
7-1258
rdivide, ./
Divide d by H by using the elementwise right division operator .\. This operator divides each element
of the first matrix by the corresponding element of the second matrix. The dimensions of the matrices
must be the same.
d./H
ans =
[ 1, 0, 0]
[ 0, 6, 0]
[ 0, 0, 15]
syms f(x)
f(x) = x^2;
f1 = (x^2 + 5*x + 6)./f
f1(x) =
(x^2 + 5*x + 6)/x^2
Input Arguments
A — Input
symbolic scalar variable | symbolic matrix variable | symbolic function | symbolic matrix function |
symbolic expression | symbolic vector | symbolic matrix | symbolic array
Input, specified as a symbolic scalar variable, matrix variable, function, matrix function, expression,
or vector, matrix, or array of symbolic scalar variables. Inputs A and B must be the same size unless
one is a scalar. A scalar value expands into an array of the same size as the other input.
B — Input
symbolic scalar variable | symbolic matrix variable | symbolic function | symbolic matrix function |
symbolic expression | symbolic vector | symbolic matrix | symbolic array
Input, specified as a symbolic scalar variable, matrix variable, function, matrix function, expression,
or vector, matrix, or array of symbolic scalar variables. Inputs A and B must be the same size unless
one is a scalar. A scalar value expands into an array of the same size as the other input.
Version History
Introduced before R2006a
7-1259
7 Functions
See Also
ctranspose | ldivide | minus | mldivide | mpower | mrdivide | mtimes | plus | power | times
| transpose
7-1260
read
read
(Not recommended) Read MuPAD program file into symbolic engine
Syntax
read(symengine,filename)
Description
read(symengine,filename) reads the MuPAD program file filename into the symbolic engine.
Reading a program file means finding and executing it.
Examples
Read MuPAD Program File into Symbolic Engine
Suppose you wrote the MuPAD procedure myProc and saved it in the file myProcedure.mu.
Before you can call this procedure at the MATLAB Command Window, you must read the file
myProcedure.mu into the symbolic engine. To read a program file into the symbolic engine, use
read:
read(symengine, 'myProcedure.mu')
7-1261
7 Functions
If the file is not on the MATLAB path, specify the full path to this file. For example, if
myProcedure.mu is in the MuPAD folder on disk C, enter:
read(symengine, 'C:/MuPAD/myProcedure.mu')
Now you can access the procedure myProc using evalin or feval. For example, compute the
factorial of 10:
feval(symengine, 'myProc', 10)
ans =
3628800
Input Arguments
filename — name of a MuPAD program file
character vector
Name of a MuPAD program file, specified as a character vector. This file must have the extension .mu
or .gz.
Tips
• If you do not specify the file extension, read searches for the file filename.mu.
• If filename is a GNU® zip file with the extension .gz, read uncompresses it upon reading.
• filename can include full or relative path information. If filename does not have a path
component, read uses the MATLAB function which to search for the file on the MATLAB path.
• read ignores any MuPAD aliases defined in the program file. If your program file contains aliases
or uses the aliases predefined by MATLAB, see “Alternatives” on page 7-1262.
Alternatives
You also can use feval to call the MuPAD read function. The read function available from the
MATLAB Command Window is equivalent to calling the MuPAD read function with the Plain option.
It ignores any MuPAD aliases defined in the program file:
feval(symengine, 'read',' "myProcedure.mu" ', 'Plain')
If your program file contains aliases or uses the aliases predefined by MATLAB, do not use Plain:
feval(symengine, 'read',' "myProcedure.mu" ')
Version History
Introduced in R2011b
Symbolic Math Toolbox includes operations and functions for symbolic math expressions that parallel
MATLAB functionality for numeric values. Unlike MuPAD functionality, Symbolic Math Toolbox
functions enable you to work in familiar interfaces, such as the MATLAB Command Window or Live
Editor, which offer a smooth workflow and are optimized for usability.
7-1262
read
Therefore, instead of passing a MuPAD program file to read, enter the equivalent Symbolic Math
Toolbox functionality into the MATLAB command line or Live Editor to work with symbolic math
expressions. For a list of available functions, see Symbolic Math Toolbox functions list.
To convert a MuPAD notebook file to a MATLAB live script file, see convertMuPADNotebook.
If you cannot find the Symbolic Math Toolbox equivalent for MuPAD functionality, contact MathWorks
Technical Support.
Although the use of read is not recommended, there are no plans to remove it at this time.
7-1263
7 Functions
real
Real part of complex number
Syntax
real(z)
Description
real(z) returns the real part of z. If z is a matrix, real acts elementwise on z.
Examples
Compute Real Part of Numeric Inputs
Find the real parts of these numbers. Because these numbers are not symbolic objects, you get
floating-point results.
ans =
2.0000 0 2.9374
ans =
[ 2, 2/5, 0]
real(2*exp(1 + sym(i)))
ans =
2*cos(1)*exp(1)
In general, real cannot extract the entire real parts from symbolic expressions containing variables.
However, real can rewrite and sometimes simplify the input expression:
syms a x y
real(a + 2)
real(x + y*i)
ans =
real(a) + 2
ans =
real(x) - imag(y)
7-1264
real
If you assign numeric values to these variables or specify that these variables are real, real can
extract the real part of the expression:
syms a
a = 5 + 3*i;
real(a + 2)
ans =
7
syms x y real
real(x + y*i)
ans =
x
Clear the assumption that x and y are real by recreating them using syms:
syms x y
syms x
A = [-1 + sym(i), sinh(x); exp(10 + sym(7)*i), exp(sym(pi)*i)];
real(A)
ans =
[ -1, real(sinh(x))]
[ cos(7)*exp(10), -1]
Input Arguments
z — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
Tips
• Calling real for a number that is not a symbolic object invokes the MATLAB real function.
Alternatives
You can compute the real part of z via the conjugate: real(z)= (z + conj(z))/2.
Version History
Introduced before R2006a
7-1265
7 Functions
See Also
conj | imag | in | sign | signIm
7-1266
rectangularPulse
rectangularPulse
Rectangular pulse function
Syntax
rectangularPulse(a,b,x)
rectangularPulse(x)
Description
rectangularPulse(a,b,x) returns the “Rectangular Pulse Function” on page 7-1270.
Examples
7-1267
7 Functions
Compute the rectangular pulse function for these numbers. Because these numbers are not symbolic
objects, you get floating-point results.
[rectangularPulse(-1, 1, -2)
rectangularPulse(-1, 1, -1)
rectangularPulse(-1, 1, 0)
rectangularPulse(-1, 1, 1)
rectangularPulse(-1, 1, 2)]
ans =
0
0.5000
1.0000
0.5000
0
Compute the rectangular pulse function for the same numbers in symbolic form.
[rectangularPulse(sym(-1), 1, -2)
rectangularPulse(-1, sym(1), -1)
rectangularPulse(-1, 1, sym(0))
rectangularPulse(sym(-1), 1, 1)
rectangularPulse(sym(-1), 1, 2)]
ans =
0
1/2
1
1/2
0
Show that if a < b, the rectangular pulse function for x = a and x = b equals 1/2.
syms a b x
assume(a < b)
rectangularPulse(a, b, a)
rectangularPulse(a, b, b)
ans =
1/2
ans =
1/2
For further computations, remove the assumptions on the variables by recreating them using syms:
syms a b
7-1268
rectangularPulse
syms a x
rectangularPulse(a, a, x)
ans =
0
syms x
rectangularPulse(x)
ans =
rectangularPulse(-1/2, 1/2, x)
[rectangularPulse(sym(-1))
rectangularPulse(sym(-1/2))
rectangularPulse(sym(0))
rectangularPulse(sym(1/2))
rectangularPulse(sym(1))]
ans =
0
1/2
1
1/2
0
When the rising or falling edge of rectangularPulse is Inf, then the result is in terms of
heaviside.
syms x
rectangularPulse(-inf, 0, x)
rectangularPulse(0, inf, x)
rectangularPulse(-inf, inf, x)
ans =
heaviside(-x)
ans =
heaviside(x)
ans =
1
Input Arguments
a — Input
-1/2 (default) | number | symbolic scalar
7-1269
7 Functions
Input, specified as a number or a symbolic scalar. This argument specifies the rising edge of the
rectangular pulse function.
b — Input
-1/2 (default) | number | symbolic scalar
Input, specified as a number or a symbolic scalar. This argument specifies the falling edge of the
rectangular pulse function.
x — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
More About
Rectangular Pulse Function
The rectangular pulse function is also called the rectangle function, boxcar function, Pi function, or
gate function.
Tips
• If a and b are variables or expressions with variables, rectangularPulse assumes that a < b.
If a and b are numerical values, such that a > b, rectangularPulse throws an error.
• If a = b, rectangularPulse returns 0.
Version History
Introduced in R2012b
See Also
dirac | heaviside | triangularPulse
7-1270
reduceDAEIndex
reduceDAEIndex
Convert system of first-order differential algebraic equations to equivalent system of differential
index 1
Syntax
[newEqs,newVars] = reduceDAEIndex(eqs,vars)
[newEqs,newVars,R] = reduceDAEIndex(eqs,vars)
[newEqs,newVars,R,oldIndex] = reduceDAEIndex(eqs,vars)
Description
[newEqs,newVars] = reduceDAEIndex(eqs,vars) converts a high-index system of first-order
differential algebraic equations eqs to an equivalent system newEqs of differential index 1.
reduceDAEIndex keeps the original equations and variables and introduces new variables and
equations. After conversion, reduceDAEIndex checks the differential index of the new system by
calling isLowIndexDAE. If the index of newEqs is 2 or higher, then reduceDAEIndex issues a
warning.
Examples
Reduce Differential Index of DAE System
Check if the following DAE system has a low (0 or 1) or high (>1) differential index. If the index is
higher than 1, then use reduceDAEIndex to reduce it.
Create the following system of two differential algebraic equations. Here, the symbolic functions
x(t), y(t), and z(t) represent the state variables of the system. Specify the equations and
variables as two symbolic vectors: equations as a vector of symbolic equations, and variables as a
vector of symbolic function calls.
Use isLowIndexDAE to check the differential index of the system. For this system, isLowIndexDAE
returns 0 (false). This means that the differential index of the system is 2 or higher.
isLowIndexDAE(eqs, vars)
ans =
logical
0
7-1271
7 Functions
Use reduceDAEIndex to rewrite the system so that the differential index is 1. The new system has
one additional state variable, Dyt(t).
newEqs =
diff(x(t), t) - z(t) - x(t)
Dyt(t) - f(t)
x(t) - y(t)
diff(x(t), t) - Dyt(t)
newVars =
x(t)
y(t)
z(t)
Dyt(t)
isLowIndexDAE(newEqs, newVars)
ans =
logical
1
Reduce the differential index of a system that contains two second-order differential algebraic
equation. Because the equations are second-order equations, first use reduceDifferentialOrder
to rewrite the system to a system of first-order DAEs.
Create the following system of two second-order DAEs. Here, x(t), y(t), and F(t) are the state
variables of the system. Specify the equations and variables as two symbolic vectors: equations as a
vector of symbolic equations, and variables as a vector of symbolic function calls.
Rewrite this system so that all equations become first-order differential equations. The
reduceDifferentialOrder function replaces the second-order DAE by two first-order expressions
by introducing the new variables Dxt(t) and Dyt(t). It also replaces the first-order equations by
symbolic expressions.
eqs =
diff(Dxt(t), t) + F(t)*x(t)
diff(Dyt(t), t) + g + F(t)*y(t)
- r^2 + x(t)^2 + y(t)^2
Dxt(t) - diff(x(t), t)
Dyt(t) - diff(y(t), t)
vars =
x(t)
y(t)
7-1272
reduceDAEIndex
F(t)
Dxt(t)
Dyt(t)
eqs =
Dxtt(t) + F(t)*x(t)
g + Dytt(t) + F(t)*y(t)
- r^2 + x(t)^2 + y(t)^2
Dxt(t) - Dxt1(t)
Dyt(t) - Dyt1(t)
2*Dxt1(t)*x(t) + 2*Dyt1(t)*y(t)
2*Dxt1t(t)*x(t) + 2*Dxt1(t)^2 + 2*Dyt1(t)^2 + 2*y(t)*diff(Dyt1(t), t)
Dxtt(t) - Dxt1t(t)
Dytt(t) - diff(Dyt1(t), t)
Dyt1(t) - diff(y(t), t)
vars =
x(t)
y(t)
F(t)
Dxt(t)
Dyt(t)
Dytt(t)
Dxtt(t)
Dxt1(t)
Dyt1(t)
Dxt1t(t)
R =
[ Dytt(t), diff(Dyt(t), t)]
[ Dxtt(t), diff(Dxt(t), t)]
[ Dxt1(t), diff(x(t), t)]
[ Dyt1(t), diff(y(t), t)]
[ Dxt1t(t), diff(x(t), t, t)]
originalIndex =
3
eqs =
Dxtt(t) + F(t)*x(t)
g + Dytt(t) + F(t)*y(t)
- r^2 + x(t)^2 + y(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) - diff(Dyt(t), t)
Dyt(t) - diff(y(t), t)
vars =
x(t)
y(t)
F(t)
7-1273
7 Functions
Dxt(t)
Dyt(t)
Dytt(t)
Dxtt(t)
Input Arguments
eqs — System of first-order DAEs
vector of symbolic equations | vector of symbolic expressions
State variables, specified as a vector of symbolic functions or function calls, such as x(t).
Example: [x(t),y(t)]
Output Arguments
newEqs — System of first-order DAEs of differential index 1
column vector of symbolic expressions
Extended set of variables, returned as a column vector of symbolic function calls. This vector includes
the original state variables vars followed by the generated variables that replace the second- and
higher-order derivatives in eqs.
Relations between new and original variables, returned as a symbolic matrix with two columns. The
first column contains the new variables. The second column contains their definitions as derivatives
of the original variables vars.
Algorithms
The implementation of reduceDAEIndex uses the Pantelides algorithm. This algorithm reduces
higher-index systems to lower-index systems by selectively adding differentiated forms of the original
equations. The Pantelides algorithm can underestimate the differential index of a new system, and
therefore, can fail to reduce the differential index to 1. In this case, reduceDAEIndex issues a
warning and, for the syntax with four output arguments, returns the value of oldIndex as NaN. The
7-1274
reduceDAEIndex
reduceDAEToODE function uses more reliable, but slower Gaussian elimination. Note that
reduceDAEToODE requires the DAE system to be semilinear.
Version History
Introduced in R2014b
See Also
daeFunction | decic | findDecoupledBlocks | incidenceMatrix | isLowIndexDAE |
massMatrixForm | odeFunction | reduceDAEToODE | reduceDifferentialOrder |
reduceRedundancies
Topics
“Solve Differential Algebraic Equations (DAEs)” on page 3-61
7-1275
7 Functions
reduceDAEToODE
Convert system of first-order semilinear differential algebraic equations to equivalent system of
differential index 0
Syntax
newEqs = reduceDAEToODE(eqs,vars)
[newEqs,constraintEqs] = reduceDAEToODE(eqs,vars)
[newEqs,constraintEqs,oldIndex] = reduceDAEToODE(eqs,vars)
Description
newEqs = reduceDAEToODE(eqs,vars) converts a high-index system of first-order semilinear
algebraic equations eqs to an equivalent system of ordinary differential equations, newEqs. The
differential index of the new system is 0, that is, the Jacobian of newEqs with respect to the
derivatives of the variables in vars is invertible.
Examples
Convert DAE System to Implicit ODE System
Create the following system of two differential algebraic equations. Here, the symbolic functions
x(t), y(t), and z(t) represent the state variables of the system. Specify the equations and
variables as two symbolic vectors: equations as a vector of symbolic equations, and variables as a
vector of symbolic function calls.
newEqs =
x(t)*diff(y(t), t) - y(t) + diff(x(t), t)
diff(x(t), t)*(cos(x(t)) - y(t)) - x(t)*diff(y(t), t)
z(t) - 2*x(t)*diff(x(t), t) - 2*y(t)*diff(y(t), t) + t*diff(z(t), t)
7-1276
reduceDAEToODE
Check if the following DAE system has a low (0 or 1) or high (>1) differential index. If the index is
higher than 1, first try to reduce the index by using reduceDAEIndex and then by using
reduceDAEToODE.
Create the system of differential algebraic equations. Here, the functions x1(t), x2(t), and x3(t)
represent the state variables of the system. The system also contains the functions q1(t), q2(t),
and q3(t). These functions do not represent state variables. Specify the equations and variables as
two symbolic vectors: equations as a vector of symbolic equations, and variables as a vector of
symbolic function calls.
syms x1(t) x2(t) x3(t) q1(t) q2(t) q3(t)
eqs = [diff(x2) == q1 - x1,
diff(x3) == q2 - 2*x2 - t*(q1-x1),
q3 - t*x2 - x3];
vars = [x1(t), x2(t), x3(t)];
Use isLowIndexDAE to check the differential index of the system. For this system, isLowIndexDAE
returns 0 (false). This means that the differential index of the system is 2 or higher.
isLowIndexDAE(eqs, vars)
ans =
logical
0
Use reduceDAEIndex as your first attempt to rewrite the system so that the differential index is 1.
For this system, reduceDAEIndex issues a warning because it cannot reduce the differential index of
the system to 0 or 1.
[newEqs, newVars] = reduceDAEIndex(eqs, vars)
newEqs =
x1(t) - q1(t) + diff(x2(t), t)
Dx3t(t) - q2(t) + 2*x2(t) + t*(q1(t) - x1(t))
q3(t) - x3(t) - t*x2(t)
diff(q3(t), t) - x2(t) - t*diff(x2(t), t) - Dx3t(t)
newVars =
x1(t)
x2(t)
x3(t)
Dx3t(t)
If reduceDAEIndex cannot reduce the semilinear system so that the index is 0 or 1, try using
reduceDAEToODE. This function can be much slower, therefore it is not recommended as a first
choice. Use the syntax with two output arguments to also return the constraint equations.
[newEqs, constraintEqs] = reduceDAEToODE(eqs, vars)
newEqs =
x1(t) - q1(t) + diff(x2(t), t)
2*x2(t) - q2(t) + t*q1(t) - t*x1(t) + diff(x3(t), t)
diff(x1(t), t) - diff(q1(t), t) + diff(q2(t), t, t) - diff(q3(t), t, t, t)
7-1277
7 Functions
constraintEqs =
x1(t) - q1(t) + diff(q2(t), t) - diff(q3(t), t, t)
x3(t) - q3(t) + t*x2(t)
x2(t) - q2(t) + diff(q3(t), t)
Use the syntax with three output arguments to return the new equations, constraint equations, and
the differential index of the original system, eqs.
newEqs =
x1(t) - q1(t) + diff(x2(t), t)
2*x2(t) - q2(t) + t*q1(t) - t*x1(t) + diff(x3(t), t)
diff(x1(t), t) - diff(q1(t), t) + diff(q2(t), t, t) - diff(q3(t), t, t, t)
constraintEqs =
x1(t) - q1(t) + diff(q2(t), t) - diff(q3(t), t, t)
x3(t) - q3(t) + t*x2(t)
x2(t) - q2(t) + diff(q3(t), t)
oldIndex =
3
Input Arguments
eqs — System of first-order semilinear DAEs
vector of symbolic equations | vector of symbolic expressions
State variables, specified as a vector of symbolic functions or function calls, such as x(t).
Example: [x(t),y(t)] or [x(t);y(t)]
Output Arguments
newEqs — System of implicit ordinary differential equations
column vector of symbolic expressions
Constraint equations encountered during system reduction, returned as a column vector of symbolic
expressions. These expressions depend on the variables vars, but not on their derivatives. The
constraints are conserved quantities of the differential equations in newEqs, meaning that the time
derivative of each constraint vanishes modulo the equations in newEqs.
You can use these equations to determine consistent initial conditions for the DAE system.
7-1278
reduceDAEToODE
Algorithms
The implementation of reduceDAEToODE is based on Gaussian elimination. This algorithm is more
reliable than the Pantelides algorithm used by reduceDAEIndex, but it can be much slower.
Version History
Introduced in R2014b
See Also
daeFunction | decic | findDecoupledBlocks | incidenceMatrix | isLowIndexDAE |
massMatrixForm | odeFunction | reduceDAEIndex | reduceDifferentialOrder |
reduceRedundancies
Topics
“Solve Semilinear DAE System” on page 3-70
7-1279
7 Functions
reduceDifferentialOrder
Reduce system of higher-order differential equations to equivalent system of first-order differential
equations
Syntax
[newEqs,newVars] = reduceDifferentialOrder(eqs,vars)
[newEqs,newVars,R] = reduceDifferentialOrder(eqs,vars)
Description
[newEqs,newVars] = reduceDifferentialOrder(eqs,vars) rewrites a system of higher-
order differential equations eqs as a system of first-order differential equations newEqs by
substituting derivatives in eqs with new variables. Here, newVars consists of the original variables
vars augmented with these new variables.
Examples
Reduce Differential Order of DAE System
Reduce a system containing higher-order DAEs to a system containing only first-order DAEs.
Create the system of differential equations, which includes a second-order expression. Here, x(t)
and y(t) are the state variables of the system, and c1 and c2 are parameters. Specify the equations
and variables as two symbolic vectors: equations as a vector of symbolic equations, and variables as a
vector of symbolic function calls.
Rewrite this system so that all equations become first-order differential equations. The
reduceDifferentialOrder function replaces the higher-order DAE by first-order expressions by
introducing the new variable Dxt(t). It also represents all equations as symbolic expressions.
newEqs =
diff(Dxt(t), t) + sin(x(t)) + y(t) - c1*cos(t)
diff(y(t), t) - c2*x(t)
Dxt(t) - diff(x(t), t)
newVars =
x(t)
y(t)
Dxt(t)
7-1280
reduceDifferentialOrder
Reduce a system containing a second- and a third-order expression to a system containing only first-
order DAEs. In addition, return a matrix that expresses the variables generated by
reduceDifferentialOrder via the original variables of this system.
Create a system of differential equations, which includes a second- and a third-order expression.
Here, x(t) and y(t) are the state variables of the system. Specify the equations and variables as
two symbolic vectors: equations as a vector of symbolic equations, and variables as a vector of
symbolic function calls.
Call reduceDifferentialOrder with three output arguments. This syntax returns matrix R with
two columns: the first column contains the new variables, and the second column expresses the new
variables as derivatives of the original variables, x(t) and y(t).
newEqs =
diff(Dxt(t), t) - diff(f(t), t, t, t)
diff(Dytt(t), t) - diff(f(t), t, t)
Dxt(t) - diff(x(t), t)
Dyt(t) - diff(y(t), t)
Dytt(t) - diff(Dyt(t), t)
newVars =
x(t)
y(t)
Dxt(t)
Dyt(t)
Dytt(t)
R =
[ Dxt(t), diff(x(t), t)]
[ Dyt(t), diff(y(t), t)]
[ Dytt(t), diff(y(t), t, t)]
Input Arguments
eqs — System containing higher-order differential equations
vector of symbolic equations | vector of symbolic expressions
7-1281
7 Functions
Output Arguments
newEqs — System of first-order differential equations
column vector of symbolic expressions
Extended set of variables, returned as a column vector of symbolic function calls. This vector includes
the original state variables vars followed by the generated variables that replace the higher-order
derivatives in eqs.
Relations between new and original variables, returned as a symbolic matrix with two columns. The
first column contains the new variables newVars. The second column contains their definition as
derivatives of the original variables vars.
Version History
Introduced in R2014b
See Also
findDecoupledBlocks | daeFunction | decic | incidenceMatrix | isLowIndexDAE |
massMatrixForm | odeFunction | reduceDAEIndex | reduceDAEToODE | reduceRedundancies
Topics
“Solve Differential Algebraic Equations (DAEs)” on page 3-61
7-1282
reduceRedundancies
reduceRedundancies
Simplify system of first-order differential algebraic equations by eliminating redundant equations and
variables
Syntax
[newEqs,newVars] = reduceRedundancies(eqs,vars)
[newEqs,newVars,R] = reduceRedundancies(eqs,vars)
Description
[newEqs,newVars] = reduceRedundancies(eqs,vars) eliminates redundant equations and
variables from the system of first-order differential algebraic equations (DAEs) eqs. The input
argument vars specifies the state variables of the system.
reduceRedundancies returns the new DAE system as a column vector newEqs and the reduced
state variables as a column vector newVars. Each element of newEqs represents an equation with
right side equal to zero.
Examples
Simplify a system of five differential algebraic equations (DAEs) in four state variables to a system of
two equations in two state variables.
Create the following system of five DAEs in four state variables x1(t), x2(t), x3(t), and x4(t).
The system also contains symbolic parameters a1, a2, a3, a4, b, c, and the function f(t) that are
not state variables.
syms x1(t) x2(t) x3(t) x4(t) a1 a2 a3 a4 b c f(t)
eqs = [a1*diff(x1(t),t)+a2*diff(x2(t),t) == b*x4(t),
a3*diff(x2(t),t)+a4*diff(x3(t),t) == c*x4(t),
x1(t) == 2*x2(t),
x4(t) == f(t),
f(t) == sin(t)];
vars = [x1(t),x2(t),x3(t),x4(t)];
newEqs =
∂
∂ a2 ∂t x1 t
a1 x1 t + −bf t
∂t 2
∂
a3 ∂t x1 t ∂
+ a4 x t −cf t
2 ∂t 3
7-1283
7 Functions
newVars =
x1 t
x3 t
Specify input order of the state variables to choose which variables are being returned when
eliminating DAEs.
Create a system of four DAEs in four state variables V_ac(t), V1(t), V2(t), and I(t). The system
also contains symbolic parameters L, R, and V0.
eqs =
V ac t = V 1 t + V 2 t
V1 t = R I t
∂
V2 t = L It
∂t
V ac t = V 0 cos t
vars = [V_ac(t),I(t),V1(t),V2(t)]
vars = V ac t I t V 1 t V 2 t
[newEqs,newVars] = reduceRedundancies(eqs,vars)
newEqs =
∂
−L I t − R I t + V 0 cos t
∂t
newVars = I t
When multiple ways of reducing the DAEs exist, specify a different input order of the state variables
to choose which variables are being returned. Specify another vector that contains a different order
of the state variables. Eliminate the DAEs again.
vars2 = [V_ac(t),V1(t),V2(t),I(t)]
vars2 = V ac t V 1 t V 2 t I t
[newEqs,newVars] = reduceRedundancies(eqs,vars2)
newEqs =
7-1284
reduceRedundancies
∂
L ∂t V 1 t + R V 1 t − R V 0 cos t
−
R
newVars = V 1 t
Here, reduceRedundancies returns a reduced equation in term of the state variable V1(t).
Create the following system of five differential algebraic equations (DAEs) in four state variables
x1(t), x2(t), x3(t), and x4(t). The system also contains symbolic parameters a1, a2, a3, a4, b,
c, and the function f(t) that are not state variables.
syms x1(t) x2(t) x3(t) x4(t) a1 a2 a3 a4 b c f(t)
eqs = [a1*diff(x1(t),t)+a2*diff(x2(t),t) == b*x4(t),
a3*diff(x2(t),t)+a4*diff(x3(t),t) == c*x4(t),
x1(t) == 2*x2(t),
x4(t) == f(t),
f(t) == sin(t)];
vars = [x1(t),x2(t),x3(t),x4(t)];
newEqs =
∂
∂ a2 ∂t x1 t
a1 x1 t + −bf t
∂t 2
∂
a3 ∂t x1 t ∂
+ a4 x t −cf t
2 ∂t 3
newVars =
x1 t
x3 t
The solvedEquations field contains the equations that are eliminated by reduceRedundancies.
The eliminated equations contain those state variables from vars that do not appear in newEqs. The
right side of each eliminated equation is equal to zero.
R1 = R.solvedEquations
7-1285
7 Functions
R1 =
x1 t − 2 x2 t
x4 t − f t
The constantVariables field contains a matrix with two columns. The first column contains those
state variables from vars that reduceRedundancies replaced by constant values. The second
column contains the corresponding constant values.
R2 = R.constantVariables
R2 = x4 t f t
The replacedVariables field contains a matrix with two columns. The first column contains those
state variables from vars that reduceRedundancies replaced by expressions in terms of other
variables. The second column contains the corresponding values of the eliminated variables.
R3 = R.replacedVariables
R3 =
x1 t
x2 t
2
The otherEquations field contains those equations from eqs that do not contain any of the state
variables vars.
R4 = R.otherEquations
R4 = f t − sin t
Input Arguments
eqs — System of first-order DAEs
vector of symbolic equations | vector of symbolic expressions
The relation operator == defines symbolic equations. If you specify the element of eqs as a symbolic
expression without a right side, then a symbolic equation with right side equal to zero is assumed.
State variables, specified as a vector of symbolic functions or function calls, such as x(t).
The input order of the state variables determines which reduced variables are being returned. If
multiple ways of reducing the DAEs exist, then reduceRedundancies prioritizes to keep the state
variables in vars starting from the first element.
Example: [x(t),z(t),y(t)]
Output Arguments
newEqs — System of first-order DAEs
column vector of symbolic expressions
7-1286
reduceRedundancies
System of first-order DAEs, returned as a column vector of symbolic expressions. Each element of
newEqs represents an equation with right side equal to zero.
Information about eliminated variables, returned as a structure array containing four fields. To access
this information, use:
Version History
Introduced in R2014b
See Also
daeFunction | decic | findDecoupledBlocks | incidenceMatrix | isLowIndexDAE |
massMatrixForm | odeFunction | reduceDAEIndex | reduceDAEToODE |
reduceDifferentialOrder
Topics
“Solve Differential Algebraic Equations (DAEs)” on page 3-61
7-1287
7 Functions
release
Evaluate integrals
Syntax
release(expr)
Description
release(expr) evaluates the integrals in the expression expr. The release function ignores the
'Hold' option in the int function when the integrals are defined.
Examples
Unevaluated Integral
Define a symbolic call to an integral ∫cos x dx without evaluating it. Set the 'Hold' option to true
when defining the integral using the int function.
syms x
F = int(cos(x),'Hold',true)
F =
∫cos x dx
G = release(F)
G = sin x
Define the integral without evaluating it by setting the 'Hold' option to true.
syms x g(y)
F = int(x*exp(x),'Hold',true)
F =
∫x ex dx
You can apply integration by parts to F by using the integrateByParts function. Use exp(x) as
the differential to be integrated.
G = integrateByParts(F,exp(x))
7-1288
release
G =
x ex − ∫ ex dx
To evaluate the integral in G, use the release function to ignore the 'Hold' option.
Gcalc = release(G)
Gcalc = x ex − ex
Compare the result to the integration result returned by int without setting the 'Hold' option.
Fcalc = int(x*exp(x))
Fcalc = ex x − 1
Integration by Substitution
Define the integral without evaluating it by setting the 'Hold' option to true.
syms x t
F = int(cos(log(x)),'Hold',true)
F =
∫cos log x dx
G = changeIntegrationVariable(F,log(x),t)
G =
∫ et cos t dt
To evaluate the integral in G, use the release function to ignore the 'Hold' option.
H = release(G)
H =
et cos t + sin t
2
H = simplify(subs(H,t,log(x)))
H =
π
2 x sin 4 + log x
2
Compare the result to the integration result returned by int without setting the 'Hold' option to
true.
7-1289
7 Functions
Fcalc = int(cos(log(x)))
Fcalc =
π
2 x sin 4 + log x
2
Input Arguments
expr — Expression containing integrals
symbolic expression | symbolic function | symbolic vector | symbolic matrix
Version History
Introduced in R2019b
See Also
integrateByParts | int | diff | changeIntegrationVariable
7-1290
rem
rem
Remainder after division
Syntax
rem(a,b)
Description
rem(a,b) finds the remainder after division. If b <> 0, then rem(a,b) = a - fix(a/b)*b. If b
= 0 or b = Inf or b = -Inf, then rem returns NaN.
The rem function does not support complex numbers: all values must be real numbers.
Examples
Divide Integers by Integers
Find the remainder after division in case both the dividend and divisor are integers.
ans =
[ 3, 3, -3, -3]
Find the remainder after division in case the dividend is a rational number, and the divisor is an
integer.
ans =
[ 7/3, 1/2, 9/2]
For vectors and matrices, rem finds the remainder after division element-wise. Nonscalar arguments
must be the same size.
Find the remainder after division for the elements of these two matrices.
7-1291
7 Functions
ans =
[ 1, 1]
[ 1, 0]
Find the remainder after division for the elements of matrix A and the value 9. Here, rem expands 9
into the 2-by-2 matrix with all elements equal to 9.
rem(A,9)
ans =
[ 0, 1]
[ 2, 3]
Input Arguments
a — Dividend (numerator)
number | symbolic number | vector | matrix
b — Divisor (denominator)
number | symbolic number | vector | matrix
Tips
• Calling rem for numbers that are not symbolic objects invokes the MATLAB rem function.
• All nonscalar arguments must be the same size. If one input arguments is nonscalar, then mod
expands the scalar into a vector or matrix of the same size as the nonscalar argument, with all
elements equal to the corresponding scalar.
Version History
Introduced before R2006a
See Also
mod | quorem
7-1292
removeUnit
removeUnit
Remove unit
Syntax
removeUnit(unit)
Description
removeUnit(unit) removes the symbolic unit unit. You can remove only user-defined units
created with newUnit. You cannot remove predefined units. If unit is a vector, removeUnit
removes all units in unit.
Examples
Remove Unit
Remove units you define by using removeUnit. Create the unit warp3, use the unit in calculations,
and then remove the unit.
u = symunit;
warp3 = newUnit('warp3',3*u.c_0)
warp3 =
[warp3]
speed = rewrite(1e10*u.m/u.s,u.warp3)
speed =
(5000000000/449688687)*[warp3]
removeUnit(u.warp3)
Input Arguments
unit — Unit name
symbolic unit | vector of symbolic units
7-1293
7 Functions
Version History
Introduced in R2017b
See Also
checkUnits | isUnit | newUnit | newUnitSystem | symunit
Topics
“Units of Measurement Tutorial” on page 2-47
“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)
7-1294
reset
reset
(Not recommended) Close MuPAD engine
Note reset(symengine) is not recommended. Call clear all instead. For more information, see
“Compatibility Considerations”.
Syntax
reset(symengine)
Description
reset(symengine) closes the MuPAD engine associated with the MATLAB workspace, and resets
all its assumptions. Immediately before or after executing reset(symengine) you should clear all
symbolic objects in the MATLAB workspace.
Version History
Introduced in R2008b
To update your code, replace any instance of reset(symengine) with clear all. The clear all
call closes the MuPAD engine associated with the MATLAB Workspace, resets all associated
assumptions, and removes all variables, including symbolic objects, from the MATLAB Workspace.
Although the use of reset is not recommended, there are no plans to remove it at this time.
7-1295
7 Functions
reshape
Reshape symbolic array
Syntax
reshape(A,n1,n2)
reshape(A,n1,...,nM)
reshape(A,...,[],...)
reshape(A,sz)
Description
reshape(A,n1,n2) returns the n1-by-n2 matrix, which has the same elements as A. The elements
are taken column-wise from A to fill in the elements of the n1-by-n2 matrix.
reshape(A,n1,...,nM) returns the n1-by-...-by-nM array, which has the same elements as A. The
elements are taken column-wise from A to fill in the elements of the n1-by-...-by-nM array.
reshape(A,...,[],...) lets you represent a size value with the placeholder [] while calculating
the magnitude of that size value automatically. For example, if A has size 2-by-6, then reshape(A,4,
[]) returns a 4-by-3 array.
reshape(A,sz) reshapes A into an array with size specified by sz, where sz is a vector.
Examples
Reshape Symbolic Row Vector into Column Vector
Reshape V, which is a 1-by-4 row vector, into the 4-by-1 column vector Y. Here, V and Y must have the
same number of elements.
syms f(x) y
V = [3 f(x) -4 y]
V =
[ 3, f(x), -4, y]
Reshape V into Y.
Y = reshape(V,4,1)
Y =
3
f(x)
-4
y
7-1296
reshape
M =
[ 1, 9, 4, 3, 0, 1]
[ 3, 9, 5, 1, 9, 2]
N =
[ 1, 4, 0]
[ 3, 5, 9]
[ 9, 3, 1]
[ 9, 1, 2]
M and N must have the same number of elements. reshape reads M column-wise to fill in the elements
of N column-wise.
Alternatively, use a size vector to specify the dimensions of the reshaped matrix.
sz = [4 3];
N = reshape(M,sz)
N =
[ 1, 4, 0]
[ 3, 5, 9]
[ 9, 3, 1]
[ 9, 1, 2]
When you replace a dimension with the placeholder [], reshape calculates the required magnitude
of that dimension to reshape the matrix.
M =
[ 1, 9, 4, 3, 0, 1]
[ 3, 9, 5, 1, 9, 2]
ans =
[ 1, 4, 0]
[ 3, 5, 9]
[ 9, 3, 1]
[ 9, 1, 2]
reshape calculates that a reshaped matrix of three columns needs four rows.
7-1297
7 Functions
Create matrix M.
syms x
M = sym([1 9 0 sin(x) 2 2; NaN x 5 1 4 7])
M =
[ 1, 9, 0, sin(x), 2, 2]
[ NaN, x, 5, 1, 4, 7]
ans =
[ 1, NaN, 9, x]
[ 0, 5, sin(x), 1]
[ 2, 4, 2, 7]
Note that .' returns the non-conjugate transpose while ' returns the conjugate transpose.
M has 18 elements. Because a 9-by-2 matrix also has 18 elements, M can be reshaped into it. Construct
M.
syms x
M = [sin(x) x 4; 3 2 9; 8 x x];
M(:,:,2) = M'
M(:,:,1) =
[ sin(x), x, 4]
[ 3, 2, 9]
[ 8, x, x]
M(:,:,2) =
[ sin(conj(x)), 3, 8]
[ conj(x), 2, conj(x)]
[ 4, 9, conj(x)]
N =
[ sin(x), sin(conj(x))]
[ 3, conj(x)]
[ 8, 4]
[ x, 3]
[ 2, 2]
[ x, 9]
[ 4, 8]
[ 9, conj(x)]
[ x, conj(x)]
Use reshape instead of loops to break up arrays for further computation. Use reshape to break up
the vector V to find the product of every three elements.
7-1298
reshape
Create vector V.
syms x
V = [exp(x) 1 3 9 x 2 7 7 1 8 x^2 3 4 sin(x) x]
V =
[ exp(x), 1, 3, 9, x, 2, 7, 7, 1, 8, x^2, 3, 4, sin(x), x]
Specify 3 for the number of rows. Use the placeholder [] for the number of columns. This lets
reshape automatically calculate the number of columns required for three rows.
M = prod( reshape(V,3,[]) )
M =
[ 3*exp(x), 18*x, 49, 24*x^2, 4*x*sin(x)]
reshape calculates that five columns are required for a matrix of three rows. prod then multiples
the elements of each column to return the result.
Input Arguments
A — Input array
symbolic vector | symbolic matrix | symbolic multidimensional array
Size of reshaped array, specified as a numeric vector. For example, reshape(A,[3 2]) returns a 3-
by-2 matrix. The number of elements in the output array specified by sz must be equal to numel(A).
Version History
Introduced before R2006a
See Also
colon | transpose
7-1299
7 Functions
resultant
Resultant of two polynomials
Syntax
resultant(p,q)
resultant(p,q,var)
Description
resultant(p,q) returns the resultant of the polynomials p and q with respect to the variable found
by symvar.
Examples
syms x y
p = x^2+y;
q = x-2*y;
resultant(p,q)
ans =
4*y^2 + y
Find the resultant with respect to a specific variable by using the third argument.
resultant(p,q,y)
ans =
2*x^2 + x
If two polynomials have a common root, then the resultant must be 0 at that root. Solve polynomial
equations in two variables by calculating the resultant with respect to one variable, and solving the
resultant for the other variable.
First, calculate the resultant of two polynomials with respect to x to return a polynomial in y.
syms x y
p = y^3 - 2*x^2 + 3*x*y;
q = x^3 + 2*y^2 - 5*x^2*y;
res = resultant(p,q,x)
res =
y^9 - 35*y^8 + 44*y^6 + 126*y^5 - 32*y^4
7-1300
resultant
Solve the resultant for y values of the roots. Avoid numerical roundoff errors by solving equations
symbolically using the solve function. solve represents the solutions symbolically by using root.
yRoots = solve(res)
yRoots =
0
0
0
0
root(z^5 - 35*z^4 + 44*z^2 + 126*z - 32, z, 1)
root(z^5 - 35*z^4 + 44*z^2 + 126*z - 32, z, 2)
root(z^5 - 35*z^4 + 44*z^2 + 126*z - 32, z, 3)
root(z^5 - 35*z^4 + 44*z^2 + 126*z - 32, z, 4)
root(z^5 - 35*z^4 + 44*z^2 + 126*z - 32, z, 5)
vpa(yRoots)
ans =
0
0
0
0
0.23545637976581197505601615070637
- 0.98628744767074109264070992415511 - 1.1027291033304653904984097788422i
- 0.98628744767074109264070992415511 + 1.1027291033304653904984097788422i
1.7760440932430169904041045113342
34.96107442233265321982129918627
Assume that you want to investigate the fifth root. For the fifth root, calculate the x value by
substituting the y value into p and q. Then simultaneously solve the polynomials for x. Avoid
numerical roundoff errors by solving equations symbolically using solve.
root5 =
[ 0.37078716473998365045397220797284, 0.23545637976581197505601615070637]
Verify that the root is correct by substituting root5 into p and q. The result is 0 within roundoff
error.
ans =
[ -6.313690360861895794753956010471e-41, -9.1835496157991211560057541970488e-41]
Input Arguments
p — Polynomial
symbolic expression | symbolic function
7-1301
7 Functions
q — Polynomial
symbolic expression | symbolic function
var — Variable
symbolic variable
Version History
Introduced in R2018a
See Also
eliminate | gcd | solve
7-1302
removeUnitSystem
removeUnitSystem
Remove unit system
Syntax
removeUnitSystem(unitSystem)
Description
removeUnitSystem(unitSystem) removes the unit system unitSystem. You can remove only
user-defined unit systems created with newUnitSystem. You cannot remove predefined unit systems
listed in “Unit Systems List” on page 2-71.
Examples
Define a unit system, use the unit system to rewrite units, and then remove the unit system by using
removeUnitSystem.
Define the unit system mySystem with SI base units and the derived unit kilowatt hour.
u = symunit;
bunits = baseUnits('SI');
dunits = [u.kWh];
mySystem = newUnitSystem('mySystem',bunits,dunits)
mySystem =
"mySystem"
Convert 50,000 Joules to derived units of mySystem by using rewrite with the third argument
'Derived'. As expected, the result is in kilowatt hour.
rewrite(50000*u.J,mySystem,'Derived')
ans =
(1/72)*[kWh]
removeUnitSystem(mySystem)
Input Arguments
unitSystem — Name of unit system
string | character vector
7-1303
7 Functions
Version History
Introduced in R2017b
See Also
baseUnits | derivedUnits | newUnitSystem | removeUnit | rewrite | symunit | unitSystems
Topics
“Units of Measurement Tutorial” on page 2-47
“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)
7-1304
rewindAnimation
rewindAnimation
Rewind previously played animation objects
Syntax
rewindAnimation
rewindAnimation(fig)
Description
rewindAnimation rewinds previously played animation objects by restoring the animation time
parameter to its initial value. The animation objects must be created using the fanimator function.
Examples
First, create two symbolic variables, t and x. The variable t defines the time parameter of the
animation. Use t to set the center of the circle at (t,1) and x to parameterize the perimeter of the
circle within the range [-pi pi]. Create the circle animation object using fanimator. Set the x-
axis and y-axis to be equal length.
syms t x
fanimator(@fplot,cos(x)+t,sin(x)+1,[-pi pi])
axis equal
Play the animation by entering the command playAnimation. By default, playAnimation plays the
animation within the range of t from 0 to 10. You can rewind the animation by using
rewindAnimation. rewindAnimation restores the animation time parameter to its initial value at
t = 0 and shows the starting animation frame.
rewindAnimation
7-1305
7 Functions
Create an animation of a moving circle with a timer, and rewind the animation using
rewindAnimation.
First, create two symbolic variables, t and x. The variable t defines the time parameter of the
animation. Create a figure window for the animation.
syms t x
fig = figure;
Create the circle animation object using fanimator. Use t to set the center of the circle at (t,1)
and x to parameterize the perimeter of the circle within the range [-pi pi]. Set the range of the
animation time parameter to [4 8]. Set the x-axis and y-axis to be equal length.
Next, add a timer animation object. Use the text function to create a piece of text to count the
elapsed time. Use num2str to convert the time parameter to a string.
hold on
fanimator(@(t) text(8,3,"Timer: "+num2str(t,2)),'AnimationRange',[4 8])
hold off
7-1306
rewindAnimation
Play the animation in figure fig between 4 and 8 seconds by entering the playAnimation
command.
playAnimation(fig,'AnimationRange',[4 8])
rewindAnimation(fig)
Input Arguments
fig — Target figure
Figure object
Target figure, specified as a Figure object. For more information about Figure objects, see figure.
Version History
Introduced in R2019a
7-1307
7 Functions
See Also
animationToFrame | playAnimation | fanimator | writeAnimation
7-1308
rewrite
rewrite
Rewrite expression in terms of another function
Syntax
R = rewrite(expr,target)
Description
R = rewrite(expr,target) rewrites the symbolic expression expr in terms of another function
as specified by target. The rewritten expression is mathematically equivalent to the original
expression. If expr is a vector or matrix, rewrite acts element-wise on expr.
Examples
Rewrite any trigonometric function in terms of the exponential function by specifying the target
"exp".
syms x
sin2exp = rewrite(sin(x),"exp")
sin2exp =
e−x i i ex i i
−
2 2
tan2exp = rewrite(tan(x),"exp")
tan2exp =
e2 x i i − i
−
e2 x i + 1
Rewrite the exponential function in terms of any trigonometric function by specifying the
trigonometric function as the target. For a full list of target options, see “target” on page 7-0 .
syms x
exp2sin = rewrite(exp(x),"sin")
exp2sin =
x i 2
−2 sin − sin x i i +1
2
exp2tan =
tan x − i i
tan x + i
+ i
− tan x − i
tan x + i
−1
7-1309
7 Functions
exp2tan = simplify(exp2tan)
exp2tan = tan x
Rewrite any trigonometric function in terms of any other trigonometric function by specifying the
target. For a full list of target options, see “target” on page 7-0 .
Rewrite tan(x) in terms of the sine function by specifying the target "sin".
syms x
tan2sin = rewrite(tan(x),"sin")
tan2sin =
sin x
−
x 2
2 sin 2 − 1
Rewrite any inverse trigonometric function in terms of the logarithm function by specifying the target
"log". For a full list of target options, see “target” on page 7-0 .
syms x
acos2log = rewrite(acos(x),"log")
acos2log = −log x + 1 − x2 i i
acot2log = rewrite(acot(x),"log")
acot2log =
i i
log 1 − x i log 1 + x i
−
2 2
Similarly, rewrite the logarithm function in terms of any inverse trigonometric function by specifying
the inverse trigonometric function as the target.
syms x
matrix = [sin(x) cos(x); sinh(x) cosh(x)];
R = rewrite(matrix,"exp")
7-1310
rewrite
R =
e−x i i ex i i e−x i ex i
− +
2 2 2 2
ex e−x e−x ex
− +
2 2 2 2
Rewrite the cosine function in terms of the sine function. Here, the rewrite function rewrites the
x 2
cosine function using the identity cos x = 1 − 2 sin 2
, which is valid for any x.
syms x
R = rewrite(cos(x),"sin")
R =
x 2
1 − 2 sin
2
rewrite does not rewrite sin(x) as either − 1 − cos2 x or 1 − cos2 x because these expressions
are not valid for all x. However, using the square of these expressions to represent sin(x)^2 is valid
for all x. Thus, rewrite can rewrite sin(x)^2.
syms x
R1 = rewrite(sin(x),"cos")
R1 = sin x
R2 = rewrite(sin(x)^2,"cos")
2
R2 = 1 − cos x
Find the root of a polynomial by using root. The result is a column vector in terms of the root
function with k = 1, 2, 3, 4, or 5 for the kth root of the polynomial.
syms x
sols = root(x^5 - x^4 - 1,x)
sols =
root x5 − x4 − 1, x, 1
root x5 − x4 − 1, x, 2
root x5 − x4 − 1, x, 3
root x5 − x4 − 1, x, 4
root x5 − x4 − 1, x, 5
Expand the root function in sols by using rewrite with the "expandroot" option. The result is in
terms of arithmetic operations such as ^, *, /, +, and – that operate on exact symbolic numbers.
7-1311
7 Functions
Because the expanded result can involve many terms that operate arithmetically, numerical
approximation of this result can be inaccurate (due to accumulation of round-off errors).
R = rewrite(sols,"expandroot")
R =
1 3 i
−
2 2
1 3 i
+
2 2
1
+ σ1
3 σ1
1
σ1 3 3 σ − σ1 i
1 1
− − −
6 σ1 2 2
1
σ1 3 3 σ − σ1 i
1 1
− − +
6 σ1 2 2
where
23 108 1 1/3
σ1 = +
108 2
As an alternative, you can numerically approximate sols directly by using vpa to return variable-
precision symbolic numbers. The resulting numeric values have the default 32 significant digits,
which are more accurate.
solsVpa = vpa(sols)
solsVpa =
−0.66235897862237301298045442723905 − 0.56227951206230124389918214490937 i
−0.66235897862237301298045442723905 + 0.56227951206230124389918214490937 i
0.5 − 0.86602540378443864676372317075294 i
0.5 + 0.86602540378443864676372317075294 i
1.3247179572447460259609088544781
To use sols without Symbolic Math Toolbox™, you can generate code and convert sols to a
MATLAB® function by using matlabFunction. The generated file uses the roots function that
operates on the numeric double data type.
matlabFunction(sols,"File","myfile");
type myfile
% This function was generated by the Symbolic Math Toolbox version 23.2.
% 20-Aug-2023 01:04:22
t0 = roots([1.0,-1.0,0.0,0.0,0.0,-1.0]);
t2 = t0(1);
t0 = roots([1.0,-1.0,0.0,0.0,0.0,-1.0]);
t3 = t0(2);
t0 = roots([1.0,-1.0,0.0,0.0,0.0,-1.0]);
7-1312
rewrite
t4 = t0(3);
t0 = roots([1.0,-1.0,0.0,0.0,0.0,-1.0]);
t5 = t0(4);
t0 = roots([1.0,-1.0,0.0,0.0,0.0,-1.0]);
t6 = t0(5);
sols = [t2;t3;t4;t5;t6];
end
Find the indefinite integral of a polynomial fraction. The result is in terms of the symsum and root
functions as represented by the ∑ and root symbols.
syms x
F = int(1/(x^3 + x - 1),x)
F =
∑3k = 1 log root z3 − 331z − 31
1
, z, k 3 x + root z3 −
3z
−
31 31
1
, z, k 6 x − 9 root z3 −
3z
−
31 31
1
, z, k
Rewrite the result in terms of arithmetic operations. Because the symbolic summation is the
outermost operation, first apply the rewrite function with the "expandsum" option to expand
symsum. Then, apply rewrite again with the "expandroot" option to rewrite the root function.
The resulting symbolic expression is in terms of arithmetic operations such as ^, *, /, +, and –.
R = rewrite(rewrite(F,"expandsum"),"expandroot")
R =
log 3 x + 6 x − 9 σ3 σ3 σ3 − log − 3 x − 6 x − 9 σ2 σ2 σ2 − log − 3 x − 6 x − 9 σ1 σ1 σ1
where
1
σ4 3 31 σ − σ4 i
1 4
σ1 = + −
62 σ4 2 2
1
σ4 3 31 σ − σ4 i
1 4
σ2 = + +
62 σ4 2 2
1
σ3 = + σ4
31 σ4
27 119164 1 1/3
σ4 = +
119164 62
Input Arguments
expr — Input to rewrite
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix | symbolic multidimensional array
Input to rewrite or replace, specified as a symbolic number, variable, expression, function, vector,
matrix, or multidimensional array.
7-1313
7 Functions
Target function or function to expand, specified as a string scalar or character vector. This table
summarizes the rewriting rules for all allowed target options.
Tips
• rewrite replaces symbolic function calls in expr with another function as specified by target
only if the replacement is mathematically valid. Otherwise, it keeps the original function calls. For
example, see “Rewrite Between Sine and Cosine Functions” on page 7-1311.
7-1314
rewrite
Version History
Introduced in R2012a
You can rewrite or expand symbolic expressions that use the root and symsum functions in terms of
arithmetic operations. For examples, see “Rewrite root Function” on page 7-1311 and “Rewrite
symsum and root Functions” on page 7-1313.
See Also
Functions
collect | combine | expand | factor | horner | numden | simplify | simplifyFraction |
unitConvert
Topics
“Choose Function to Rearrange Expression” on page 3-119
“Simplify Symbolic Expressions Using Live Editor Task” on page 3-134
7-1315
7 Functions
rhs
Right side (RHS) of equation
Syntax
rhsEqn = rhs(eqn)
Description
rhsEqn = rhs(eqn) returns the right side of the symbolic equation eqn. The value of eqn also can
be a symbolic condition, such as x > 0. If eqn is an array, then rhs returns an array of the right sides
of the equations in eqn.
Conditions that use the > or >= operator are internally rewritten using the < or <= operator.
Therefore, rhs returns the original left side. For example, rhs(x > 0) returns x.
Examples
syms x y
eqn = 2*y == x^2
eqn = 2 y = x2
rhsEqn = rhs(eqn)
rhsEqn = x2
syms x y
cond = x < y + 1
cond = x < y + 1
7-1316
rhs
rhsCond = rhs(cond)
rhsCond = y + 1
For an array that contains equations and conditions, rhs returns an array of the right sides of those
equations or conditions. The output array is the same size as the input array.
Find the right side of the equations and conditions in the vector V.
syms x y
V = [y^2 == x^2, x ~= 0, x*y >= 1]
V = y2 = x2 x ≠ 0 1 ≤ x y
rhsV = rhs(V)
rhsV = x2 0 x y
Because any condition using the >= operator is internally rewritten using the <= operator, the sides of
the last condition in V are exchanged.
Find the right side of a symbolic equation that involves symbolic matrix variables.
syms A [2 2] matrix
syms B [2 1] matrix
syms C [1 2] matrix
eqn = B*C == A*A - 2*A + eye(2)
eqn = B C = I2 − 2 A + A2
rhsEqn = rhs(eqn)
rhsEqn = I2 − 2 A + A2
Input Arguments
eqn — Equation or condition
symbolic equation | symbolic condition | vector of symbolic equations or conditions | matrix of
symbolic equations or conditions | multidimensional array of symbolic equations or conditions
7-1317
7 Functions
Version History
Introduced in R2017a
R2022b: Find right side of symbolic equation or condition involving symbolic matrix
variables and matrix functions
The rhs function accepts a symbolic equation or condition involving symbolic matrix variables and
matrix functions as an input argument. The input data type can be symmatrix or symfunmatrix.
For an example, see “Find Right Side of Equation Involving Symbolic Matrix Variables” on page 7-
1317.
See Also
assume | children | lhs | subs
7-1318
root
root
Represent roots of polynomial
Syntax
root(p,x)
root(p,x,k)
Description
root(p,x) returns a column vector of numbered roots of symbolic polynomial p with respect to x.
Symbolically solving a high-degree polynomial for its roots can be complex or mathematically
impossible. In this case, the Symbolic Math Toolbox uses the root function to represent the roots of
the polynomial.
Examples
Represent the roots of the polynomial x3 + 1 using root. The root function returns a column vector.
The elements of this vector represent the three roots of the polynomial.
syms x
p = x^3 + 1;
root(p,x)
ans =
root x3 + 1, x, 1
root x3 + 1, x, 2
root x3 + 1, x, 3
root x3 + 1, x, 1 represents the first root of p, while root x3 + 1, x, 2 represents the second root, and
so on. Use this syntax to represent roots of high-degree polynomials.
When solving a high-degree polynomial, solve represents the roots by using root. Alternatively, you
can either return an explicit solution by using the MaxDegree option or return a numerical result by
using vpa.
7-1319
7 Functions
syms x
p = x^3 + 3*x - 16;
R = solve(p,x)
R =
root z3 + 3 z − 16, z, 1
root z3 + 3 z − 16, z, 2
root z3 + 3 z − 16, z, 3
Find the roots explicitly by setting the MaxDegree option to the degree of the polynomial.
Polynomials with a degree greater than 4 do not have explicit solutions.
Rexplicit = solve(p,x,"MaxDegree",3)
Rexplicit =
1
σ1 −
σ1
1
σ1 3 σ + σ1 i
1 1
− −
2 σ1 2 2
1
σ1 3 σ + σ1 i
1 1
− +
2 σ1 2 2
where
1/3
σ1 = 65 + 8
Calculate the roots numerically by using vpa to convert R to high-precision floating point.
Rnumeric = vpa(R)
Rnumeric =
2.1267693318103912337456401562601
−1.0633846659051956168728200781301 − 2.5283118563671914055545884653776 i
−1.0633846659051956168728200781301 + 2.5283118563671914055545884653776 i
If the call to root contains parameters, substitute the parameters with numbers by using subs
before calling vpa.
You can use the root function as input to Symbolic Math Toolbox functions such as simplify, subs,
and diff.
syms x
r = root(x^6 + x, x, 1);
simplify(sin(r)^2 + cos(r)^2)
ans = 1
7-1320
root
ans = root x2 + 5 x, x, 1
Substituting for parameters using subs is necessary before converting root to numeric form using
vpa.
ans =
root x2 + b x, x, 1
b
Find the inverse Laplace transform of a ratio of two polynomials using ilaplace. The inverse
Laplace transform is returned in terms of root.
syms s
G = (s^3 + 1)/(s^6 + s^5 + s^2);
H = ilaplace(G)
H =
4 3
et root z + z + 1, z, k
t− ∑4k = 1
4 root z4 + z3 + 1, z, k + 3
When you get the root function in output, you can use the root function as input in subsequent
symbolic calculations. However, if a numerical result is required, convert the root function to a high-
precision numeric result using vpa.
Input Arguments
p — Symbolic polynomial
symbolic expression
7-1321
7 Functions
x — Variable
symbolic variable
Tips
• You can numerically approximate a symbolic expression involving the root function by using vpa
to return variable-precision symbolic numbers. Starting in R2023a, you can convert the expression
to a MATLAB function that can be used without Symbolic Math Toolbox by using
matlabFunction. The generated file uses the roots function that operates on the numeric
double data type.
Version History
Introduced in R2015b
See Also
solve | vpa | rewrite
7-1322
rref
rref
Reduced row echelon form of matrix (Gauss-Jordan elimination)
Syntax
rref(A)
Description
rref(A) computes the reduced row echelon form of the symbolic matrix A. If the elements of a
matrix contain free symbolic variables, rref regards the matrix as nonzero.
Examples
Compute the reduced row echelon form of the magic square matrix.
rref(sym(magic(4)))
ans =
[ 1, 0, 0, 1]
[ 0, 1, 0, 3]
[ 0, 0, 1, -3]
[ 0, 0, 0, 0]
Compute the reduced row echelon form of the following symbolic matrix.
syms a b c
A = [a b c; b c a; a + b, b + c, c + a];
rref(A)
ans =
[ 1, 0, -(- c^2 + a*b)/(- b^2 + a*c)]
[ 0, 1, -(- a^2 + b*c)/(- b^2 + a*c)]
[ 0, 0, 0]
Version History
Introduced before R2006a
See Also
eig | jordan | linsolve | rank
7-1323
7 Functions
rsums
Interactive evaluation of Riemann sums
Syntax
rsums(f)
rsums(f,a,b)
rsums(f,[a,b])
Description
rsums(f) interactively approximates the integral of f(x) by middle Riemann sums for x from 0 to 1.
rsums(f) displays a graph of f(x) using 10 terms (rectangles). You can adjust the number of terms
taken in the middle Riemann sum by using the slider below the graph. The number of terms available
ranges from 2 to 128. f can be a character vector or a symbolic expression. The height of each
rectangle is determined by the value of the function in the middle of each interval.
Examples
1
Approximate the integral ∫0 x2 dx by middle Riemann sum. rsums displays a graph of x2 using 10
terms of the midpoint Riemann sum for the integration range from 0 to 1. The total sum is 0.3325.
syms x
rsums(x^2)
Change the integration range of x from -2 to 5. The total Riemann sum is 44.0475.
rsums(x^2,-2,5)
7-1324
rsums
Input Arguments
f — Integrand
symbolic expression | symbolic function | symbolic number
a — Lower bound
number | symbolic number
b — Upper bound
number | symbolic number
Version History
Introduced before R2006a
See Also
taylortool | int | funtool
7-1325
7 Functions
sec
Symbolic secant function
Syntax
sec(X)
Description
sec(X) returns the secant function on page 7-1328 of X.
Examples
Secant Function for Numeric and Symbolic Arguments
Compute the secant function for these numbers. Because these numbers are not symbolic objects,
sec returns floating-point results.
A =
-2.4030 -1.0000 1.1547 -1.6039 225.9531
Compute the secant function for the numbers converted to symbolic objects. For many symbolic
(exact) numbers, sec returns unresolved symbolic calls.
symA =
[ 1/cos(2), -1, (2*3^(1/2))/3, -1/cos((2*pi)/7), 1/cos(11)]
vpa(symA)
ans =
[ -2.4029979617223809897546004014201,...
-1.0,...
1.1547005383792515290182975610039,...
-1.6038754716096765049444092780298,...
225.95305931402493269037542703557]
syms x
fplot(sec(x),[-4*pi 4*pi])
grid on
7-1326
sec
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing sec.
syms x
diff(sec(x), x)
diff(sec(x), x, x)
ans =
sin(x)/cos(x)^2
ans =
1/cos(x) + (2*sin(x)^2)/cos(x)^3
int(sec(x), x)
ans =
log(1/cos(x)) + log(sin(x) + 1)
taylor(sec(x), x)
7-1327
7 Functions
ans =
(5*x^4)/24 + x^2/2 + 1
rewrite(sec(x), 'exp')
ans =
1/(exp(-x*1i)/2 + exp(x*1i)/2)
sec numerically evaluates these units automatically: radian, degree, arcmin, arcsec, and
revolution.
u = symunit;
syms x
f = [x*u.degree 2*u.radian];
secf = sec(f)
secf =
[ 1/cos((pi*x)/180), 1/cos(2)]
You can calculate secf by substituting for x using subs and then using double or vpa.
Input Arguments
X — Input
symbolic number | symbolic scalar variable | symbolic matrix variable | symbolic expression |
symbolic function | symbolic matrix function | symbolic vector | symbolic matrix
Input, specified as a symbolic number, scalar variable, matrix variable, expression, function, matrix
function, or as a vector or matrix of symbolic numbers, scalar variables, expressions, or functions.
More About
Secant Function
1 hypotenuse h
sec(α) = = = .
cos α adjacent side b
7-1328
sec
2
sec(α) = .
eiα + e−iα
Version History
Introduced before R2006a
See Also
acos | asin | atan | acsc | asec | acot | sin | cos | tan | csc | cot
7-1329
7 Functions
sech
Symbolic hyperbolic secant function
Syntax
sech(X)
Description
sech(X) returns the hyperbolic secant function of X.
Examples
Hyperbolic Secant Function for Numeric and Symbolic Arguments
Compute the hyperbolic secant function for these numbers. Because these numbers are not symbolic
objects, sech returns floating-point results.
A =
0.2658 -1.0000 1.1547 1.0000 2.0000 -1.6039 0.6481
Compute the hyperbolic secant function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, sech returns unresolved symbolic calls.
symA =
[ 1/cosh(2), -1, (2*3^(1/2))/3, 1, 2, -1/cosh((pi*2i)/7), 1/cosh(1)]
vpa(symA)
ans =
[ 0.26580222883407969212086273981989,...
-1.0,...
1.1547005383792515290182975610039,...
1.0,...
2.0,...
-1.6038754716096765049444092780298,...
0.64805427366388539957497735322615]
Plot the hyperbolic secant function on the interval from -10 to 10.
7-1330
sech
syms x
fplot(sech(x),[-10, 10])
grid on
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing sech.
Find the first and second derivatives of the hyperbolic secant function:
syms x
diff(sech(x), x)
diff(sech(x), x, x)
ans =
-sinh(x)/cosh(x)^2
ans =
(2*sinh(x)^2)/cosh(x)^3 - 1/cosh(x)
ans =
2*atan(exp(x))
7-1331
7 Functions
taylor(sech(x), x)
ans =
(5*x^4)/24 - x^2/2 + 1
rewrite(sech(x), 'exp')
ans =
1/(exp(-x)/2 + exp(x)/2)
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Version History
Introduced before R2006a
See Also
acosh | asinh | atanh | acsch | asech | acoth | sinh | cosh | tanh | csch | coth
7-1332
separateUnits
separateUnits
Separate units from expression
Syntax
[Data,Units] = separateUnits(expr)
Data = separateUnits(expr)
Description
[Data,Units] = separateUnits(expr) returns the symbolic units of the symbolic expression
expr in Units and the rest of expr in Data.
Data = separateUnits(expr) removes symbolic units from expr and then returns the rest.
Examples
Separate the units from the expression 10*t*u.m/u.s, where u = symunit, by providing two
output arguments for separateUnits.
u = symunit;
syms t
speed = 10*t*u.m/u.s;
[Data,Units] = separateUnits(speed)
Data = 10 t
Units =
m
s
Return only the expression with the units removed by providing one output argument.
Data = separateUnits(speed)
Data = 10 t
If the input has compatible units that can be converted to the same unit, then separateUnits
performs the conversion and returns the separated result. Units are compatible when they have the
same dimensions (although the conversion factor may not necessarily be 1).
Separate the units from 2*u.m + 30*u.cm + 12*u.in. Even though the units differ,
separateUnits converts them to the same unit and returns the separated result.
7-1333
7 Functions
u = symunit;
[Data,Units] = separateUnits(2*u.m + 30*u.cm + 12*u.in)
Data =
1628
625
Units = m
Input Arguments
expr — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic equation | symbolic multidimensional array | symbolic function |
symbolic expression
When adding or subtracting quantities with different units in expr, the units must be compatible.
Units are compatible when they have the same dimensions. For example, see “Separate Compatible
Units” on page 7-1333.
Output Arguments
Data — Expression after removing units
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic equation | symbolic multidimensional array | symbolic function |
symbolic expression
Expression after removing units, returned as a number, vector, matrix, or multidimensional array, or a
symbolic number, variable, vector, matrix, equation, multidimensional array, function, or expression.
Tips
• If an expression has incompatible units, then separateUnits errors. Units are incompatible
when they do not have the same dimensions, such as length and time.
u = symunit;
[Data,Units] = separateUnits(2*u.m + 3*u.s)
Units =
[[m], [s]]
7-1334
separateUnits
Version History
Introduced in R2017a
Starting in R2022b, separateUnits returns a simplified expression after separating units. For
example, separate the units from an expression expr, and return the remaining expression as Data
and the units as Units.
u = symunit;
syms t tau;
t_s = t*u.s;
t_0 = 0.01*u.s;
tau_s = tau*u.s;
a = 2*u.V;
b = 6*u.V;
expr = a + b*exp(-(t_s-t_0)/tau_s)
[Data,Units] = separateUnits(expr)
expr =
2*[V] + 6*exp((((1/100)*[s] + (-t)*[s])/tau)*(1/[s]))*[V]
Data =
6*exp(-(100*t - 1)/(100*tau)) + 2
Units =
[V]
See Also
checkUnits | findUnits | isUnit | newUnit | symunit | str2symunit | symunit2str |
unitConversionFactor
Topics
“Units of Measurement Tutorial” on page 2-47
“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)
7-1335
7 Functions
series
Puiseux series
Syntax
series(f,var)
series(f,var,a)
series( ___ ,Name,Value)
Description
series(f,var) approximates f with the Puiseux series expansion of f up to the fifth order at the
point var = 0. If you do not specify var, then series uses the default variable determined by
symvar(f,1).
series(f,var,a) approximates f with the Puiseux series expansion of f at the point var = a.
series( ___ ,Name,Value) uses additional options specified by one or more Name,Value pair
arguments. You can specify Name,Value after the input arguments in any of the previous syntaxes.
Examples
Find Puiseux Series Expansion
ans =
x/6 + 1/x + (7*x^3)/360
Find the Puiseux series expansion of this multivariate expression. If you do not specify the expansion
variable, series uses the default variable determined by symvar(f,1).
syms s t
f = sin(s)/sin(t);
symvar(f, 1)
series(f)
ans =
t
ans =
sin(s)/t + (7*t^3*sin(s))/360 + (t*sin(s))/6
7-1336
series
ans =
s^5/(120*sin(t)) - s^3/(6*sin(t)) + s/sin(t)
Find the Puiseux series expansion of psi(x) around x = Inf. The default expansion point is 0. To
specify a different expansion point, use the ExpansionPoint name-value pair.
ans =
log(x) - 1/(2*x) - 1/(12*x^2) + 1/(120*x^4)
syms x
series(psi(x), x, Inf)
ans =
log(x) - 1/(2*x) - 1/(12*x^2) + 1/(120*x^4)
Find the Puiseux series expansion of exp(x)/x using different truncation orders.
syms x
f = exp(x)/x;
s6 = series(f, x)
s6 =
x 1 x2 x3 x4
+ + + + +1
2 x 6 24 120
Use Order to control the truncation order. For example, approximate the same expression up to the
orders 7 and 8.
s7 = series(f, x, 'Order', 7)
s7 =
x 1 x2 x3 x4 x5
+ + + + + +1
2 x 6 24 120 720
s8 = series(f, x, 'Order', 8)
s8 =
x 1 x2 x3 x4 x5 x6
+ + + + + + +1
2 x 6 24 120 720 5040
Plot the original expression f and its approximations s6, s7, and s8. Note how the accuracy of the
approximation depends on the truncation order.
fplot([s6 s7 s8 f])
legend('approximation up to O(x^6)','approximation up to O(x^7)',...
'approximation up to O(x^8)','exp(x)/x','Location', 'Best')
title('Puiseux Series Expansion')
7-1337
7 Functions
Find the Puiseux series approximations using the Direction argument. This argument lets you
change the convergence area, which is the area where series tries to find converging Puiseux series
expansion approximating the original expression.
Find the Puiseux series approximation of this expression. By default, series finds the approximation
that is valid in a small open circle in the complex plane around the expansion point.
syms x
series(sin(sqrt(-x)), x)
ans =
(-x)^(1/2) - (-x)^(3/2)/6 + (-x)^(5/2)/120
Find the Puiseux series approximation of the same expression that is valid in a small interval to the
left of the expansion point. Then, find an approximation that is valid in a small interval to the right of
the expansion point.
syms x
series(sin(sqrt(-x)), x)
series(sin(sqrt(-x)), x, 'Direction', 'left')
series(sin(sqrt(-x)), x, 'Direction', 'right')
ans =
(-x)^(1/2) - (-x)^(3/2)/6 + (-x)^(5/2)/120
7-1338
series
ans =
- x^(1/2)*1i - (x^(3/2)*1i)/6 - (x^(5/2)*1i)/120
ans =
x^(1/2)*1i + (x^(3/2)*1i)/6 + (x^(5/2)*1i)/120
Try computing the Puiseux series approximation of this expression. By default, series tries to find
an approximation that is valid in the complex plane around the expansion point. For this expression,
such approximation does not exist.
series(real(sin(x)), x)
However, the approximation exists along the real axis, to both sides of x = 0.
ans =
x^5/120 - x^3/6 + x
Input Arguments
f — Input to approximate
symbolic expression | symbolic function | symbolic vector | symbolic matrix | symbolic
multidimensional array
Input to approximate, specified as a symbolic expression or function. It also can be a vector, matrix,
or multidimensional array of symbolic expressions or functions.
Expansion variable, specified as a symbolic variable. If you do not specify var, then series uses the
default variable determined by symvar(f,1).
a — Expansion point
0 (default) | number | symbolic number | symbolic variable | symbolic function | symbolic expression
Expansion point, specified as a number, or a symbolic number, variable, function, or expression. The
expansion point cannot depend on the expansion variable.
You also can specify the expansion point as a Name,Value pair argument. If you specify the
expansion point both ways, then the Name,Value pair argument takes precedence.
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: series(psi(x),x,'ExpansionPoint',Inf,'Order',9)
7-1339
7 Functions
Expansion point, specified as a number, or a symbolic number, variable, function, or expression. The
expansion point cannot depend on the expansion variable.
You can also specify the expansion point using the input argument a. If you specify the expansion
point both ways, then the Name,Value pair argument takes precedence.
Truncation order of Puiseux series expansion, specified as a positive integer or a symbolic positive
integer.
series computes the Puiseux series approximation with the order n - 1. The truncation order n is
the exponent in the O-term: O(varn).
'left' Find a Puiseux series approximation that is valid in a small interval to the
left of the expansion point.
'right' Find a Puiseux series approximation that is valid in a small interval to the
right of the expansion point.
'realAxis' Find a Puiseux series approximation that is valid in a small interval on the
both sides of the expansion point.
'complexPlane' Find a Puiseux series approximation that is valid in a small open circle in
the complex plane around the expansion point. This is the default value.
Tips
• If you use both the third argument a and the ExpansionPoint name-value pair to specify the
expansion point, the value specified via ExpansionPoint prevails.
Version History
Introduced in R2015b
See Also
pade | taylor
7-1340
sign
sign
Sign of real or complex value
Syntax
sign(z)
Description
sign(z) returns the sign of real or complex value z. The sign of a complex number z is defined as z/
abs(z). If z is a vector or a matrix, sign(z) returns the sign of each element of z.
Examples
Signs of Real Numbers
ans =
[ 1, 0, -1]
ans =
[ 5^(1/2)*(1/5 + 2i/5), -1]
[ 2^(1/2)*(- 1/2 + 1i/2), 5^(1/2)*18^(1/2)*(1/30 - 1i/10)]
Find the sign of this expression assuming that the value x is negative:
syms x
assume(x < 0)
sign(5*x^3)
ans =
-1
syms x
7-1341
7 Functions
Input Arguments
z — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
More About
Sign Function
The sign function of any number z is defined via the absolute value of z:
z
sign z =
z
−1 if x < 0
sign z = 0 if x = 0
1 if x > 0
Tips
• Calling sign for a number that is not a symbolic object invokes the MATLAB sign function.
Version History
Introduced in R2013a
See Also
abs | angle | imag | real | signIm
7-1342
signIm
signIm
Sign of the imaginary part of complex number
Syntax
signIm(z)
Description
signIm(z) returns the sign of the imaginary part of a complex number z. For all complex numbers
with a nonzero imaginary part, signIm(z) = sign(imag(z)). For real numbers, signIm(z) = -
sign(z).
Examples
Symbolic Results Including signIm
Results of symbolic computations, especially symbolic integration, can include the signIm function.
Integrate this expression. For complex values a and x, this integral includes signIm.
syms a x
f = 1/(a^2 + x^2);
F = int(f, x, -Inf, Inf)
F =
(pi*signIm(1i/a))/a
Find the signs of imaginary parts of complex numbers with nonzero imaginary parts and of real
numbers.
Use signIm to find the signs of imaginary parts of these numbers. For complex numbers with
nonzero imaginary parts, signIm returns the sign of the imaginary part of the number.
ans =
1 -1 1 -1 1 -1
7-1343
7 Functions
ans =
-1 -1 -1 -1
ans =
1 1 1 1
signIm(0) is 0.
ans =
0 0 0
Find the signs of imaginary parts of symbolic expressions that represent complex numbers.
Call signIm for these symbolic expressions without additional assumptions. Because signIm cannot
determine if the imaginary part of a symbolic expression is positive, negative, or zero, it returns
unresolved symbolic calls.
syms x y z
[signIm(z), signIm(x + y*i), signIm(x - 3*i)]
ans =
[ signIm(z), signIm(x + y*1i), signIm(x - 3i)]
Assume that x, y, and z are positive values. Find the signs of imaginary parts of the same symbolic
expressions.
syms x y z positive
[signIm(z), signIm(x + y*i), signIm(x - 3*i)]
ans =
[ -1, 1, -1]
For further computations, clear the assumptions by recreating the variables using syms.
syms x y z
Find the first derivative of the signIm function. signIm is a constant function, except for the jump
discontinuities along the real axis. The diff function ignores these discontinuities.
syms z
diff(signIm(z), z)
ans =
0
singIm accepts vectors and matrices as its input argument. This lets you find the signs of imaginary
parts of several numbers in one function call.
Find the signs of imaginary parts of the real and complex elements of matrix A.
7-1344
signIm
ans =
[ 1, 1]
[ 1, -1]
Input Arguments
z — Input representing complex number
number | symbolic number | symbolic variable | symbolic expression | vector | matrix
Input representing complex number, specified as a number, symbolic number, symbolic variable,
expression, vector, or matrix.
Tips
• signIm(NaN) returns NaN.
Version History
Introduced in R2014b
See Also
conj | imag | real | sign
7-1345
7 Functions
simplify
Algebraic simplification
Syntax
S = simplify(expr)
S = simplify(expr,Name,Value)
Description
S = simplify(expr) performs algebraic simplification of expr. If expr is a symbolic vector or
matrix, this function simplifies each element of expr.
Examples
Simplify Expressions
syms x a b c
S = simplify(sin(x)^2 + cos(x)^2)
S = 1
S = simplify(exp(c*log(sqrt(a+b))))
c/2
S = a+b
Call simplify for this symbolic matrix. When the input argument is a vector or matrix, simplify
tries to find a simpler form of each element of the vector or matrix.
syms x
M = [(x^2 + 5*x + 6)/(x + 2), sin(x)*sin(2*x) + cos(x)*cos(2*x);
(exp(-x*1i)*1i)/2 - (exp(x*1i)*1i)/2, sqrt(16)];
S = simplify(M)
S =
x + 3 cos x
sin x 4
7-1346
simplify
Simplify a symbolic expression that contains logarithms and powers. By default, simplify does not
combine powers and logarithms because combining them is not valid for generic complex values.
syms x
expr = (log(x^2 + 2*x + 1) - log(x + 1))*sqrt(x^2);
S = simplify(expr)
2
S = − log x + 1 − log x + 1 x2
To apply the simplification rules that allow the simplify function to combine powers and logarithms,
set 'IgnoreAnalyticConstraints' to true:
S = simplify(expr,'IgnoreAnalyticConstraints',true)
S = x log x + 1
syms x
expr = ((exp(-x*1i)*1i) - (exp(x*1i)*1i))/(exp(-x*1i) + exp(x*1i));
S = simplify(expr)
S =
e2 x i i − i
−
e2 x i + 1
By default, simplify uses one internal simplification step. You can get different, often shorter,
simplification results by increasing the number of simplification steps:
S10 = simplify(expr,'Steps',10)
S10 =
2 i
− i
e2 x i + 1
S30 = simplify(expr,'Steps',30)
S30 =
cos x − sin x i i
− i
cos x
S50 = simplify(expr,'Steps',50)
S50 = tan x
If you are unable to return the desired result, try alternate simplification functions. See “Choose
Function to Rearrange Expression” on page 3-119.
7-1347
7 Functions
Get equivalent results for a symbolic expression by setting the value of 'All' to true.
syms x
expr = cos(x)^2 - sin(x)^2;
S = simplify(expr,'All',true)
S =
cos 2 x
2 2
cos x − sin x
Increase the number of simplification steps to 10. Find the other equivalent results for the same
expression.
S = simplify(expr,'Steps',10,'All',true)
S =
cos 2 x
2
1 − 2 sin x
2
2 cos x −1
2 2
cos x − sin x
cot 2 x sin 2 x
e−2 x i e2 x i
+
2 2
Attempt to separate real and imaginary parts of an expression by setting the value of 'Criterion'
to 'preferReal'.
syms x
f = (exp(x + exp(-x*1i)/2 - exp(x*1i)/2)*1i)/2 -...
(exp(-x - exp(-x*1i)/2 + exp(x*1i)/2)*1i)/2;
S = simplify(f,'Criterion','preferReal','Steps',100)
If 'Criterion' is not set to 'preferReal', then simplify returns a shorter result but the real
and imaginary parts are not separated.
S = simplify(f,'Steps',100)
S = sin sin x + x i
When you set 'Criterion' to 'preferReal', the simplifier disfavors expression forms where
complex values appear inside subexpressions. In nested subexpressions, the deeper the complex
value appears inside an expression, the least preference this form of an expression gets.
7-1348
simplify
Show this behavior by simplifying a complex symbolic expression with and without setting
'Criterion' to 'preferReal'. When 'Criterion' is set to 'preferReal', then simplify
places the imaginary term outside the exponent.
expr = sym(1i)^(1i+1);
withoutPreferReal = simplify(expr,'Steps',100)
withoutPreferReal =
1 1
+ i
−1 2 2
withPreferReal = simplify(expr,'Criterion','preferReal','Steps',100)
withPreferReal =
π
e− 2 i
Simplify Units
Simplify expressions containing symbolic units of the same dimension by using simplify.
u = symunit;
expr = 300*u.cm + 40*u.inch + 2*u.m;
S = simplify(expr)
S =
752
m
125
simplify automatically chooses the unit to rewrite into. To choose a specific unit, use rewrite.
In most cases, to simplify a symbolic expression using Symbolic Math Toolbox™, you only need to use
the simplify function. But for some large and complex expressions, you can obtain a faster and
simpler result by using the expand function before applying simplify.
For instance, this workflow gives better results when finding the determinant of a matrix that
represents the Kerr metric [1]. Declare the parameters of the Kerr metric.
7-1349
7 Functions
g(4,1) = - (rs*a*r*sin(theta)^2)/rho^2;
g(2,2) = rho^2/delta;
g(3,3) = rho^2;
g(4,4) = (r^2 + a^2 + rs*a^2*r*sin(theta)^2/rho^2)*sin(theta)^2;
det_g = det(g)
det_g =
2 4 4 2 2 2 2 2
sin θ a6 cos θ + a4 r 2 cos θ + 2 a4 r 2 cos θ + rs a4 r cos θ sin θ − rs a4 r cos θ + 2 a2 r 4 cos θ + a2 r 4 − rs a
−
a2 + r 2 − rs r
D = simplify(det_g)
2 2 2
D = −sin θ a2 cos θ + r 2 −a2 sin θ + a2 + r 2
Instead, flatten the expression using the expand function, and then apply the simplify function.
The result is simpler with this extra step.
D = simplify(expand(det_g))
2 2 2
D = −sin θ −a2 sin θ + a2 + r 2
Input Arguments
expr — Input expression
symbolic expression | symbolic function | symbolic vector | symbolic matrix
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: 'Seconds',60 limits the simplification process to 60 seconds.
Option to return equivalent results, specified as the comma-separated pair consisting of 'All' and
either of the two logical values. When you use this option, the input argument expr must be a scalar.
false Use the default option to return only the final simplification result.
7-1350
simplify
true Return a column vector of equivalent results for the input expression. You
can use this option along with the 'Steps' option to obtain alternative
expressions in the simplification process.
Simplification criterion, specified as the comma-separated pair consisting of 'Criterion' and one
of these character vectors.
false Use strict simplification rules. simplify always returns results that are
analytically equivalent to the initial expression.
true Apply purely algebraic simplifications to expressions. Setting
IgnoreAnalyticConstraints to true can give you simpler solutions,
which could lead to results not generally valid. In other words, this option
applies mathematical identities that are convenient, but the results might
not hold for all possible values of the variables. In some cases, the results
might not be equivalent to the initial expression. For details, see
“Algorithms” on page 7-1352.
Time limit for the simplification process, specified as the comma-separated pair consisting of
'Seconds' and a positive value that denotes the maximal time in seconds.
Number of simplification steps, specified as the comma-separated pair consisting of 'Steps' and a
positive value that denotes the maximal number of internal simplification steps. Note that increasing
the number of simplification steps can slow down your computations.
7-1351
7 Functions
Tips
• Simplification of mathematical expression is not a clearly defined subject. There is no universal
idea as to which form of an expression is simplest. The form of a mathematical expression that is
simplest for one problem might be complicated or even unsuitable for another problem.
Algorithms
When you use IgnoreAnalyticConstraints, then simplify follows some of these rules:
• log(a) + log(b) = log(a·b) for all values of a and b. In particular, the following equality is valid for
all values of a, b, and c:
(a·b)c = ac·bc.
• log(ab) = b·log(a) for all values of a and b. In particular, the following equality is valid for all values
of a, b, and c:
(ab)c = ab·c.
• If f and g are standard mathematical functions and f(g(x)) = x for all small positive numbers,
f(g(x)) = x is assumed to be valid for all complex values of x. In particular:
• log(ex) = x
• asin(sin(x)) = x, acos(cos(x)) = x, atan(tan(x)) = x
• asinh(sinh(x)) = x, acosh(cosh(x)) = x, atanh(tanh(x)) = x
• Wk(x·ex) = x for all branch indices k of the Lambert W function.
Version History
Introduced before R2006a
References
[1] Zee, A. Einstein Gravity in a Nutshell. Princeton: Princeton University Press, 2013.
See Also
Functions
collect | combine | expand | factor | horner | numden | rewrite | simplifyFraction
Topics
“Simplify Symbolic Expressions” on page 3-129
“Choose Function to Rearrange Expression” on page 3-119
“Simplify Symbolic Expressions Using Live Editor Task” on page 3-134
7-1352
simplifyFraction
simplifyFraction
Simplify symbolic rational expressions
Syntax
simplifyFraction(expr)
simplifyFraction(expr,'Expand',true)
Description
simplifyFraction(expr) simplifies the rational expression expr such that the numerator and
denominator have no divisors in common.
Examples
syms x y
fraction = (x^2-1)/(x+1);
simplifyFraction(fraction)
ans =
x - 1
fraction = (y*(x^2-1))/((x+1)*(x-1));
simplifyFraction(fraction)
ans =
y
syms x y
fraction = ((y+1)^2*(x^2-1))/((x+1)*(x-1)^2);
simplifyFraction(fraction)
ans =
(y + 1)^2/(x - 1)
Simplify the same rational expression again. Expand the numerator and denominator of the resulting
fraction by setting 'Expand' to true.
7-1353
7 Functions
simplifyFraction(fraction,'Expand',true)
ans =
(y^2 + 2*y + 1)/(x - 1)
syms x
expr = ((x^2+2*x+1)/(x+1))^(1/2);
simplifyFraction(expr)
ans =
(x + 1)^(1/2)
expr = (1-sin(x)^2)/(1-sin(x));
simplifyFraction(expr)
ans =
sin(x) + 1
simplifyFraction does not apply algebraic identities to simplify the rational expression. Show that
simplifyFraction does not apply standard trigonometric identities.
expr = (1-cos(x)^2)/sin(x);
simplifyFraction(expr)
ans =
-(cos(x)^2 - 1)/sin(x)
Input Arguments
expr — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
Tips
• expr can contain irrational subexpressions, such as sin(x) and x^(-1/3). simplifyFraction
simplifies such expressions as if they were variables.
• simplifyFraction does not apply algebraic identities.
Alternatives
You can also simplify rational expressions using the general simplification function simplify.
However, simplifyFraction is more efficient for simplifying rational expressions.
7-1354
simplifyFraction
Version History
Introduced in R2011b
See Also
Functions
collect | combine | expand | factor | horner | numden | rewrite | simplify
Topics
“Simplify Symbolic Expressions” on page 3-129
“Choose Function to Rearrange Expression” on page 3-119
“Simplify Symbolic Expressions Using Live Editor Task” on page 3-134
7-1355
7 Functions
Description
The Simplify Symbolic Expression task enables you to interactively simplify or rearrange symbolic
expressions. The task automatically generates MATLAB code for your live script. For more
information about Live Editor tasks, see “Add Interactive Tasks to a Live Script”.
Related Functions
The code that Simplify Symbolic Expression generates to simplify expressions uses these
functions.
• simplify
• simplifyFraction
• rewrite
• expand
• combine
7-1356
Simplify Symbolic Expression
The code that Simplify Symbolic Expression generates to simplify expressions uses these
functions.
• simplify
• simplifyFraction
• rewrite
• expand
• combine
• On the Live Editor tab, select Task > Simplify Symbolic Expression.
• In a code block in your script, type a relevant keyword, such as simplify, symbolic, rewrite,
expand, or combine. Select Simplify Symbolic Expression from the suggested command
completions.
7-1357
7 Functions
Parameters
Method — Specify simplification method
Simplify (default) | Simplify fraction | Rewrite | Expand | Combine
Specify the computational effort used for the Simplify method from the drop-down list:
Select this check box to not expand special functions for the Expand method. This option expands the
arithmetic part of an expression, such as powers and roots, without expanding trigonometric,
hyperbolic, logarithmic, and special functions.
Select this check box to apply purely algebraic simplifications to the Expand method, such as log(a)
+ log(b) = log(a*b) with the assumption that a and b are real positive numbers. Setting Ignore
analytic constraints to on can give you simpler solutions, which could lead to results not
generally valid. This option applies mathematical identities that are convenient for most engineering
workflow, but do not always hold for all values of variables. In some cases, this option can lead to
simpler results that are not equivalent to the initial expression. For details, see “Algorithms” on page
7-1359.
7-1358
Simplify Symbolic Expression
Algorithms
When you use Ignore analytic constraints, then the simplification follows some of these rules:
• log(a) + log(b) = log(a·b) for all values of a and b. In particular, the following equality is valid for
all values of a, b, and c :
(a·b)c = ac·bc.
• log(ab) = b·log(a) for all values of a and b. In particular, the following equality is valid for all values
of a, b, and c :
(ab)c = ab·c.
• If f and g are standard mathematical functions and f(g(x)) = x for all small positive numbers,
f(g(x)) = x is assumed to be valid for all complex values of x. In particular:
• log(ex) = x
• asin(sin(x)) = x, acos(cos(x)) = x, atan(tan(x)) = x
• asinh(sinh(x)) = x, acosh(cosh(x)) = x, atanh(tanh(x)) = x
• Wk(x·ex) = x for all branch indices k of the Lambert W function.
Version History
Introduced in R2020a
See Also
Functions
simplify | simplifyFraction | combine | expand | rewrite
Topics
“Add Interactive Tasks to a Live Script”
“Simplify Symbolic Expressions Using Live Editor Task” on page 3-134
“Choose Function to Rearrange Expression” on page 3-119
“Simplify Symbolic Expressions” on page 3-129
7-1359
7 Functions
simscapeEquation
Convert symbolic expressions to Simscape language equations
Syntax
simscapeEquation(f)
simscapeEquation(LHS,RHS)
Description
simscapeEquation(f) converts the symbolic expression f to a Simscape language equation. This
function call converts any derivative with respect to the variable t to the Simscape notation X.der.
Here X is the time-dependent variable. In the resulting Simscape equation, the variable time
replaces all instances of the variable t except for derivatives with respect to t.
simscapeEquation converts expressions with the second and higher-order derivatives to a system
of first-order equations, introducing new variables, such as x1, x2, and so on.
Examples
ans =
'phi == sin(time)+y*5.0+x.der;'
ans =
'y.der == sin(time)+y*5.0+x.der;'
syms x(t)
eqn1 = diff(x,2) - diff(x) + sin(t);
simscapeEquation(eqn1)
ans =
'x.der == x1;
eqn1 == sin(time)-x1+x1.der;'
7-1360
simscapeEquation
ans =
'x.der == x1;
x1.der == x2;
x2.der == x3;
eqn2 == sin(time)-x1+x2+x3.der;'
Tips
• The equation section of a Simscape component file supports a limited number of functions. For
details and the list of supported functions, see Simscape equations (Simscape). If a symbolic
equation contains functions that are not available in the equation section of a Simscape
component file, simscapeEquation cannot convert these equations correctly to Simscape
equations. Such expressions do not trigger an error message. Expressions with infinities are prone
to invalid conversion.
Version History
Introduced in R2010a
See Also
matlabFunctionBlock | matlabFunction | ccode | fortran | symWriteSSC
Topics
“Generate Simscape Equations from Symbolic Expressions” on page 5-8
7-1361
7 Functions
sin
Symbolic sine function
Syntax
sin(X)
Description
sin(X) returns the sine function on page 7-1364 of X.
Examples
Sine Function for Numeric and Symbolic Arguments
Compute the sine function for these numbers. Because these numbers are not symbolic objects, sin
returns floating-point results.
A =
-0.9093 -0.0000 0.5000 0.7818 -1.0000
Compute the sine function for the numbers converted to symbolic objects. For many symbolic (exact)
numbers, sin returns unresolved symbolic calls.
symA =
[ -sin(2), 0, 1/2, sin((2*pi)/7), sin(11)]
vpa(symA)
ans =
[ -0.90929742682568169539601986591174,...
0,...
0.5,...
0.78183148246802980870844452667406,...
-0.99999020655070345705156489902552]
syms x
fplot(sin(x),[-4*pi 4*pi])
grid on
7-1362
sin
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing sin.
syms x
diff(sin(x), x)
diff(sin(x), x, x)
ans =
cos(x)
ans =
-sin(x)
int(sin(x), x)
ans =
-cos(x)
taylor(sin(x), x)
7-1363
7 Functions
ans =
x^5/120 - x^3/6 + x
rewrite(sin(x), 'exp')
ans =
(exp(-x*1i)*1i)/2 - (exp(x*1i)*1i)/2
sin numerically evaluates these units automatically: radian, degree, arcmin, arcsec, and
revolution.
u = symunit;
syms x
f = [x*u.degree 2*u.radian];
sinf = sin(f)
sinf =
[ sin((pi*x)/180), sin(2)]
You can calculate sinf by substituting for x using subs and then using double or vpa.
Input Arguments
X — Input
symbolic number | symbolic scalar variable | symbolic matrix variable | symbolic expression |
symbolic function | symbolic matrix function | symbolic vector | symbolic matrix
Input, specified as a symbolic number, scalar variable, matrix variable, expression, function, matrix
function, or as a vector or matrix of symbolic numbers, scalar variables, expressions, or functions.
More About
Sine Function
opposite side a
sin α = = .
hypotenuse h
7-1364
sin
eiα − e−iα
sin α = .
2i
Version History
Introduced before R2006a
See Also
acos | asin | atan | acsc | asec | acot | cos | tan | csc | sec | sinc | cot
7-1365
7 Functions
sinc
Normalized sinc function
Syntax
sinc(x)
Description
sinc(x) returns sin(pi*x)/(pi*x). The symbolic sinc function does not implement floating-
point results, only symbolic results. Floating-point results are returned by the sinc function in Signal
Processing Toolbox™.
Examples
syms x
sinc(x)
ans =
sin π x
xπ
Show that sinc returns 1 at 0, 0 at other integer inputs, and exact symbolic values for other inputs.
V = sym([-1 0 1 3/2]);
S = sinc(V)
S =
2
010−
3π
Convert the exact symbolic output to high-precision floating point by using vpa.
vpa(S)
Although sinc can appear in tables of Fourier transforms, fourier does not return sinc in output.
syms x
fourier(rectangularPulse(x))
7-1366
sinc
ans =
w w w w
sin 2 + cos 2 i −sin 2 + cos 2 i
−
w w
ans =
π heaviside π − w − π heaviside −w − π
π
Rewrite the sinc function to the exponential function exp by using rewrite.
7-1367
7 Functions
syms x
rewrite(sinc(x),'exp')
ans =
e−π x i i eπ x i i
2
− 2
xπ
Differentiate, integrate, and expand sinc by using the diff, int, and taylor functions,
respectively.
Differentiate sinc.
syms x
diff(sinc(x))
ans =
cos π x sin π x
−
x x2 π
int(sinc(x),[-Inf Inf])
ans = 1
int(sinc(x),-Inf,x)
ans =
sinint π x 1
+
π 2
taylor(sinc(x))
ans =
π4 x4 π2 x2
− +1
120 6
Prove an identity by defining the identity as a condition and using the isAlways function to check
the condition.
1
Prove the identity sinc x = Γ 1+x Γ 1−x
.
7-1368
sinc
syms x
cond = sinc(x) == 1/(gamma(1+x)*gamma(1-x));
isAlways(cond)
ans = logical
1
Input Arguments
x — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
Version History
Introduced in R2018b
See Also
sin
7-1369
7 Functions
sinh
Symbolic hyperbolic sine function
Syntax
sinh(X)
Description
sinh(X) returns the hyperbolic sine function of X.
Examples
Hyperbolic Sine Function for Numeric and Symbolic Arguments
Compute the hyperbolic sine function for these numbers. Because these numbers are not symbolic
objects, sinh returns floating-point results.
A = sinh([-2, -pi*i, pi*i/6, 5*pi*i/7, 3*pi*i/2])
A =
-3.6269 + 0.0000i 0.0000 - 0.0000i 0.0000 + 0.5000i...
0.0000 + 0.7818i 0.0000 - 1.0000i
Compute the hyperbolic sine function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, sinh returns unresolved symbolic calls.
symA = sinh(sym([-2, -pi*i, pi*i/6, 5*pi*i/7, 3*pi*i/2]))
symA =
[ -sinh(2), 0, 1i/2, sinh((pi*2i)/7), -1i]
ans =
[ -3.6268604078470187676682139828013,...
0,...
0.5i,...
0.78183148246802980870844452667406i,...
-1.0i]
7-1370
sinh
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing sinh.
Find the first and second derivatives of the hyperbolic sine function:
syms x
diff(sinh(x), x)
diff(sinh(x), x, x)
ans =
cosh(x)
ans =
sinh(x)
int(sinh(x), x)
ans =
cosh(x)
taylor(sinh(x), x)
7-1371
7 Functions
ans =
x^5/120 + x^3/6 + x
rewrite(sinh(x), 'exp')
ans =
exp(x)/2 - exp(-x)/2
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Version History
Introduced before R2006a
See Also
acosh | asinh | atanh | acsch | asech | acoth | cosh | tanh | csch | sech | coth
7-1372
sinhint
sinhint
Hyperbolic sine integral function
Syntax
sinhint(X)
Description
sinhint(X) returns the hyperbolic sine integral function on page 7-1375 of X.
Examples
Hyperbolic Sine Integral Function for Numeric and Symbolic Arguments
Compute the hyperbolic sine integral function for these numbers. Because these numbers are not
symbolic objects, sinhint returns floating-point results.
A =
-5.4696 -1.0573 0 1.8027 53.7368
Compute the hyperbolic sine integral function for the numbers converted to symbolic objects. For
many symbolic (exact) numbers, sinhint returns unresolved symbolic calls.
symA =
[ -sinhint(pi), -sinhint(1), 0, sinhint(pi/2), sinhint(2*pi)]
vpa(symA)
ans =
[ -5.4696403451153421506369580091277,...
-1.0572508753757285145718423548959,...
0,...
1.802743198288293882089794577617,...
53.736750620859153990408011863262]
Plot the hyperbolic sine integral function on the interval from -2*pi to 2*pi.
syms x
fplot(sinhint(x),[-2*pi 2*pi])
grid on
7-1373
7 Functions
Many functions, such as diff, int, and taylor, can handle expressions containing sinhint.
Find the first and second derivatives of the hyperbolic sine integral function:
syms x
diff(sinhint(x), x)
diff(sinhint(x), x, x)
ans =
sinh(x)/x
ans =
cosh(x)/x - sinh(x)/x^2
int(sinhint(x), x)
ans =
x*sinhint(x) - cosh(x)
taylor(sinhint(x), x)
7-1374
sinhint
ans =
x^5/600 + x^3/18 + x
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
More About
Hyperbolic Sine Integral Function
Version History
Introduced in R2014a
References
[1] Gautschi, W. and W. F. Cahill. “Exponential Integral and Related Functions.” Handbook of
Mathematical Functions with Formulas, Graphs, and Mathematical Tables. (M. Abramowitz
and I. A. Stegun, eds.). New York: Dover, 1972.
See Also
coshint | cosint | eulergamma | int | sin | sinint | ssinint
7-1375
7 Functions
sinint
Sine integral function
Syntax
sinint(X)
Description
sinint(X) returns the sine integral function of X.
Examples
Sine Integral Function for Numeric and Symbolic Arguments
Compute the sine integral function for these numbers. Because these numbers are not symbolic
objects, sinint returns floating-point results.
A =
-1.8519 0 1.3708 1.8519 0.9461
Compute the sine integral function for the numbers converted to symbolic objects. For many symbolic
(exact) numbers, sinint returns unresolved symbolic calls.
symA =
[ -sinint(pi), 0, sinint(pi/2), sinint(pi), sinint(1)]
vpa(symA)
ans =
[ -1.851937051982466170361053370158,...
0,...
1.3707621681544884800696782883816,...
1.851937051982466170361053370158,...
0.94608307036718301494135331382318]
Plot the sine integral function on the interval from -4*pi to 4*pi.
syms x
fplot(sinint(x),[-4*pi 4*pi])
grid on
7-1376
sinint
Many functions, such as diff, int, and taylor, can handle expressions containing sinint.
Find the first and second derivatives of the sine integral function:
syms x
diff(sinint(x), x)
diff(sinint(x), x, x)
ans =
sin(x)/x
ans =
cos(x)/x - sin(x)/x^2
int(sinint(x), x)
ans =
cos(x) + x*sinint(x)
taylor(sinint(x), x)
7-1377
7 Functions
ans =
x^5/600 - x^3/18 + x
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
More About
Sine Integral Function
Version History
Introduced before R2006a
References
[1] Gautschi, W. and W. F. Cahill. “Exponential Integral and Related Functions.” Handbook of
Mathematical Functions with Formulas, Graphs, and Mathematical Tables. (M. Abramowitz
and I. A. Stegun, eds.). New York: Dover, 1972.
See Also
coshint | cosint | eulergamma | int | sin | sinhint | ssinint
7-1378
smithForm
smithForm
Smith form of matrix
Syntax
S = smithForm(A)
[U,V,S] = smithForm(A)
___ = smithForm(A,var)
Description
S = smithForm(A) returns the Smith normal form on page 7-1383 of a square invertible matrix A.
The elements of A must be integers or polynomials in a variable determined by symvar(A,1). The
Smith form S is a diagonal matrix.
[U,V,S] = smithForm(A) returns the Smith normal form of A and unimodular transformation
matrices U and V, such that S = U*A*V.
___ = smithForm(A,var) assumes that the elements of A are univariate polynomials in the
specified variable var. If A contains other variables, smithForm treats those variables as symbolic
parameters.
You can use the input argument var in any of the previous syntaxes.
If A does not contain var, then smithForm(A) and smithForm(A,var) return different results.
Examples
Smith Form for Matrix of Integers
A = sym(invhilb(5))
S = smithForm(A)
A =
[ 25, -300, 1050, -1400, 630]
[ -300, 4800, -18900, 26880, -12600]
[ 1050, -18900, 79380, -117600, 56700]
[ -1400, 26880, -117600, 179200, -88200]
[ 630, -12600, 56700, -88200, 44100]
S =
[ 5, 0, 0, 0, 0]
[ 0, 60, 0, 0, 0]
[ 0, 0, 420, 0, 0]
[ 0, 0, 0, 840, 0]
[ 0, 0, 0, 0, 2520]
7-1379
7 Functions
Create a 2-by-2 matrix, the elements of which are polynomials in the variable x.
syms x
A = [x^2 + 3, (2*x - 1)^2; (x + 2)^2, 3*x^2 + 5]
A =
[ x^2 + 3, (2*x - 1)^2]
[ (x + 2)^2, 3*x^2 + 5]
S = smithForm(A)
S =
[ 1, 0]
[ 0, x^4 + 12*x^3 - 13*x^2 - 12*x - 11]
syms x y
A = [2/x + y, x^2 - y^2; 3*sin(x) + y, x]
A =
[ y + 2/x, x^2 - y^2]
[ y + 3*sin(x), x]
Find the Smith form of this matrix. If you do not specify the polynomial variable, smithForm uses
symvar(A,1) and thus determines that the polynomial variable is x. Because 3*sin(x) + y is not
a polynomial in x, smithForm throws an error.
S = smithForm(A)
Find the Smith form of A specifying that all elements of A are polynomials in the variable y.
S = smithForm(A,y)
S =
[ 1, 0]
[ 0, 3*y^2*sin(x) - 3*x^2*sin(x) + y^3 + y*(- x^2 + x) + 2]
Find the Smith form and transformation matrices for an inverse Hilbert matrix.
A = sym(invhilb(3));
[U,V,S] = smithForm(A)
U =
[ 1, 1, 1]
[ -4, -1, 0]
[ 10, 5, 3]
7-1380
smithForm
V =
[ 1, -2, 0]
[ 0, 1, 5]
[ 0, 1, 4]
S =
[ 3, 0, 0]
[ 0, 12, 0]
[ 0, 0, 60]
isAlways(S == U*A*V)
ans =
3×3 logical array
1 1 1
1 1 1
1 1 1
Find the Smith form and transformation matrices for a matrix of polynomials.
syms x y
A = [2*(x - y), 3*(x^2 - y^2);
4*(x^3 - y^3), 5*(x^4 - y^4)];
[U,V,S] = smithForm(A,x)
U =
[ 0, 1]
[ 1, - x/(10*y^3) - 3/(5*y^2)]
V =
[ -x/(4*y^3), - (5*x*y^2)/2 - (5*x^2*y)/2 - (5*x^3)/2 - (5*y^3)/2]
[ 1/(5*y^3), 2*x^2 + 2*x*y + 2*y^2]
S =
[ x - y, 0]
[ 0, x^4 + 6*x^3*y - 6*x*y^3 - y^4]
isAlways(S == U*A*V)
ans =
2×2 logical array
1 1
1 1
If a matrix does not contain a particular variable, and you call smithForm specifying that variable as
the second argument, then the result differs from what you get without specifying that variable. For
example, create a matrix that does not contain any variables.
A =
9 -36 30
7-1381
7 Functions
Call smithForm specifying variable x as the second argument. In this case, smithForm assumes that
the elements of A are univariate polynomials in x.
syms x
smithForm(A,x)
ans =
1 0 0
0 1 0
0 0 1
Call smithForm without specifying variables. In this case, smithForm treats A as a matrix of
integers.
smithForm(A)
ans =
3 0 0
0 12 0
0 0 60
Input Arguments
A — Input matrix
square invertible symbolic matrix
Input matrix, specified as a square invertible symbolic matrix, the elements of which are integers or
univariate polynomials. If the elements of A contain more than one variable, use the var argument to
specify a polynomial variable, and treat all other variables as symbolic parameters. If A is
multivariate, and you do not specify var, then smithForm uses symvar(A,1) to determine a
polynomial variable.
Output Arguments
S — Smith normal form of input matrix
symbolic diagonal matrix
Smith normal form of input matrix, returned as a symbolic diagonal matrix. The first diagonal
element divides the second, the second divides the third, and so on.
U — Transformation matrix
unimodular symbolic matrix
Transformation matrix, returned as a unimodular symbolic matrix. If elements of A are integers, then
elements of U are also integers, and det(U) = 1 or det(U) = -1. If elements of A are polynomials,
then elements of U are univariate polynomials, and det(U) is a constant.
7-1382
smithForm
V — Transformation matrix
unimodular symbolic matrix
Transformation matrix, returned as a unimodular symbolic matrix. If elements of A are integers, then
elements of V are also integers, and det(V) = 1 or det(V) = -1. If elements of A are polynomials,
then elements of V are univariate polynomials, and det(V) is a constant.
More About
Smith Normal Form
Smith normal form of a an n-by-n matrix A is an n-by-n diagonal matrix S, such that Si, i divides
Si + 1, i + 1 for all i < n.
Version History
Introduced in R2015b
See Also
hermiteForm | jordan
7-1383
7 Functions
solve
Equations and systems solver
Syntax
S = solve(eqn,var)
S = solve(eqn,var,Name,Value)
Y = solve(eqns,vars)
Y = solve(eqns,vars,Name,Value)
[y1,...,yN] = solve(eqns,vars)
[y1,...,yN] = solve(eqns,vars,Name,Value)
[y1,...,yN,parameters,conditions] = solve(eqns,vars,'ReturnConditions',true)
Description
S = solve(eqn,var) solves the equation eqn for the variable var. If you do not specify var, the
symvar function determines the variable to solve for. For example, solve(x + 1 == 2, x) solves
the equation x + 1 = 2 for x.
Y = solve(eqns,vars) solves the system of equations eqns for the variables vars and returns a
structure that contains the solutions. If you do not specify vars, solve uses symvar to find the
variables to solve for. In this case, the number of variables that symvar finds is equal to the number
of equations eqns.
[y1,...,yN] = solve(eqns,vars) solves the system of equations eqns for the variables vars.
The solutions are assigned to the variables y1,...,yN. If you do not specify the variables, solve
uses symvar to find the variables to solve for. In this case, the number of variables that symvar finds
is equal to the number of output arguments N.
[y1,...,yN,parameters,conditions] = solve(eqns,vars,'ReturnConditions',true)
returns the additional arguments parameters and conditions that specify the parameters in the
solution and the conditions on the solution.
Examples
7-1384
solve
Solve the quadratic equation without specifying a variable to solve for. solve chooses x to return the
solution.
syms a b c x
eqn = a*x^2 + b*x + c == 0
eqn = a x2 + b x + c = 0
S = solve(eqn)
S =
2
b+ b −4ac
−
2a
2
b− b −4ac
−
2a
Specify the variable to solve for and solve the quadratic equation for a.
Sa = solve(eqn,a)
Sa =
c+bx
−
x2
S =
5
5 5 2 5− 5 i
−σ1 − −
4 4
5 5 2 5− 5 i
−σ1 − +
4 4
5 5 2 5+5 i
σ1 − −
4 4
5 5 2 5+5 i
σ1 − +
4 4
where
5 5
σ1 =
4
Return only real solutions by setting 'Real' option to true. The only real solutions of this equation
is 5.
S = solve(eqn,x,'Real',true)
7-1385
7 Functions
S = 5
When solve cannot symbolically solve an equation, it tries to find a numeric solution using
vpasolve. The vpasolve function returns the first solution found.
Try solving the following equation. solve returns a numeric solution because it cannot find a
symbolic solution.
syms x
eqn = sin(x) == x^2 - 1;
S = solve(eqn,x)
Warning: Unable to solve symbolically. Returning a numeric solution using <a href="matlab:web(ful
S = −0.63673265080528201088799090383828
Plot the left and the right sides of the equation. Observe that the equation also has a positive solution.
Find the other solution by directly calling the numeric solver vpasolve and specifying the interval.
V = vpasolve(eqn,x,[0 2])
7-1386
solve
V = 1.4096240040025962492355939705895
When solving for multiple variables, it can be more convenient to store the outputs in a structure
array than in separate variables. The solve function returns a structure when you specify a single
output argument and multiple outputs exist.
ans =
1
3
S.v
ans =
2
−
3
Using a structure array allows you to conveniently substitute solutions into other expressions.
Use the subs function to substitute the solutions S into other expressions.
expr1 = u^2;
e1 = subs(expr1,S)
e1 =
1
9
expr2 = 3*v + u;
e2 = subs(expr2,S)
e2 =
5
−
3
S =
7-1387
7 Functions
Solve Inequalities
The solve function can solve inequalities and return solutions that satisfy the inequalities. Solve the
following inequalities.
x>0
y>0
x2 + y2 + xy < 1
Set 'ReturnConditions' to true to return any parameters in the solution and conditions on the
solution.
syms x y
eqn1 = x > 0;
eqn2 = y > 0;
eqn3 = x^2 + y^2 + x*y < 1;
eqns = [eqn1 eqn2 eqn3];
S = solve(eqns,[x y],'ReturnConditions',true);
S.x
ans =
u − 3 v2 v
−
2 2
S.y
ans = v
S.parameters
ans = u v
S.conditions
The parameters u and v do not exist in MATLAB® workspace and must be accessed using
S.parameters.
Check if the values u = 7/2 and v = 1/2 satisfy the condition using subs and isAlways.
ans = logical
1
7-1388
solve
isAlways returns logical 1 (true) indicating that these values satisfy the condition. Substitute these
parameter values into S.x and S.y to find a solution for x and y.
xSol =
11 1
−
4 4
ySol =
1
2
2u2 + v2 = 0
u−v=1
When solving for more than one variable, the order in which you specify the variables defines the
order in which the solver returns the solutions. Assign the solutions to variables solv and solu by
specifying the variables explicitly. The solver returns an array of solutions for each variable.
syms u v
eqns = [2*u^2 + v^2 == 0, u - v == 1];
vars = [v u];
[solv, solu] = solve(eqns,vars)
solv =
2 2 i
− −
3 3
2 2 i
− +
3 3
solu =
1 2 i
−
3 3
1 2 i
+
3 3
solutions =
2 2 i 1 2 i
− − −
3 3 3 3
2 2 i 1 2 i
− + +
3 3 3 3
7-1389
7 Functions
Return the complete solution of an equation with parameters and conditions of the solution by
specifying 'ReturnConditions' as true.
Solve the equation sin(x) = 0. Provide two additional output variables for output arguments
parameters and conditions.
syms x
eqn = sin(x) == 0;
[solx,parameters,conditions] = solve(eqn,x,'ReturnConditions',true)
solx = π k
parameters = k
conditions = k ∈ ℤ
The solution πk contains the parameter k, where k must be an integer. The variable k does not exist in
the MATLAB® workspace and must be accessed using parameters.
Restrict the solution to 0 < x < 2π. Find a valid value of k for this restriction. Assume the condition,
conditions, and use solve to find k. Substitute the value of k found into the solution for x.
assume(conditions)
restriction = [solx > 0, solx < 2*pi];
solk = solve(restriction,parameters)
solk = 1
valx = subs(solx,parameters,solk)
valx = π
Alternatively, determine the solution for x by choosing a value of k. Check if the value chosen satisfies
the condition on k using isAlways.
condk4 = subs(conditions,parameters,4);
isAlways(condk4)
ans = logical
1
isAlways returns logical 1(true), meaning that 4 is a valid value for k. Substitute k with 4 to obtain
a solution for x. Use vpa to obtain a numeric approximation.
valx = subs(solx,parameters,4)
valx = 4 π
vpa(valx)
ans = 12.566370614359172953850573533118
7-1390
solve
By default, solve does not apply simplifications that are not valid for all values of x. In this case, the
solver does not assume that x is a positive real number, so it does not apply the logarithmic identity
log(3x) = log(3) + log(x). As a result, solve cannot solve the equation symbolically.
syms x
eqn = exp(log(x)*log(3*x)) == 4;
S = solve(eqn,x)
Warning: Unable to solve symbolically. Returning a numeric solution using <a href="matlab:web(ful
S = −14.009379055223370038369334703094 − 2.9255310052111119036668717988769 i
Set 'IgnoreAnalyticConstraints' to true to apply simplification rules that might allow solve
to find a solution. For details, see “Algorithms” on page 7-1397.
S = solve(eqn,x,'IgnoreAnalyticConstraints',true)
S =
2
log 256 + log 3
3 e− 2
3
2
log 256 + log 3
3 e 2
3
solve applies simplifications that allow the solver to find a solution. The mathematical rules applied
when performing simplifications are not always valid in general. In this example, the solver applies
logarithmic identities with the assumption that x is a positive real number. Therefore, the solutions
found in this mode should be verified.
The sym and syms functions let you set assumptions for symbolic variables.
syms x positive
When you solve an equation for a variable under assumptions, the solver only returns solutions
consistent with the assumptions. Solve this equation for x.
S = 1
Allow solutions that do not satisfy the assumptions by setting 'IgnoreProperties' to true.
S = solve(eqn,x,'IgnoreProperties',true)
7-1391
7 Functions
S =
−6
1
For further computations, clear the assumption that you set on the variable x by recreating it using
syms.
syms x
When you solve a polynomial equation, the solver might use root to return the solutions. Solve a
third-degree polynomial.
syms x a
eqn = x^3 + x^2 + a == 0;
solve(eqn, x)
ans =
root z3 + z2 + a, z, 1
root z3 + z2 + a, z, 2
root z3 + z2 + a, z, 3
Try to get an explicit solution for such equations by calling the solver with 'MaxDegree'. The option
specifies the maximum degree of polynomials for which the solver tries to return explicit solutions.
The default value is 2. Increasing this value, you can get explicit solutions for higher order
polynomials.
Solve the same equations for explicit solutions by increasing the value of 'MaxDegree' to 3.
S = solve(eqn, x, 'MaxDegree', 3)
S =
1 1
+ σ1 −
9 σ1 3
1
σ1 1 3 9 σ − σ1 i
1 1
− − − −
18 σ1 2 3 2
1
σ1 1 3 9 σ − σ1 i
1 1
− − − +
18 σ1 2 3 2
where
1/3
a 1 2 1 a 1
σ1 = + − − −
2 27 729 2 27
7-1392
solve
Instead of returning an infinite set of periodic solutions, the solver picks three solutions that it
considers to be the most practical.
syms x
eqn = sin(x) + cos(2*x) == 1;
S = solve(eqn,x)
S =
0
π
6
5π
6
S1 = 0
Input Arguments
eqn — Equation to solve
symbolic expression | symbolic equation
Equation to solve, specified as a symbolic expression or symbolic equation. The relation operator ==
defines symbolic equations. If eqn is a symbolic expression (without the right side), the solver
assumes that the right side is 0, and solves the equation eqn == 0.
Variable for which you solve an equation, specified as a symbolic variable. By default, solve uses the
variable determined by symvar.
Variables for which you solve an equation or system of equations, specified as a symbolic vector or
symbolic matrix. By default, solve uses the variables determined by symvar.
The order in which you specify these variables defines the order in which the solver returns the
solutions.
7-1393
7 Functions
Flag for returning only real solutions, specified as the comma-separated pair consisting of 'Real'
and one of these values.
Flag for returning parameters in solution and conditions under which the solution is true, specified as
the comma-separated pair consisting of 'ReturnConditions' and one of these values.
false Do not return parameterized solutions and the conditions under which the
solution holds. The solve function replaces parameters with appropriate
values.
true Return the parameters in the solution and the conditions under which the
solution holds. For a call with a single output variable, solve returns a
structure with the fields parameters and conditions. For multiple output
variables, solve assigns the parameters and conditions to the last two
output variables. This behavior means that the number of output variables
must be equal to the number of variables to solve for plus two.
Simplification rules applied to expressions and equations, specified as the comma-separated pair
consisting of 'IgnoreAnalyticConstraints' and one of these values.
Flag for returning solutions inconsistent with the properties of variables, specified as the comma-
separated pair consisting of 'IgnoreProperties' and one of these values.
7-1394
solve
MaxDegree — Maximum degree of polynomial equations for which solver uses explicit
formulas
2 (default) | positive integer smaller than 5
Maximum degree of polynomial equations for which solver uses explicit formulas, specified as a
positive integer smaller than 5. The solver does not use explicit formulas that involve radicals when
solving polynomial equations of a degree larger than the specified value.
Flag for returning one solution, specified as the comma-separated pair consisting of
'PrincipalValue' and one of these values.
Output Arguments
S — Solutions of equation
symbolic array
Solutions of an equation, returned as a symbolic array. The size of a symbolic array corresponds to
the number of the solutions.
Solutions of a system of equations, returned as a structure. The number of fields in the structure
correspond to the number of independent variables in a system. If 'ReturnConditions' is set to
true, the solve function returns two additional fields that contain the parameters in the solution,
and the conditions under which the solution is true.
Solutions of a system of equations, returned as symbolic variables. The number of output variables or
symbolic arrays must be equal to the number of independent variables in a system. If you explicitly
specify independent variables vars, then the solver uses the same order to return the solutions. If
you do not specify vars, the toolbox sorts independent variables alphabetically, and then assigns the
solutions for these variables to the output variables.
7-1395
7 Functions
Parameters in a solution, returned as a vector of generated parameters. This output argument is only
returned if ReturnConditions is true. If a single output argument is provided, parameters is
returned as a field of a structure. If multiple output arguments are provided, parameters is returned
as the second-to-last output argument. The generated parameters do not appear in the MATLAB
workspace. They must be accessed using parameters.
Example: [solx, params, conditions] = solve(sin(x) == 0, 'ReturnConditions',
true) returns the parameter k in the argument params.
Conditions under which solutions are valid, returned as a vector of symbolic expressions. This output
argument is only returned if ReturnConditions is true. If a single output argument is provided,
conditions is returned as a field of a structure. If multiple output arguments are provided,
conditions is returned as the last output argument.
Example: [solx, params, conditions] = solve(sin(x) == 0, 'ReturnConditions',
true) returns the condition in(k, 'integer') in conditions. The solution in solx is valid only
under this condition.
Tips
• If solve cannot find a solution and ReturnConditions is false, the solve function internally
calls the numeric solver vpasolve that tries to find a numeric solution. For polynomial equations
and systems without symbolic parameters, the numeric solver returns all solutions. For
nonpolynomial equations and systems without symbolic parameters, the numeric solver returns
only one solution (if a solution exists).
• If solve cannot find a solution and ReturnConditions is true, solve returns an empty
solution with a warning. If no solutions exist, solve returns an empty solution without a warning.
• If the solution contains parameters and ReturnConditions is true, solve returns the
parameters in the solution and the conditions under which the solutions are true. If
ReturnConditions is false, the solve function either chooses values of the parameters and
returns the corresponding results, or returns parameterized solutions without choosing particular
values. In the latter case, solve also issues a warning indicating the values of parameters in the
returned solutions.
• If a parameter does not appear in any condition, it means the parameter can take any complex
value.
• The output of solve can contain parameters from the input equations in addition to parameters
introduced by solve.
• Parameters introduced by solve do not appear in the MATLAB workspace. They must be
accessed using the output argument that contains them. Alternatively, to use the parameters in
the MATLAB workspace use syms to initialize the parameter. For example, if the parameter is k,
use syms k.
• The variable names parameters and conditions are not allowed as inputs to solve.
• To solve differential equations, use the dsolve function.
• When solving a system of equations, always assign the result to output arguments. Output
arguments let you access the values of the solutions of a system.
7-1396
solve
• MaxDegree only accepts positive integers smaller than 5 because, in general, there are no explicit
expressions for the roots of polynomials of degrees higher than 4.
• The output variables y1,...,yN do not specify the variables for which solve solves equations or
systems. If y1,...,yN are the variables that appear in eqns, then there is no guarantee that
solve(eqns) will assign the solutions to y1,...,yN using the correct order. Thus, when you run
[b,a] = solve(eqns), you might get the solutions for a assigned to b and vice versa.
To ensure the order of the returned solutions, specify the variables vars. For example, the call
[b,a] = solve(eqns,b,a) assigns the solutions for a to a and the solutions for b to b.
Algorithms
When you use IgnoreAnalyticConstraints, the solver applies some of these rules to the
expressions on both sides of an equation.
• log(a) + log(b) = log(a·b) for all values of a and b. In particular, the following equality is valid for
all values of a, b, and c:
(a·b)c = ac·bc.
• log(ab) = b·log(a) for all values of a and b. In particular, the following equality is valid for all values
of a, b, and c:
(ab)c = ab·c.
• If f and g are standard mathematical functions and f(g(x)) = x for all small positive numbers,
f(g(x)) = x is assumed to be valid for all complex values x. In particular:
• log(ex) = x
• asin(sin(x)) = x, acos(cos(x)) = x, atan(tan(x)) = x
• asinh(sinh(x)) = x, acosh(cosh(x)) = x, atanh(tanh(x)) = x
• Wk(x·ex) = x for all branch indices k of the Lambert W function.
• The solver can multiply both sides of an equation by any expression except 0.
• The solutions of polynomial equations must be complete.
Version History
Introduced before R2006a
Support for character vector or string inputs has been removed. Instead, use syms to declare
variables and replace inputs such as solve('2*x == 1','x') with solve(2*x == 1,x).
See Also
Functions
dsolve | isolate | linsolve | root | subs | symvar | vpasolve
7-1397
7 Functions
Topics
“Solve Algebraic Equations” on page 3-3
“Solve System of Algebraic Equations” on page 3-7
“Solve System of Linear Equations” on page 3-30
“Solve Algebraic Equation Using Live Editor Task” on page 3-36
“Select Numeric or Symbolic Solver” on page 3-33
“Troubleshoot Equation Solutions from solve Function” on page 3-17
External Websites
Beam Bending and Deflection (MathWorks Teaching Resources)
7-1398
Solve Symbolic Equation
Description
The Solve Symbolic Equation task enables you to interactively find analytic solutions of symbolic
equations. The task automatically generates MATLAB code for your live script. For more information
about Live Editor tasks, see “Add Interactive Tasks to a Live Script”.
• Find analytic solutions of symbolic equations, which include a single equation and a system of
algebraic equations.
• Specify the solver options to find solutions.
• Generate the code used to solve equations.
7-1399
7 Functions
• On the Live Editor tab, select Task > Solve Symbolic Equation.
• In a code block in your script, type a relevant keyword, such as solve, symbolic, or equation.
Select Solve Symbolic Equation from the suggested command completions.
Parameters
Return real solutions — Return only real solutions
off (default) | on
Select this check box to return solutions for which every subexpression of the equation represents a
real number. This option assumes all parameters of the equation represent real numbers.
Select this check box to return a single solution (principal value). If an equation or a system of
equations does not have any solution, the solver returns an empty symbolic object.
Select this check box to return the more general solution and the analytic constraints under which
the solution holds. This option returns a structure with the fields parameters and conditions that
contain the parameters in the solution and the conditions under which they hold, respectively.
Select this check box to express the root function in terms of square roots in the solutions. The
results can be lengthy or less accurate for floating-point approximations.
Select this check box to apply purely algebraic simplifications, such as log(a) + log(b) =
log(a*b) with the assumption that a and b are real positive numbers. Setting Ignore analytic
constraints to on can give you simpler solutions, which could lead to results not generally valid. In
other words, this option applies mathematical identities that are convenient for most engineering
workflow, but do not always hold for all values of variables. In some cases, it also enables the Solve
Symbolic Equation task to solve equations and systems that cannot be solved otherwise. For details,
see “Algorithms” on page 7-1401.
Select this check box to ignore assumptions on the variables to solve for. This option may include
solutions that are inconsistent with assumptions on the variables to solve for.
7-1400
Solve Symbolic Equation
Algorithms
When you use Ignore analytic constraints, the solver applies some of these rules to the
expressions on both sides of an equation.
• log(a) + log(b) = log(a·b) for all values of a and b. In particular, the following equality is valid for
all values of a, b, and c :
(a·b)c = ac·bc.
• log(ab) = b·log(a) for all values of a and b. In particular, the following equality is valid for all values
of a, b, and c :
(ab)c = ab·c.
• If f and g are standard mathematical functions and f(g(x)) = x for all small positive numbers,
f(g(x)) = x is assumed to be valid for all complex values x. In particular:
• log(ex) = x
• asin(sin(x)) = x, acos(cos(x)) = x, atan(tan(x)) = x
• asinh(sinh(x)) = x, acosh(cosh(x)) = x, atanh(tanh(x)) = x
• Wk(x·ex) = x for all branch indices k of the Lambert W function.
• The solver can multiply both sides of an equation by any expression except 0.
• The solutions of polynomial equations must be complete.
Version History
Introduced in R2020a
See Also
Functions
solve
Topics
“Add Interactive Tasks to a Live Script”
“Solve Algebraic Equation Using Live Editor Task” on page 3-36
“Solve Algebraic Equations” on page 3-3
7-1401
7 Functions
sort
Sort elements of symbolic arrays
Syntax
Y = sort(X)
Y = sort(X,dim)
Y = sort( ___ ,direction)
[Y,I] = sort( ___ )
Description
Y = sort(X) sorts the elements of X in ascending lexicographical order.
Y = sort(X,dim) sorts the elements of X along the dimension dim. For example, if X is a two-
dimensional matrix, then sort(X,1) sorts the elements of each column of X, and sort(X,2) sorts
the elements of each row.
Y = sort( ___ ,direction) returns sorted elements of X in the order specified by direction
using any of the previous syntaxes. 'ascend' indicates ascending order (the default), and
'descend' indicates descending order.
[Y,I] = sort( ___ ) also returns a collection of index vectors for any of the previous syntaxes. I is
the same size as X and describes the arrangement of the elements of X into Y along the sorted
dimension. For example, if X is an m-by-n matrix and you sort the elements of each column (dim = 1),
then each column of I is an index vector of the sorted column of X, such that
for j = 1:n
Y(:,j) = X(I(:,j),j);
end
Examples
Create a symbolic row vector and sort its elements in ascending order.
syms a b c d e
sort([7 e 1 c 5 d a b])
ans = 1 5 7 a b c d e
7-1402
sort
When sorting the elements of a matrix, sort can work along the columns or rows of that matrix.
X = magic(3)*sym('a')
X =
8a a 6a
3a 5a 7a
4a 9a 2a
Sort the matrix X. By default, the sort command sorts the elements of each column.
Y = sort(X)
Y =
3a a 2a
4a 5a 6a
8a 9a 7a
To sort the elements of each row, set the value of the dim option to 2.
Y = sort(X,2)
Y =
a 6a 8a
3a 5a 7a
2a 4a 9a
X = magic(3)*sym('a')
X =
8a a 6a
3a 5a 7a
4a 9a 2a
Y = sort(X,2,'descend')
Y =
8a 6a a
7a 5a 3a
9a 4a 2a
7-1403
7 Functions
To find the indices that each element of a matrix Y had in the original matrix X, call sort with two
output arguments.
X =
8a a 6a
3a 5a 7a
4a 9a 2a
Sort each column of X and return the indices of the sorted elements in I. Each column of I contains
the presorted positions of entries in Y.
[Y,I] = sort(X)
Y =
3a a 2a
4a 5a 6a
8a 9a 7a
I = 3×3
2 1 3
3 2 1
1 3 2
Sort a symbolic vector X that contains real and complex numbers. When X contains symbolic real and
complex numbers, sort(X) returns the sorted real numbers, followed by the sorted complex
numbers based on their real parts.
X = sort(sym([2 -1/2 3+4i 5i 4+3i]))
X =
1
− 2 5 i 3+4 i 4+3 i
2
Create a 2-by-2-by-2 symbolic array that contains symbolic numbers, variables, and functions.
syms x y f(x);
X(:,:,1) = [y 1; 1/3 x];
X(:,:,2) = [x -2; 1/4 f(x)];
X
X(:,:,1) =
7-1404
sort
y 1
1
x
3
X(:,:,2) =
x −2
1
f x
4
Y = sort(X,3)
Y(:,:,1) =
x −2
1
x
4
Y(:,:,2) =
y 1
1
f x
3
Y = sort(X(:))
Y =
−2
1
4
1
3
1
x
x
y
f x
Input Arguments
X — Input array
symbolic vector | symbolic matrix | symbolic multidimensional array
Input array, specified as a symbolic vector, matrix, or multidimensional array. sort uses the following
rules:
• If X contains only symbolic real numbers that are rational, then sort(X) sorts the elements
numerically.
• If X contains only symbolic complex numbers with rational real and imaginary parts, then
sort(X) sorts the elements first by their real parts, then by their imaginary parts to break ties.
• If X contains only symbolic variables, then sort(X) sorts the elements alphabetically.
7-1405
7 Functions
• If X contains a mix of symbolic numbers (with rational parts) and variables, then sort(X) returns
the following sequence: sorted real numbers, sorted complex numbers, and sorted variables.
• If X contains symbolic irrational numbers, expressions, and functions, comparing and sorting the
elements can be computationally complex. Therefore, sort uses internal sorting rules to optimize
its performance.
Dimension to operate along, specified as a positive integer scalar. If no value is specified, then the
default is the first array dimension whose size does not equal 1.
Output Arguments
Y — Sorted array
symbolic vector | symbolic matrix | symbolic multidimensional array
Sorted array, returned as a symbolic vector, matrix, or multidimensional array. Y is the same size and
type as X.
I — Sort index
symbolic vector | symbolic matrix | symbolic multidimensional array
7-1406
sort
Sort index, returned as a symbolic vector, matrix, or multidimensional array. I is the same size as X.
The index vectors are oriented along the same dimension that sort operates on. For example, if X is
a 2-by-3 matrix, then [Y,I] = sort(X,2) sorts the elements in each row of X. The output I is a
collection of 1-by-3 row index vectors that contains the presorted positions of each row of Y.
Tips
• Calling sort for arrays of numbers that are not symbolic objects invokes the MATLAB sort
function.
• The sort function sorts symbolic complex numbers differently from MATLAB floating-point
complex numbers. For symbolic input X that contains complex numbers, sort(X) sorts the
complex numbers first by their real parts, then by their imaginary parts to break ties. For floating-
point input X, by default, sort(X) sorts complex numbers by their magnitude, followed by their
phase angles in the interval (−π, π] to break ties.
Version History
Introduced before R2006a
7-1407
7 Functions
sqrtm
Matrix square root
Syntax
X = sqrtm(A)
[X,resnorm] = sqrtm(A)
Description
X = sqrtm(A) returns a matrix X, such that X2 = A and the eigenvalues of X are the square roots of
the eigenvalues of A.
Examples
Compute Square Root of Matrix
Compute the square root of this matrix. Because these numbers are not symbolic objects, you get
floating-point results.
X =
1.3333 -0.6667 0.0000
-0.3333 1.6667 -0.0000
-0.0572 0.5286 1.4142
Now, convert this matrix to a symbolic object, and compute its square root again:
X =
[ 4/3, -2/3, 0]
[ -1/3, 5/3, 0]
[ (2*2^(1/2))/3 - 1, 1 - 2^(1/2)/3, 2^(1/2)]
isAlways(X^2 == A)
ans =
3×3 logical array
1 1 1
1 1 1
1 1 1
7-1408
sqrtm
Use the syntax with two output arguments to return the square root of a matrix and the residual:
X =
[ 0, 0]
[ 0, 1.2909944487358056283930884665941]
resnorm =
2.9387358770557187699218413430556e-40
Input Arguments
A — Input
symbolic matrix
Output Arguments
X — Matrix square root
symbolic matrix
resnorm — Residual
symbolic expression
Tips
• Calling sqrtm for a matrix that is not a symbolic object invokes the MATLAB sqrtm function.
Version History
Introduced in R2013a
See Also
cond | eig | expm | funm | jordan | logm | norm
7-1409
7 Functions
ssinint
Shifted sine integral function
Syntax
ssinint(X)
Description
ssinint(X) returns the shifted sine integral function on page 7-1412 ssinint(X) = sinint(X)
— pi/2.
Examples
Shifted Sine Integral Function for Numeric and Symbolic Arguments
Compute the shifted sine integral function for these numbers. Because these numbers are not
symbolic objects, ssinint returns floating-point results.
A = ssinint([- pi, 0, pi/2, pi, 1])
A =
-3.4227 -1.5708 -0.2000 0.2811 -0.6247
Compute the shifted sine integral function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, ssinint returns unresolved symbolic calls.
symA = ssinint(sym([- pi, 0, pi/2, pi, 1]))
symA =
[ - pi - ssinint(pi), -pi/2, ssinint(pi/2), ssinint(pi), ssinint(1)]
ans =
[ -3.4227333787773627895923750617977,...
-1.5707963267948966192313216916398,...
-0.20003415864040813916164340325818,...
0.28114072518756955112973167851824,...
-0.62471325642771360428996837781657]
Plot the shifted sine integral function on the interval from -4*pi to 4*pi.
syms x
fplot(ssinint(x),[-4*pi 4*pi])
grid on
7-1410
ssinint
Many functions, such as diff, int, and taylor, can handle expressions containing ssinint.
Find the first and second derivatives of the shifted sine integral function:
syms x
diff(ssinint(x), x)
diff(ssinint(x), x, x)
ans =
sin(x)/x
ans =
cos(x)/x - sin(x)/x^2
int(ssinint(x), x)
ans =
cos(x) + x*ssinint(x)
taylor(ssinint(x), x)
7-1411
7 Functions
ans =
x^5/600 - x^3/18 + x - pi/2
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
More About
Sine Integral Function
Version History
Introduced in R2014a
References
[1] Gautschi, W. and W. F. Cahill. “Exponential Integral and Related Functions.” Handbook of
Mathematical Functions with Formulas, Graphs, and Mathematical Tables. (M. Abramowitz
and I. A. Stegun, eds.). New York: Dover, 1972.
See Also
coshint | cosint | eulergamma | int | sin | sinhint | sinhint | sinint
7-1412
str2symunit
str2symunit
Convert character vector or string to unit
Syntax
str2symunit(unitStr)
str2symunit(unitStr,toolbox)
Description
str2symunit(unitStr) converts the character vector or string unitStr to symbolic units.
Examples
Convert Character Vector to Unit
unit =
1*([km]/[h])
speed =
50*([km]/[h])
Convert units from other toolboxes to symbolic units by specifying the toolbox name as the second
argument to str2symunit. The allowed names are 'Aerospace', 'SimBiology', 'Simscape', or
'Simulink'.
unit =
1*([km]/([h]*[s]))
unit =
1*([molecule]/[s])
7-1413
7 Functions
unit = str2symunit('gee/km','Simscape')
unit =
1*([g_n]/[km])
unit = str2symunit('rad/second','Simulink')
unit =
1*([rad]/[s])
Input Arguments
unitStr — Input units
character vector | string
Version History
Introduced in R2017a
See Also
checkUnits | findUnits | isUnit | newUnit | separateUnits | symunit | symunit2str |
unitConversionFactor
Topics
“Units of Measurement Tutorial” on page 2-47
“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)
7-1414
str2sym
str2sym
Evaluate string representing symbolic expression
Syntax
str2sym(symstr)
Description
str2sym(symstr) evaluates symstr where symstr is a string representing a symbolic expression.
Enter symbolic expressions as strings only when reading expressions from text files or when
specifying numbers exactly. Otherwise, do not use strings for symbolic input.
Examples
str2sym('sin(pi)')
ans =
0
str2sym assumes the = operator represents an equation, not an assignment. Also, str2sym does not
add the variables contained in the string to the workspace.
Show this behavior by evaluating 'x^2 = 4'. The str2sym function returns the equation x^2 == 4
but x does not appear in the workspace.
eqn =
x^2 == 4
Find the variable in eqn by using symvar. The variable var now refers to x.
var = symvar(eqn)
var =
x
Assign values from eqn by solving eqn for var and assigning the result.
varVal = solve(eqn,var)
varVal =
-2
2
7-1415
7 Functions
str2sym does not substitute values from the workspace for variables in the input. Therefore,
str2sym has reproducible output. Instead, substitute workspace values by using subs on the output
of str2sym.
Set y to 2. Then, evaluate 'y^2' with and without subs to show how subs substitutes y with its
value.
y = 2;
withoutSubs = str2sym('y^2')
withoutSubs =
y^2
withSubs = subs(str2sym('y^2'))
withSubs =
4
When symbolic expressions are stored as strings in a file, evaluate the strings by reading the file and
using str2sym.
a = 2.431
y = a*exp(t)
diff(z(t),t) = b*y*z
filename = 'mySym.txt';
filetext = fileread(filename);
filetext = splitlines(filetext);
str2sym(filetext)
ans =
a == 2.431
y == a*exp(t)
diff(z(t), t) == b*y*z
The output of str2sym is independent of workspace values, which means the output is reproducible.
Show this reproducibility by assigning a value to b and re-evaluating the stored expressions.
b = 5;
str2sym(filetext)
ans =
a == 2.431
y == a*exp(t)
diff(z(t), t) == b*y*z
7-1416
str2sym
To use workspace values or a value from input equations, use subs (solve the equation first using
solve), as described in “Evaluate String as Symbolic Expression” on page 7-1415 and “Substitute
Workspace Values into String Input” on page 7-1415.
str2sym executes functions in input when the functions are on the path. Otherwise, str2sym
returns the symbolic object as expected. This behavior means that the output is reproducible.
Show this behavior by reading a differential equation and initial condition from a file. Solve the
equation for the condition. Because str2sym does not evaluate y(t) in the equation, the output is
reproducible.
filename = 'mySym.txt';
filetext = fileread(filename);
filetext = splitlines(filetext);
eqn = str2sym(filetext(1))
eqn =
diff(y(t), t) == -y(t)
cond = str2sym(filetext(2))
cond =
y(0) == 2
ySol = dsolve(eqn,cond)
ySol =
2*exp(-t)
Because the MATLAB parser automatically converts all numbers to double precision, maintain
original precision by entering large numbers and high-precision numbers as strings. Instead of
str2sym, enter integers using sym and floating-point numbers using vpa because sym and vpa are
faster.
Show the error between entering a ratio of large integers directly versus the exact string
representation.
num = sym(12230984290/38490293482)
num =
5724399718238385/18014398509481984
numExact = sym('12230984290/38490293482')
numExact =
6115492145/19245146741
error =
-7827162395/346689742765832461975814144
7-1417
7 Functions
Show the error between entering a high-precision number directly versus the exact string
representation.
num = vpa(8.023098429038490293482)
num =
8.0230984290384910195825796108693
numExact = vpa('8.023098429038490293482')
numExact =
8.023098429038490293482
error =
0.00000000000000072610057961086928844451883343504
For details, see “Numeric to Symbolic Conversion” on page 2-29. For full workflows, see “Find Almost
Integers with High-Precision Arithmetic” on page 2-41 and “Prime Factorizations” on page 3-323.
Starting in R2019b, you can represent hexadecimal and binary values using character vectors.
Hexadecimal values start with a 0x or 0X prefix, while binary values start with a 0b or 0B prefix. You
can then convert the hexadecimal and binary values to symbolic decimal numbers using str2sym.
For more information, see “Hexadecimal and Binary Values”.
Create a character vector that represents a hexadecimal value. Convert the value to symbolic decimal
number.
H = '0x2A'
D = str2sym(H)
D =
42
Create a character vector that represents a binary value. Convert the value to symbolic decimal
number.
B = '0b101010'
D = str2sym(B)
D =
42
Input Arguments
symstr — String representing symbolic expression
character vector | string | cell array of character vectors
String representing a symbolic expression, specified as a character vector, string, or cell array of
character vectors.
7-1418
str2sym
Tips
• str2sym assumes the = operator represents an equation, not an assignment.
• str2sym does not create variables contained in the input.
• str2sym('inf') returns infinity (Inf).
• str2sym('i') returns the imaginary number 1i.
Version History
Introduced in R2017b
See Also
sym | syms | subs | vpa
Topics
“Numeric to Symbolic Conversion” on page 2-29
“Create Symbolic Numbers, Variables, and Expressions” on page 1-3
7-1419
7 Functions
subexpr
Rewrite symbolic expression in terms of common subexpressions
Syntax
[r,sigma] = subexpr(expr)
[r,var] = subexpr(expr,'var')
[r,var] = subexpr(expr,var)
Description
[r,sigma] = subexpr(expr) rewrites the symbolic expression expr in terms of a common
subexpression, substituting this common subexpression with the symbolic variable sigma. The input
expression expr cannot contain the variable sigma.
This syntax overwrites the value of the variable var with the common subexpression found in expr.
To avoid overwriting the value of var, use another variable name as the second output argument. For
example, use [r,var1] = subexpr(expr,var).
Examples
Solve the following equation. The solutions are very long expressions. To display the solutions,
remove the semicolon at the end of the solve command.
syms a b c d x
solutions = solve(a*x^3 + b*x^2 + c*x + d == 0, x, 'MaxDegree', 3);
These long expressions have common subexpressions. To shorten the expressions, abbreviate the
common subexpression by using subexpr. If you do not specify the variable to use for abbreviations
as the second input argument of subexpr, then subexpr uses the variable sigma.
r =
7-1420
subexpr
b σ2
σ− −
3a σ
σ2 b σ
− − − σ1
2σ 3a 2
σ2 b σ
− − + σ1
2σ 3a 2
where
σ2
3 σ+ σ i
σ1 =
2
2
c b
σ2 = −
3 a 9 a2
sigma =
2 1/3
3 2 3 3
d b bc c b b d bc
+ − + − − − +
2 a 27 a3 6 a2 3 a 9 a2 27 a3 2 a 6 a2
syms a b c x
solutions = solve(a*x^2 + b*x + c == 0, x)
solutions =
2
b+ b −4ac
−
2a
2
b− b −4ac
−
2a
Use syms to create the symbolic variable s, and then replace common subexpressions in the result
with this variable.
syms s
[abbrSolutions,s] = subexpr(solutions,s)
abbrSolutions =
b+s
−
2a
b−s
−
2a
2
s = b −4ac
[abbrSolutions,s] = subexpr(solutions,'s')
abbrSolutions =
7-1421
7 Functions
b+s
−
2a
b−s
−
2a
2
s = b −4ac
Both syntaxes overwrite the value of the variable s with the common subexpression. Therefore, you
cannot, for example, substitute s with some value.
subs(abbrSolutions,s,0)
ans =
b+s
−
2a
b−s
−
2a
To avoid overwriting the value of the variable s, use another variable name for the second output
argument.
syms s
[abbrSolutions,t] = subexpr(solutions,'s')
abbrSolutions =
b+s
−
2a
b−s
−
2a
2
t = b −4ac
subs(abbrSolutions,s,0)
ans =
b
−
2a
b
−
2a
Input Arguments
expr — Long expression containing common subexpressions
symbolic expression | symbolic function
Variable to use for substituting common subexpressions, specified as a character vector or symbolic
variable.
subexpr throws an error if the input expression expr already contains var.
7-1422
subexpr
Output Arguments
r — Expression with common subexpressions replaced by abbreviations
symbolic expression | symbolic function
Version History
Introduced before R2006a
See Also
children | simplify | subs
Topics
“Abbreviate Common Terms in Long Expressions” on page 3-147
7-1423
7 Functions
subs
Symbolic substitution
Syntax
snew = subs(s,old,new)
snew = subs(s,new)
snew = subs(s)
sMnew = subs(sM,oldM,newM)
sMnew = subs(sM,newM)
sMnew = subs(sM)
Description
Substitute Symbolic Scalar Variables and Functions
snew = subs(s,old,new) returns a copy of s, replacing all occurrences of old with new, and then
evaluates s. Here, s is an expression of symbolic scalar variables or a symbolic function, and old
specifies the symbolic scalar variables or symbolic function to be substituted.
• If old and new are both vectors or cell arrays of the same size, subs replaces each element of
old with the corresponding element of new.
• If old is a scalar, and new is a vector or matrix, then subs(s,old,new) replaces all instances of
old in s with new, performing all operations element-wise. All constant terms in s are replaced
with the constant multiplied by a vector or matrix of all ones.
snew = subs(s,new) returns a copy of s, replacing all occurrences of the default symbolic scalar
variable in s with new, and then evaluates s. The default variable is defined by symvar(s,1).
snew = subs(s) returns a copy of s, replacing symbolic scalar variables in s with their assigned
values in the MATLAB workspace, and then evaluates s. Variables with no assigned values remain as
variables.
Substitute Symbolic Matrix Variables and Functions
sMnew = subs(sM,oldM,newM) returns a copy of sM, replacing all occurrences of oldM with newM,
and then evaluates sM. Here, sM is an expression, equation, or condition involving symbolic matrix
variables and matrix functions, and oldM specifies the symbolic matrix variables and matrix functions
to be substituted. The substitution values newM must have the same size as oldM.
sMnew = subs(sM,newM) returns a copy of sM, replacing all occurrences of the default symbolic
matrix variable in sM with newM, and then evaluates sM.
sMnew = subs(sM) returns a copy of sM, replacing symbolic matrix variables in sM with their
assigned values in the MATLAB workspace, and then evaluates sM. Variables with no assigned values
remain as variables.
Examples
7-1424
subs
Single Substitution
ans = b + 4
ans = 5 b
Substitute the default symbolic scalar variable in this expression with a. If you do not specify the
scalar variable or expression to replace, subs uses symvar to find the default variable. For x + y,
the default variable is x.
syms x y a
symvar(x + y,1)
ans = x
ans = a + y
When you assign a new value to a symbolic scalar variable, expressions containing the variable are
not automatically evaluated. Instead, evaluate expressions by using subs.
y = x2
ans = 4
7-1425
7 Functions
Multiple Substitutions
Make multiple substitutions by specifying the old and new values as vectors.
syms a b
subs(cos(a) + sin(b), [a,b], [sym('alpha'),2])
Replace the symbolic scalar variable a in this expression with the 3-by-3 magic square matrix. Note
that the constant 1 expands to the 3-by-3 matrix with all its elements equal to 1.
syms a t
subs(exp(a*t) + 1, a, -magic(3))
ans =
e−8 t + 1 e−t + 1 e−6 t + 1
e−3 t + 1 e−5 t + 1 e−7 t + 1
e−4 t + 1 e−9 t + 1 e−2 t + 1
You can also replace an element of a vector, matrix, or array with a nonscalar value. For example,
create these 2-by-2 matrices.
A = sym('A',[2,2])
A =
A1, 1 A1, 2
A2, 1 A2, 2
B = sym('B',[2,2])
B =
B1, 1 B1, 2
B2, 1 B2, 2
Replace the first element of the matrix A with the matrix B. While making this substitution, subs
expands the 2-by-2 matrix A into this 4-by-4 matrix.
A44 =
7-1426
subs
subs does not let you replace a nonscalar or matrix with a scalar that shrinks the matrix size.
syms x y z
S = struct('f1',x*y,'f2',y + z,'f3',y^2)
Replace the symbolic scalar variables x and y with these 2-by-2 matrices. When you make multiple
substitutions involving vectors or matrices, use cell arrays to specify the old and new values.
syms x y
subs(x*y, {x,y}, {[0 1; -1 0], [1 -1; -2 1]})
ans =
0 −1
2 0
Note that because x and y are scalars, these substitutions are element-wise.
[0 1; -1 0].*[1 -1; -2 1]
ans = 2×2
0 -1
2 0
7-1427
7 Functions
Substitutions in Equations
Eliminate scalar variables from an equation by using the variable's value from another equation. In
the second equation, isolate the variable on the left side using isolate, and then substitute the right
side with the variable in the first equation.
syms x y
eqn1 = sin(x)+y == x^2 + y^2;
eqn2 = y*x == cos(x);
eqn2 = isolate(eqn2,y)
eqn2 =
cos x
y=
x
Eliminate y from eqn1 by substituting the left side of eqn2 with the right side of eqn2.
eqn1 = subs(eqn1,lhs(eqn2),rhs(eqn2))
eqn1 =
2
cos x cos x
sin x + = + x2
x x2
Substitutions in Functions
syms x y a
syms f(x,y)
f(x,y) = x + y;
f = subs(f,x,a)
f(x, y) = a + y
subs replaces the values in the symbolic function formula, but it does not replace input arguments of
the function.
formula(f)
ans = a + y
argnames(f)
ans = x y
syms x y
f(x,y) = x + y;
7-1428
subs
f(a,y) = subs(f,x,a);
f
f(a, y) = a + y
syms x y
eqs = [x^2 + y^2 == 1, x == y];
S = solve(eqs,[x y]);
S.x
ans =
2
−
2
2
2
S.y
ans =
2
−
2
2
2
Verify the solutions by substituting the solutions into the original system.
isAlways(subs(eqs,S))
1 1
1 1
Define the product of two 2-by-2 matrices. Declare the matrices as symbolic matrix variables with the
symmatrix data type.
syms X Y [2 2] matrix
sM = X*Y
sM = X Y
Replace the matrix variables X and Y with 2-by-2 symbolic matrices. When you make multiple
substitutions involving vectors or matrices, use cell arrays to specify the matrix variables to be
substituted and their new values. The new values must have the same size as the matrix variables to
be substituted.
7-1429
7 Functions
S =
Σ1
where
−2 2 2
Σ1 =
2 − 2
Convert the expression S to the sym data type to show the result of the substituted matrix
multiplication.
Ssym = symmatrix2sym(S)
Ssym =
−2 2 2
2 − 2
A = sym([1 4 2; 4 1 2; 2 2 3])
A =
142
412
223
Compute the coefficients of the characteristic polynomial of A using the charpoly function.
c = charpoly(A)
c = 1 −5 −17 21
Next, define X as a 3-by-3 symbolic matrix variable. Use the coefficients c to create the polynomial
p(X) = c1 X 3 + c2 X 2 + c3 X + c4I3, where X is an indeterminate that represents a 3-by-3 matrix.
syms X [3 3] matrix
p = c(1)*X^3 + c(2)*X^2 + c(3)*X + c(4)*X^0
p = 21 I3 − 17 X − 5 X 2 + X 3
Substitute X in the polynomial p(X) with A using the subs function. According to the Cayley-Hamilton
theorem, this substitution results in a 3-by-3 zero matrix because the coefficients c are the
characteristic polynomial of A. Use symmatrix2sym to convert the substituted expression to a matrix
of symbolic numbers.
Y = subs(p,A)
Y =
7-1430
subs
where
14 2
Σ1 = 4 1 2
22 3
Z = symmatrix2sym(Y)
Z =
000
000
000
Define the function f A = A2 − 2A + I2, where A is a 2-by-2 matrix and I2 is a 2-by-2 identity matrix.
Substitute the variable A with another expression and evaluate the new function.
Create a 2-by-2 symbolic matrix variable A. Create a symbolic matrix function f A , keeping the
existing definition of A in the workspace. Assign the polynomial expression of f A .
syms A 2 matrix
syms f(A) 2 matrix keepargs
f(A) = A*A - 2*A + eye(2)
f(A) = I2 − 2 A + A2
Next, create new symbolic matrix variables B and C. Create a new symbolic matrix function g B, C ,
keeping the existing definitions of B and C in the workspace.
syms B C 2 matrix
syms g(B,C) 2 matrix keepargs
Substitute the variable A in f A with B + C. Assign the substituted result to the new function
g B, C .
g(B,C) = subs(f,A,B+C)
2
g(B, C) = B + C + I2 − 2 B − 2 C
0 1 1 −1
Evaluate g B, C for the matrix values B = and C = using subs.
−1 0 −2 1
S =
7-1431
7 Functions
2
−2 Σ1 − 2 Σ2 + Σ1 + Σ2 + I2
where
0 1
Σ1 =
−1 0
1 −1
Σ2 =
−2 1
Convert the expression S from the symmatrix data type to the sym data type to show the result of
the substituted polynomial.
Ssym = symmatrix2sym(S)
Ssym =
00
00
∂ ∂
Define the equation f X, A = 2 A, where A is a 3-by-3 matrix and X is a 3-by-1 matrix.
∂ XT ∂ X
Substitute f X, A with another symbolic expression and A with symbolic values. Check if the
equation is true for these values.
Create two symbolic matrix variables A and X . Create a symbolic matrix function f X, A , keeping the
existing definitions of A and X in the workspace. Create the equation.
syms A [3 3] matrix
syms X [3 1] matrix
syms f(X,A) [1 1] matrix keepargs
eq = diff(diff(f,X),X.') == 2*A
eq(X, A) =
∂ ∂
f X, A = 2 A
∂ XT ∂ X
Substitute f X, A with XT AX and evaluate the second-order differential function in the equation for
this expression.
eq = subs(eq,f,X.'*A*X)
eq(X, A) = AT + A = 2 A
eq = subs(eq,A,hilb(3))
eq(X, A) =
7-1432
subs
Σ1 + Σ1T = 2 Σ1
where
1 1
1
2 3
1 1 1
Σ1 =
2 3 4
1 1 1
3 4 5
Check if the equation is true for these values by using isAlways. Because isAlways accepts only a
symbolic input of type symfun or sym, convert eq from type symfunmatrix to type symfun before
using isAlways.
tf = isAlways(symfunmatrix2symfun(eq))
1 1 1
1 1 1
1 1 1
Define the expression XY 2 − Y X2, where X and Y are 3-by-3 matrices. Create the matrices as
symbolic matrix variables.
syms X Y [3 3] matrix
C = X*Y^2 - Y*X^2
C = X Y 2 − Y X2
Evaluate the expression C with the assigned values of X and Y by using subs.
Cnew = subs(C)
Cnew =
−Σ1 Σ22 + Σ2 Σ12
where
3 2 2
Σ1 = −1 2 1
1 2 −1
−1 2 π
1
Σ2 = 0 2
2
2 1 0
7-1433
7 Functions
Convert the result from the symmatrix data type to the double data type.
Cnum = double(Cnew)
Cnum = 3×3
Input Arguments
s — Symbolic input
symbolic scalar variable | symbolic expression | symbolic equation | symbolic function | symbolic
array | symbolic matrix | structure
Symbolic input, specified as a symbolic scalar variable, expression, equation, function, array, matrix,
or a structure.
Data Types: sym | symfun | struct
Scalar variable to substitute, specified as a symbolic scalar variable, function, expression, array, or a
cell array.
Data Types: sym | symfun | cell
New value to substitute with, specified as a number, symbolic number, scalar variable, function,
expression, array, structure, or a cell array.
Data Types: sym | symfun | single | double | int8 | int16 | int32 | int64 | uint8 | uint16 |
uint32 | uint64 | struct | cell
sM — Symbolic input
symbolic matrix variable | symbolic matrix function | symbolic expression | symbolic equation |
symbolic condition
Symbolic input, specified as a symbolic matrix variable, matrix function, expression, equation, or
condition.
Data Types: symmatrix | symfunmatrix
Matrix variable or function to substitute, specified as a symbolic matrix variable, matrix function,
expression, or a cell array.
Data Types: symmatrix | symfunmatrix | cell
7-1434
subs
New value to substitute with, specified as a number, symbolic number, matrix variable, matrix
function, expression, array, or a cell array. newM must have the same size as oldM or the default
symbolic matrix variable in sM.
Data Types: sym | symmatrix | symfunmatrix | single | double | int8 | int16 | int32 | int64 |
uint8 | uint16 | uint32 | uint64 | struct | cell
Tips
• subs(s,__) does not modify s. To modify s, use s = subs(s,__).
• If s is a univariate polynomial and new is a numeric matrix, use polyvalm(sym2poly(s),new)
to evaluate s as a matrix. All constant terms are replaced with the constant multiplied by an
identity matrix.
• Starting in R2022b, symbolic substitution involving derivatives or the diff function follows the
input order of the symbolic objects to be substituted. For example, this code performs symbolic
substitution involving the diff function.
syms m k x(t)
syms x_t x_t_ddot
eqSHM = m*diff(x(t),t,2) == -k*x(t);
eqSHMnew = subs(eqSHM,[x(t) diff(x(t),t,2)],[x_t x_t_ddot])
eqSHMnew =
m*x_t_ddot == -k*x_t
eqSHMnew =
0 == -k*x_t
The difference in output is due to subs now first substituting x(t) with x_t, resulting in
diff(x_t,t,2), which is equal to 0. To obtain the substitution result as in previous releases,
specify the diff(x(t),t,2) term first so that it is substituted before the x(t) term.
eqSHMnew =
m*x_t_ddot == -k*x_t
Version History
Introduced before R2006a
You can use the syntax subs(sM) to substitute the symbolic matrix variables and matrix functions in
sM with their assigned values in the MATLAB workspace and then evaluate sM. Variables with no
7-1435
7 Functions
assigned values remain as variables. For an example, see “Evaluate Expression Involving Symbolic
Matrix Variables” on page 7-1433.
R2022b: Substitute symbolic matrix variables and matrix functions in symbolic equations
or conditions
The subs function accepts a symbolic equation or condition of type symmatrix or symfunmatrix as
the first input argument. For an example, see “Substitute Symbolic Matrix Variables and Matrix
Functions in Equation” on page 7-1432.
The subs function accepts a symbolic matrix function of type symfunmatrix as the first input
argument. For an example, see “Substitute Variables in Symbolic Matrix Function” on page 7-1431.
The subs function accepts a symbolic expression of type symmatrix as the first input argument. For
examples, see “Substitute Symbolic Matrix Variables with Arrays” on page 7-1429 and “Characteristic
Polynomial of Matrix” on page 7-1430.
See Also
Functions
double | lhs | rhs | simplify | subexpr | vpa
Topics
“Substitutions in Symbolic Expressions” on page 1-33
“Substitute Variables in Symbolic Expressions” on page 3-140
“Substitute Elements in Symbolic Matrices” on page 3-142
“Substitute Scalars with Matrices” on page 3-144
“Evaluate Symbolic Expressions Using subs” on page 3-146
7-1436
svd
svd
Singular value decomposition of symbolic matrix
Syntax
sigma = svd(A)
[U,S,V] = svd(A)
[U,S,V] = svd(A,0)
[U,S,V] = svd(A,'econ')
Description
sigma = svd(A) returns a vector sigma containing the singular values of a symbolic matrix A.
[U,S,V] = svd(A) returns numeric unitary matrices U and V with the columns containing the
singular vectors, and a diagonal matrix S containing the singular values. The matrices satisfy the
condition A = U*S*V', where V' is the Hermitian transpose (the complex conjugate transpose) of V.
The singular vector computation uses variable-precision arithmetic. svd does not compute symbolic
singular vectors. Therefore, the input matrix A must be convertible to floating-point numbers. For
example, it can be a matrix of symbolic numbers.
[ ___ ] = svd( ___ ,outputForm) returns the singular values in the form specified by
outputForm using any of the input or output arguments in previous syntaxes. Specify outputForm
as 'vector' to return the singular values as a column vector or as 'matrix' to return the singular
values as a diagonal matrix.
Examples
Compute the singular values of the symbolic 5-by-5 magic square. The result is a column vector.
A = sym(magic(5));
sigma = svd(A)
sigma =
7-1437
7 Functions
65
5 1345 + 65
65 5+5
65 5 − 5
5 65 − 1345
Alternatively, specify the 'matrix' option to return the singular values as a diagonal matrix.
S = svd(A,'matrix')
S =
65 0 0 0 0
0 5 1345 + 65 0 0 0
0 0 65 5+5 0 0
0 0 0 65 5 − 5 0
0 0 0 0 5 65 − 1345
syms t real
A = [0 1; -1 0];
E = expm(t*A)
E =
cos t sin t
−sin t cos t
sigma = svd(E)
sigma =
2 2
cos t + sin t
2 2
cos t + sin t
sigma = simplify(sigma)
sigma =
1
1
For further computations, remove the assumption that t is real by recreating it using syms.
syms t
7-1438
svd
Create a 5-by-5 symbolic matrix from the magic square of order 6. Compute the singular values of the
matrix using svd.
M = magic(6);
A = sym(M(1:5,1:5));
sigma = svd(A)
sigma =
root σ1, z, 5
root σ1, z, 4
root σ1, z, 3
root σ1, z, 2
root σ1, z, 1
where
The svd function cannot find the exact singular values in terms of symbolic numbers. Instead, it
returns them in terms of the root function.
sigmaVpa = vpa(sigma)
sigmaVpa =
91.903382299388875598380645217105
41.667523645705677947038130902387
33.389311761352625550607303429805
7.6138651481371046117950798870896
1.3299296132187199146053915272808
Compute the singular values and singular vectors of the 5-by-5 magic square.
old = digits(10);
A = sym(magic(5))
A =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
[U,S,V] = svd(A)
U =
7-1439
7 Functions
S =
65.0 0 0 0 0
0 22.54708869 0 0 0
0 0 21.68742536 0 0
0 0 0 13.403566 0
0 0 0 0 11.90078954
V =
0.4472135955 0.4045164361 0.2465648962 0.6627260007 0.3692782866
0.4472135955 0.005566159714 0.6627260007 −0.2465648962 −0.5476942741
0.4472135955 −0.8201651916 1.767621593e−27 9.706484055e−28 0.3568319751
0.4472135955 0.005566159714 −0.6627260007 0.2465648962 −0.5476942741
0.4472135955 0.4045164361 −0.2465648962 −0.6627260007 0.3692782866
digits(old)
Compute the product of U, S, and the Hermitian transpose of V with the 10-digit accuracy. The result
is the original matrix A with all its elements converted to floating-point numbers.
vpa(U*S*V',10)
ans =
17.0 24.0 1.0 8.0 15.0
23.0 5.0 7.0 14.0 16.0
4.0 6.0 13.0 20.0 22.0
10.0 12.0 19.0 21.0 3.0
11.0 18.0 25.0 2.0 9.0
Calculate the full and economy-size decompositions of a rectangular matrix within 8-digit accuracy.
old = digits(8);
A = sym([1 2; 3 4; 5 6; 7 8])
A =
1 2
3 4
5 6
7 8
[U,S,V] = svd(A)
U =
7-1440
svd
S =
14.269095 0
0 0.62682823
0 0
0 0
V =
0.64142303 0.7671874
0.7671874 −0.64142303
[U,S,V] = svd(A,'econ')
U =
0.15248323 −0.82264747
0.34991837 −0.42137529
0.54735351 −0.020103103
0.74478865 0.38116908
S =
14.269095 0
0 0.62682823
V =
0.64142303 0.7671874
0.7671874 −0.64142303
digits(old)
Since A is a 4-by-2 matrix, svd(A,'econ') returns fewer columns in U and fewer rows in S
compared to a full decomposition. Extra rows of zeros in S are excluded, along with the
corresponding columns in U that would multiply with those zeros in the expression A = U*S*V'.
Input Arguments
A — Input matrix
symbolic matrix
Input matrix, specified as a symbolic matrix. For syntaxes with one output argument, the elements of
A can be symbolic numbers, variables, expressions, or functions. For syntaxes with three output
arguments, the elements of A must be convertible to floating-point numbers.
Since R2021b
Output format of singular values, specified as 'vector' or 'matrix'. This option allows you to
specify whether the singular values are returned as a column vector or diagonal matrix. The default
behavior varies according to the number of outputs specified:
7-1441
7 Functions
• If you specify one output, such as sigma = svd(A), then the singular values are returned as a
column vector by default.
• If you specify three outputs, such as [U,S,V] = svd(A), then the singular values are returned
as a diagonal matrix, S, by default.
Output Arguments
sigma — Singular values
symbolic vector | vector of symbolic numbers
Singular values of a matrix, returned as a vector. If sigma is a vector of numbers, then its elements
are sorted in descending order.
U — Singular vectors
matrix of symbolic numbers
Singular vectors, returned as a unitary matrix. Each column of this matrix is a singular vector.
S — Singular values
matrix of symbolic numbers
Singular values, returned as a diagonal matrix. Diagonal elements of this matrix appear in
descending order.
V — Singular vectors
matrix of symbolic numbers
Singular vectors, returned as a unitary matrix. Each column of this matrix is a singular vector.
Tips
• The second arguments 0 and 'econ' only affect the shape of the returned matrices. These
arguments do not affect the performance of the computations.
• Calling svd for numeric matrices that are not symbolic objects invokes the MATLAB svd function.
• Matrix computations involving many symbolic variables can be slow. To increase the
computational speed, reduce the number of symbolic variables by substituting the given values for
some variables.
Version History
Introduced before R2006a
The svd function accepts the outputForm input argument. You can specify outputForm as
'vector' or 'matrix' to return singular values as a column vector or a diagonal matrix.
R2021b: sigma = svd(A) returns singular values in terms of the root function
Behavior changed in R2021b
7-1442
svd
If sigma = svd(A) cannot find the exact singular values in terms of symbolic numbers, it now
returns the exact singular values in terms of the root function instead. In previous releases, sigma
= svd(A) returns the singular values as floating-point numbers.
For example, compute the singular values of a 5-by-5 symbolic matrix. The svd function returns the
exact singular values in terms of the root function. This is consistent with the results returned by the
solve or root function when solving for the roots of a polynomial.
M = magic(6);
A = sym(M(1:5,1:5));
sigma = svd(A)
sigma =
root(z^5 - 11357*z^4 + 26691022*z^3 - 17903673324*z^2 + 979310921328*z - 1676258447616, z, 5)^(1/2)
root(z^5 - 11357*z^4 + 26691022*z^3 - 17903673324*z^2 + 979310921328*z - 1676258447616, z, 4)^(1/2)
root(z^5 - 11357*z^4 + 26691022*z^3 - 17903673324*z^2 + 979310921328*z - 1676258447616, z, 3)^(1/2)
root(z^5 - 11357*z^4 + 26691022*z^3 - 17903673324*z^2 + 979310921328*z - 1676258447616, z, 2)^(1/2)
root(z^5 - 11357*z^4 + 26691022*z^3 - 17903673324*z^2 + 979310921328*z - 1676258447616, z, 1)^(1/2)
sigmaVpa = vpa(sigma)
sigmaVpa =
91.903382299388875598380645217105
41.667523645705677947038130902387
33.389311761352625550607303429805
7.6138651481371046117950798870896
1.3299296132187199146053915272808
See Also
chol | digits | eig | lu | inv | qr | svd | vpa
Topics
“Singular Value Decomposition” on page 3-280
7-1443
7 Functions
sym
Create symbolic variables, expressions, functions, matrices
Syntax
x = sym('x')
A = sym('a',[n1 ... nM])
A = sym('a',n)
sym(num)
sym(num,flag)
sym(strnum)
symexpr = sym(h)
symexpr = sym(M)
Description
x = sym('x') creates symbolic scalar variable x.
A = sym('a',[n1 ... nM]) creates an n1-by-...-by-nM symbolic array filled with automatically
generated elements. For example, A = sym('a',[1 3]) creates the row vector A = [a1 a2 a3].
The generated elements a1, a2, and a3 do not appear in the MATLAB workspace. For
multidimensional arrays, these elements have the prefix a followed by the element’s index using _ as
a delimiter, such as a1_3_2.
A = sym('a',n) creates an n-by-n symbolic matrix filled with automatically generated elements.
sym( ___ ,set) creates a symbolic variable or array and sets the assumption that the variable or all
array elements belong to set. Here, set can be 'real', 'positive', 'integer', or 'rational'.
You also can combine multiple assumptions by specifying a string array or cell array of character
vectors. For example, assume a positive rational value by specifying set as ["positive"
"rational"] or {'positive','rational'}.
sym( ___ ,'clear') clears assumptions set on a symbolic variable or array. You can specify
'clear' after the input arguments in any of the previous syntaxes, except combining 'clear' and
set. You cannot set and clear an assumption in the same function call to sym.
sym(num) converts a number or numeric matrix specified by num to a symbolic number or symbolic
matrix.
sym(num,flag) uses the technique specified by flag to convert floating-point numbers to symbolic
numbers.
sym(strnum) converts the character vector or string specified by strnum to an accurate symbolic
number without approximation.
7-1444
sym
symexpr = sym(h) creates a symbolic expression or matrix symexpr from an anonymous MATLAB
function associated with the function handle h.
Examples
x = sym('x')
x = x
y = sym('y')
y = y
Create a 1-by-4 symbolic vector a with automatically generated elements a1, ..., a4.
a = sym('a',[1 4])
a =
You can specify the format for the element names by using a format character vector as the first
argument. sym replaces %d in the format character vector with the index of the element to generate
the element names.
b = sym('x_%d',[1 4])
b =
These syntaxes do not create symbolic variables a1, ..., a4, x_1, ..., x_4 in the MATLAB® workspace.
Access elements of a and b using standard indexing methods.
a(1)
b(2:3)
ans =
a1
7-1445
7 Functions
ans =
[x_2, x_3]
Create a 3-by-4 symbolic matrix with automatically generated elements. The sym function generates
matrix elements of the form Ai_j. Here, sym generates the elements A1_1, ..., A3_4.
A = sym('A',[3 4])
A =
Create a 4-by-4 matrix with the element names x_1_1, ..., x_4_4 by using a format character vector
as the first argument. sym replaces %d in the format character vector with the index of the element to
generate the element names.
B = sym('x_%d_%d',4)
B =
These syntaxes do not create symbolic variables A1_1, ..., A3_4, x_1_1, ..., x_4_4 in the MATLAB®
workspace. To access an element of a matrix, use parentheses.
A(2,3)
B(4,2)
ans =
A2_3
ans =
x_4_2
7-1446
sym
Create a 2-by-2-by-2 symbolic array with automatically generated elements a1, 1, 1, …, a2, 2, 2.
A = sym('a',[2 2 2])
A(:,:,1) =
a1, 1, 1 a1, 2, 1
a2, 1, 1 a2, 2, 1
A(:,:,2) =
a1, 1, 2 a1, 2, 2
a2, 1, 2 a2, 2, 2
Convert numeric values to symbolic numbers or expressions. Use sym on subexpressions instead of
the entire expression for better accuracy. Using sym on entire expressions is inaccurate because
MATLAB® first converts the expression to a floating-point number, which loses accuracy. sym cannot
always recover this lost accuracy.
inaccurate1 = sym(1/1234567)
inaccurate1 =
7650239286923505
9444732965739290427392
accurate1 = 1/sym(1234567)
accurate1 =
1
1234567
inaccurate2 = sym(sqrt(1234567))
inaccurate2 =
4886716562018589
4398046511104
accurate2 = sqrt(sym(1234567))
accurate2 = 1234567
inaccurate3 = sym(exp(pi))
inaccurate3 =
6513525919879993
281474976710656
accurate3 = exp(sym(pi))
accurate3 = eπ
7-1447
7 Functions
When creating symbolic numbers with 15 or more digits, use quotation marks to accurately represent
the numbers.
inaccurateNum = sym(11111111111111111111)
inaccurateNum = 11111111111111110656
accurateNum = sym('11111111111111111111')
accurateNum = 11111111111111111111
When you use quotation marks to create symbolic complex numbers, specify the imaginary part of a
number as 1i, 2i, and so on.
sym('1234567 + 1i')
ans = 1234567 + i
Convert anonymous functions associated with MATLAB® handles to a symbolic expression and a
symbolic matrix.
h_matrix = @(x)(x*pascal(3));
sym_matrix = sym(h_matrix)
sym_matrix =
x x x
x 2x 3x
x 3x 6x
Create the symbolic variables x, y, z, and t while simultaneously setting assumptions that x is real, y
is positive, z is rational, and t is a positive integer.
x = sym('x','real');
y = sym('y','positive');
z = sym('z','rational');
t = sym('t',{'positive','integer'});
assumptions
ans = t ∈ ℤ x ∈ ℝ z ∈ ℚ 1 ≤ t 0 < y
7-1448
sym
assume([x y z t],'clear')
assumptions
ans =
Create a symbolic matrix and set assumptions on each element of that matrix.
A = sym('A%d%d',[2 2],'positive')
A =
A11 A12
A21 A22
Solve an equation involving the first element of A. MATLAB® assumes that this element is positive.
solve(A(1,1)^2-1, A(1,1))
ans = 1
assumptions(A)
Clear all previously set assumptions on elements of the symbolic matrix by using assume.
assume(A,'clear');
assumptions(A)
ans =
solve(A(1,1)^2-1, A(1,1))
ans =
−1
1
7-1449
7 Functions
Choose the conversion technique by specifying the optional second argument, which can be 'r', 'f',
'd', or 'e'. The default is 'r'. See the Input Arguments section for details about the conversion
techniques.
r = sym(pi)
r = π
f = sym(pi,'f')
f =
884279719003555
281474976710656
d = sym(pi,'d')
d = 3.1415926535897931159979634685442
e = sym(pi,'e')
e =
198 eps
π−
359
syms A [3 3] matrix
syms X [3 1] matrix
f = X.'*A*X;
M = diff(f,X,X.')
M = AT + A
Convert the result from a symbolic matrix variable to a matrix of symbolic scalar variables.
S = sym(M)
S =
2 A1, 1 A1, 2 + A2, 1 A1, 3 + A3, 1
A1, 2 + A2, 1 2 A2, 2 A2, 3 + A3, 2
A1, 3 + A3, 1 A2, 3 + A3, 2 2 A3, 3
Alternatively, you can use symmatrix2sym to convert a symbolic matrix variable to an array of
symbolic scalar variables.
S = symmatrix2sym(M)
7-1450
sym
S =
2 A1, 1 A1, 2 + A2, 1 A1, 3 + A3, 1
A1, 2 + A2, 1 2 A2, 2 A2, 3 + A3, 2
A1, 3 + A3, 1 A2, 3 + A3, 2 2 A3, 3
Input Arguments
Variable name, specified as a character vector or string. Argument x must be a valid variable name.
That is, x must begin with a letter and contain only alphanumeric characters and underscores. To
verify that the name is a valid variable name, use isvarname.
Example: 'x', "y123", 'z_1'
Prefix for automatically generated matrix elements, specified as a character vector or string.
Argument a must be a valid variable name. That is, a must begin with a letter and contain only
alphanumeric characters and underscores. To verify that the name is a valid variable name, use
isvarname.
If you specify the argument a and its vector, matrix, or array dimensions in the argument [n1 ...
nM], then a can include a format character vector such as 'a_%d_%d'. For examples, see “Create
Symbolic Vectors” on page 7-1445 and “Create Symbolic Matrices” on page 7-1446.
Example: 'a', "b", 'a_bc'
Vector, matrix, or array dimensions, specified as a vector of integers. As a shortcut, you can create a
square matrix by specifying only one integer. For example, A = sym('A',3) creates a square 3-by-3
matrix.
Example: [2 3]
Assumptions on the symbolic variable or matrix, specified as a character vector, string array, or cell
array of character vectors. The available assumptions are 'integer', 'rational', 'real', or
'positive'.
You can combine multiple assumptions by specifying a string array or cell array of character vectors.
For example, assume a positive rational value by specifying set as ["positive" "rational"] or
{'positive','rational'}.
Example: 'integer'
7-1451
7 Functions
'r' When sym uses the rational mode, it converts floating-point numbers obtained by
evaluating expressions of the form p/q, p*pi/q, sqrt(p), 2^q, and 10^q (for modest-
sized integers p and q) to the corresponding symbolic form. For example,
sym(1/10,'r') returns 1/10. This mode effectively compensates for the round-off error
involved in the original evaluation but might not represent the floating-point value
precisely. If sym cannot find a simple rational approximation, then it uses the same
technique as it would use with the flag 'f'.
'd' When sym uses the decimal mode, it takes the number of digits from the current setting
of digits. Conversions with fewer than 16 digits lose some accuracy, while more than
16 digits might not be warranted. For example, sym(4/3,'d') with 10-digit accuracy
returns 1.333333333, while with 20-digit accuracy it returns
1.3333333333333332593. The latter does not end in 3s, but it is an accurate decimal
representation of the floating-point number nearest to 4/3.
'e' When sym uses the estimate error mode, it supplements a result obtained in the rational
mode by a term involving the variable eps. This term estimates the difference between
the theoretical rational expression and its actual floating-point value. For example,
sym(3*pi/4,'e') returns (3*pi)/4 - (103*eps)/249.
'f' When sym uses the floating-point to rational mode, it returns the symbolic form for all
values in the form N*2^e or -N*2^e, where N >= 0 is a nonnegative integer and e is an
integer. The returned symbolic number is a precise rational number that is equal to the
floating-point value. For example, sym(1/10,'f') returns
3602879701896397/36028797018963968.
h — Anonymous function
MATLAB function handle
Anonymous function, specified as a MATLAB function handle. For more information, see “Anonymous
Functions”.
Example: h = @(x)sin(x)
7-1452
sym
Alternatively, you can use symmatrix2sym to convert a symbolic matrix variable to an array of
symbolic scalar variables.
Example: syms A 2 matrix; M = A^2 + eye(2)
Data Types: symmatrix
Output Arguments
x — Variable
symbolic scalar variable
Vector or matrix with automatically generated elements, returned as a symbolic vector or matrix of
symbolic scalar variables. The elements of this vector or matrix do not appear in the MATLAB
workspace.
Expression or matrix converted from an anonymous MATLAB function or a symbolic matrix variable,
returned as a symbolic expression or matrix of symbolic scalar variables.
Data Types: sym
Tips
• Statements like pi = sym(pi) and delta = sym('1/10') create symbolic numbers that avoid
the floating-point approximations inherent in the values of pi and 1/10. The pi created in this
way stores the symbolic number in a workspace variable named pi, which temporarily replaces
the built-in numeric function with the same name. Use clear pi to restore the floating-point
representation of pi.
• sym always treats i in character vector input as an identifier. To input the imaginary number i,
use 1i instead.
• clear x does not clear the symbolic object of its assumptions, such as real, positive, or any
assumptions set by assume, sym, or syms. To remove assumptions, use one of these options:
A = eye(3);
A(1,1) = sym(pi)
A =
3.1416 0 0
7-1453
7 Functions
0 1.0000 0
0 0 1.0000
You cannot replace elements of a numeric vector or matrix with a symbolic variable, expression, or
function because these elements cannot be converted to double-precision numbers. For example,
A(1,1) = sym('a') throws an error.
• When you use the syntax A = sym('a',[n1 ... nM]), the sym function assigns only the
symbolic array A to the MATLAB workspace. To also assign the automatically generated elements
of A, use the syms function instead. For example, syms a [1 3] creates the row vector a = [a1
a2 a3] and the symbolic variables a1, a2, and a3 in the MATLAB workspace.
Alternative Functionality
Alternative Approaches for Creating Symbolic Variables
To create several symbolic variables in one function call, use syms. Using syms also clears
assumptions from the named variables.
Version History
Introduced before R2006a
You can convert a symbolic matrix variable M of type symmatrix to an array of symbolic scalar
variables symexpr of type sym by using symexpr = sym(M). For an example, see “Convert Hessian
Matrix” on page 7-1450.
sym('pi') now creates a symbolic variable named pi instead of a symbolic number representing
the mathematical constant π. In previous releases, both sym('pi') and sym(pi) create symbolic
numbers representing the constant π.
For example, the command a = sym('pi') creates a symbolic variable named pi and assigns it to
the workspace variable a.
a = sym('pi')
class(a)
symType(a)
vpa(2*a)
a =
pi
ans =
'sym'
ans =
"variable"
ans =
2.0*pi
7-1454
sym
a = sym(pi)
class(a)
symType(a)
vpa(2*a)
a =
pi
ans =
'sym'
ans =
"constant"
ans =
6.283185307179586476925286766559
This behavior also applies to the mathematical constants catalan and eulergamma.
Support for character vectors that are not valid variable names and that do not define a number has
been removed. To create symbolic expressions, first create symbolic variables, and then use
operations on them. For example, use syms x; x + 1 instead of sym('x + 1'), exp(sym(pi))
instead of sym('exp(pi)'), and syms f(var1,...,varN) instead of f(var1,...,varN) =
sym('f(var1,...,varN)').
See Also
assume | double | reset | str2sym | symfun | syms | symvar
Topics
“Create Symbolic Numbers, Variables, and Expressions” on page 1-3
“Create Symbolic Functions” on page 1-9
“Create Symbolic Matrices” on page 1-11
“Choose syms or sym Function” on page 2-4
“Use Assumptions on Symbolic Variables” on page 1-41
“Add Subscripts, Superscripts, and Accents to Symbolic Variables in the Live Editor” on page 2-14
“Change Output Format of Symbolic and Variable-Precision Arithmetic” on page 2-8
7-1455
7 Functions
sym2cell
Convert symbolic array to cell array
Syntax
C = sym2cell(S)
Description
C = sym2cell(S) converts a symbolic array S to a cell array C. The resulting cell array has the
same size and dimensions as the input symbolic array.
Examples
syms x y
S = [x 2 3 4; y 6 7 8; 9 10 11 12]
S =
x 2 3 4
y 6 7 8
9 10 11 12
Convert this matrix to a cell array by using sym2cell. The size of the resulting cell array
corresponds to the size of the input matrix. Each cell contains an element of the symbolic matrix S.
C = sym2cell(S)
[C{1,1:4}]
ans = x 2 3 4
[C{1:3,1}]
ans = x y 9
7-1456
sym2cell
Input Arguments
S — Input symbolic array
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix | symbolic multidimensional array
Input symbolic array, specified as a symbolic vector, matrix, or multidimensional array. S also can be a
scalar, that is, a symbolic number, variable, expression, or function.
Output Arguments
C — Resulting cell array
cell array
Resulting cell array, returned as a cell array such that size(C) = size(S). Each element of the
input symbolic array S is enclosed in a separate cell.
Version History
Introduced in R2016a
See Also
cell2sym | cell2mat | mat2cell | num2cell
7-1457
7 Functions
sym2poly
Extract vector of all numeric coefficients, including zeros, from symbolic polynomial
Syntax
c = sym2poly(p)
Description
c = sym2poly(p) returns the numeric vector of coefficients c of the symbolic polynomial p. The
returned vector c includes all coefficients, including those equal 0.
Examples
Extract Numeric Coefficients of Polynomial
syms x
c = sym2poly(x^3 - 2*x - 5)
c =
1 0 -2 -5
Extract rational and integer coefficients of a symbolic polynomial into a vector. Because sym2poly
returns numeric double-precision results, it approximates exact rational coefficients with double-
precision numbers.
c = sym2poly(1/2*x^3 - 2/3*x - 5)
c =
0.5000 0 -0.6667 -5.0000
Input Arguments
p — Polynomial
symbolic expression
Output Arguments
c — Polynomial coefficients
numeric row vector
7-1458
sym2poly
Tips
• To extract symbolic coefficients of a polynomial, use coeffs. This function returns a symbolic
vector of coefficients and omits all zeros. For example, syms a b x; c = coeffs(a*x^3 -
5*b,x) returns c = [ -5*b, a].
Version History
Introduced before R2006a
See Also
coeffs | poly2sym
7-1459
7 Functions
symengine
(Not recommended) Return symbolic engine
Note is not recommended. Use equivalent Symbolic Math Toolbox™ functions that replace
MuPAD®functions instead. For more information, see “Compatibility Considerations”.
Syntax
s = symengine
Description
s = symengine returns the currently active symbolic engine.
Examples
s =
MuPAD symbolic engine
Now you can use the variable s in function calls that require symbolic engine:
syms x y
A = [x y; y x];
feval(symengine,'linalg::eigenvalues',A)
ans =
[x + y, x - y]
Version History
Introduced in R2008b
Symbolic Math Toolbox includes operations and functions for symbolic math expressions that parallel
MATLAB functionality for numeric values. Unlike MuPAD functionality, Symbolic Math Toolbox
functions enable you to work in familiar interfaces, such as the MATLAB Command Window or Live
Editor, which offer a smooth workflow and are optimized for usability.
Therefore, instead of passing a symbolic engine and MuPAD expressions to feval, evalin, and
read, use the equivalent Symbolic Math Toolbox functionality to work with symbolic math
expressions. For a list of available functions, see Symbolic Math Toolbox functions list.
7-1460
symengine
To convert a MuPAD notebook file to a MATLAB live script file, see convertMuPADNotebook.
If you cannot find the Symbolic Math Toolbox equivalent for MuPAD functionality, contact MathWorks
Technical Support.
Although the use of symengine is not recommended, there are no plans to remove it at this time.
7-1461
7 Functions
symfalse
Symbolic logical constant false
Syntax
symfalse
F = symfalse(n)
F = symfalse(sz)
T = symfalse(sz1,...,szN)
Description
symfalse is the symbolic logical constant for the false condition.
F = symfalse(sz) returns an array of symbolic logical symfalses where the size vector, sz,
defines size(T). For example, symfalse([2 3]) returns a 2-by-3 array of symbolic logical
symfalses.
Examples
syms x
eq = x^2 > 4
eq = 4 < x2
Simplify the condition represented by the symbolic inequality eq. The simplify function returns the
symbolic logical constant symfalse since the condition never holds for the assumption −2 < x < 2.
F = simplify(eq)
F = symfalse
class(F)
7-1462
symfalse
ans =
'sym'
You can also use isAlways to check if the inequality does not hold under the assumption being
made. In this example, isAlways returns logical 0 (false).
TF = isAlways(eq)
TF = logical
0
F = symfalse(3)
F =
symfalse symfalse symfalse
symfalse symfalse symfalse
symfalse symfalse symfalse
class(F)
ans =
'sym'
F = symfalse(3,2,2)
F(:,:,1) =
symfalse symfalse
symfalse symfalse
symfalse symfalse
F(:,:,2) =
symfalse symfalse
symfalse symfalse
symfalse symfalse
Alternatively, you can use a size vector to specify the size of the array.
F = symfalse([3,2,2])
F(:,:,1) =
symfalse symfalse
symfalse symfalse
symfalse symfalse
F(:,:,2) =
7-1463
7 Functions
symfalse symfalse
symfalse symfalse
symfalse symfalse
Create a truth table for the and operation applied to the two symbolic logical constants, symtrue and
symfalse.
A = [symtrue symfalse]
A = symtrue symfalse
B = [symtrue; symfalse]
B =
symtrue
symfalse
TF = and(A,B)
TF =
symtrue symfalse
symfalse symfalse
Combine symbolic logical constants with logical operators and, not, or, and xor (or their shortcuts).
TF = xor(symtrue,or(symfalse,symfalse))
TF = symtrue
TF = symtrue
T1 = logical
0
Convert the symbolic logical constant symfalse to numeric values in double precision and variable
precision.
T2 = double(symfalse)
7-1464
symfalse
T2 = 0
T3 = vpa(symfalse)
T3 = 0.0
whos
T1 1x1 1 logical
T2 1x1 8 double
T3 1x1 8 sym
Input Arguments
n — Size of square matrix
scalar
Size of square matrix, specified as an integer. n sets the output array size to n-by-n. For example,
symfalse(3) returns a 3-by-3 array of symbolic logical symfalses.
sz — Size vector
row vector of integers
Size vector, specified as a row vector of integers. For example, symfalse([2 3]) returns a 2-by-3
array of symbolic logical symfalses.
Size inputs, specified by a comma-separated list of integers. For example, symfalse(2,3) returns a
2-by-3 array of symbolic logical symfalses.
7-1465
7 Functions
Output Arguments
F — Symbolic logical constant for false condition
scalar | vector | matrix | N-D array
Symbolic logical constant for false condition, returned as a scalar, vector, matrix, or N-D array.
Data Types: sym
Tips
• The command sym(false) returns a symbolic number 0, and sym(symfalse) returns
symfalse.
• When you combine two arrays of symbolic logical constants with logical operations using and, or,
or xor function, the arrays must either be the same size or have sizes that are compatible. For
more information on the required input sizes for basic array operations, see “Compatible Array
Sizes for Basic Operations”.
Version History
Introduced in R2020a
See Also
isAlways | symtrue | and | or | not | xor
7-1466
symfun
symfun
Create symbolic functions
Syntax
f(inputs) = formula
f = symfun(formula,inputs)
Description
f(inputs) = formula creates the symbolic function f. For example, f(x,y) = x + y. The
symbolic variables in inputs are the input arguments. The symbolic expression formula is the body
of the function f.
Examples
Define the symbolic function f(x,y) = x + y. First, create the function by using syms. Then define
the function.
syms f(x,y)
f(x,y) = x + y
f(x, y) = x + y
ans = 3
f(x, y) = x + y
Return the body of a symbolic function by using formula. You can use the body for operations such
as indexing into the function. Return the arguments of a symbolic function by using argnames.
Index into the symbolic function [x^2, y^4]. Since a symbolic function is a scalar, you cannot
directly index into the function. Instead, index into the body of the function.
syms f(x,y)
f(x,y) = [x^2, y^4];
7-1467
7 Functions
fbody = formula(f);
fbody(1)
ans = x2
fbody(2)
ans = y4
fvars = argnames(f)
fvars = x y
Combine the two symbolic functions into another symbolic function h(x) with the data type symfun.
h(x) =
2 x2 − x
3 x2 + 2 x
h(1)
ans =
1
5
h(2)
ans =
6
16
You can also combine the two functions into an array of symbolic expressions with the data type sym.
h_expr =
2 x2 − x
3 x2 + 2 x
Index into h_expr to access the first and the second symbolic expressions.
7-1468
symfun
h_expr(1)
ans = 2 x2 − x
h_expr(2)
ans = 3 x2 + 2 x
Input Arguments
formula — Function body
symbolic expression | vector of symbolic expressions | matrix of symbolic expressions
Output Arguments
f — Symbolic function
symfun object
While the data type of the function f is symfun, the data type of the evaluated function, such as
f(1,2), is sym.
Version History
Introduced in R2012a
See Also
argnames | formula | matlabFunction | sym | syms | symvar
Topics
“Create Symbolic Functions” on page 1-9
7-1469
7 Functions
symFunType
Determine functional type of symbolic object
Syntax
s = symFunType(symObj)
Description
s = symFunType(symObj) returns the functional type of a symbolic object.
• If symObj is a symbolic function or a symbolic expression, then symFunType returns the topmost
function name or operator of symObj. For example, syms x; symFunType(2*sin(x)) returns
"times".
• If symObj is not a symbolic function or a symbolic expression, then symFunType returns the same
output as symType. For example, symFunType(sym('2')) returns "integer".
Examples
expr =
f x sin x ex ∫f x dx
∂
∂x
f x
s = 1x5 string
"f" "sin" "exp" "int" "diff"
Create two symbolic expressions. Determine the topmost arithmetic operators of the expressions.
syms x
expr1 = x/(x^2+x+2);
expr2 = x + 1/(x^2+x+2);
s1 = symFunType(expr1)
s1 =
"times"
7-1470
symFunType
s2 = symFunType(expr2)
s2 =
"plus"
terms1 = children(expr1)
terms2 = children(expr2)
syms x y
eqns = [x+y==2, x<=5, y>3]
eqns = x + y = 2 x ≤ 5 3 < y
s = symFunType(eqns)
s = 1x3 string
"eq" "le" "lt"
Input Arguments
symObj — Symbolic objects
symbolic expressions | symbolic functions | symbolic variables | symbolic numbers | symbolic units
Symbolic objects, specified as symbolic expressions, symbolic functions, symbolic variables, symbolic
numbers, or symbolic units.
Output Arguments
s — Symbolic functional types
string array
Symbolic functional types, returned as a string array. If symObj is a symbolic function or a symbolic
expression, then symFunType returns the topmost function name or operator of symObj. This table
shows output values for various symbolic objects.
7-1471
7 Functions
7-1472
symFunType
Version History
Introduced in R2019a
See Also
sym | syms | symfun | hasSymType | isSymType | symType
7-1473
7 Functions
symfunmatrix
Create symbolic matrix function
Syntax
f = symfunmatrix(formula,inputs)
f = symfunmatrix(formula,inputs,[nrow ncol])
Description
f = symfunmatrix(formula,inputs) creates the symbolic matrix function f. The symbolic
expression formula is the body of the function f that can be converted to the symmatrix data type.
The variables in inputs are the input arguments of the function f.
• If the input arguments of function f are multiple variables, inputs must be a cell array of
symbolic scalar and matrix variables.
• If the input argument of function f is a single variable, you can specify inputs as a symbolic
scalar variable or a symbolic matrix variable.
• If formula represents an unassigned abstract function, then f(var1,var2,...) has the size of
nrow-by-ncol. For example:
syms x 2 matrix;
f = symfunmatrix('g(x)',{x},[3 4]);
size(f(x))
ans =
3 4
• If formula represents a symbolic expression or a function with definition, then the size of
f(var1,var2,...) follows the size of formula. For example:
syms X Y 2 matrix;
f = symfunmatrix(X*Y - Y*X,{X,Y},[3 3]);
size(f(X,Y))
ans =
2 2
Examples
syms X Y [2 2] matrix
7-1474
symfunmatrix
Create a symbolic matrix function that represents the matrix operation XY − YX by using
symfunmatrix.
f = symfunmatrix(X*Y - Y*X,{X,Y})
f(X, Y) = X Y − Y X
12 −2 1
Evaluate the function for the matrix values X = and Y = . The evaluated function is a
22 0 4
symbolic matrix variable of data type symmatrix.
fEval =
−Σ1 + Σ2
where
0 −2
Σ1 =
8 8
−2 9
Σ2 =
−4 10
class(fEval)
ans =
'symmatrix'
fSym = symmatrix2sym(fEval)
fSym =
−2 11
−12 2
Input Arguments
formula — Function body
symbolic expression | abstract function
Function body, specified as a symbolic expression that can be converted to the symmatrix data type
or an abstract function.
Example: X*Y.'
Input argument or arguments of a function, specified as a cell array of symbolic scalar and matrix
variables, a symbolic scalar variable, or a symbolic matrix variable.
Example: {X,Y}, symmatrix('t',[2 3])
Data Types: cell | sym | symmatrix
7-1475
7 Functions
Dimensions of the evaluated symbolic matrix function, specified as a vector of nonnegative integers.
As a shortcut, you can create a square symbolic matrix function by specifying only one integer.
Example: [2 3]
Output Arguments
f — Symbolic matrix function
symfunmatrix object
While the data type of the function f is symfunmatrix, the data type of the evaluated function, such
as f([-2 3],[1 0]), is symmatrix.
Limitations
• To show all the functions in Symbolic Math Toolbox that accept symbolic matrix functions as input,
use the command methods symfunmatrix.
Tips
• When evaluating a symbolic matrix function, you must substitute values that have the same size as
the defined input arguments. For example, see “Define and Evaluate Symbolic Matrix Functions”
on page 7-1474. For comparison, this example returns an error:
syms X [2 2] matrix
syms f(X) [1 1] matrix keepargs
f(ones(4))
Version History
Introduced in R2022a
When creating a symbolic matrix function with a single variable as its input argument, you can
specify the inputs argument as a symbolic scalar variable or a symbolic matrix variable. For
example, you can create a symbolic matrix function using:
syms X [4 5] matrix
f = symfunmatrix("f(X)",X,[1 1])
In previous releases, the inputs argument must be a cell array of symbolic scalar and matrix
variables, even if function f has only one input argument.
See Also
argnames | formula | syms | symfun | symmatrix | symfunmatrix2symfun
7-1476
symfunmatrix
Topics
“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
“Use Symbolic Objects to Represent Mathematical Objects” on page 1-20
7-1477
7 Functions
symfunmatrix2symfun
Convert symbolic matrix function to symbolic function
Syntax
f = symfunmatrix2symfun(fM)
Description
f = symfunmatrix2symfun(fM) converts a symbolic matrix function fM of type symfunmatrix to
a symbolic function f of type symfun.
The output symbolic function has the same matrix dimensions as the input symbolic matrix function,
and its components are filled with automatically generated elements. For example, syms fM(x) [1
2] matrix; f = symfunmatrix2symfun(fM) converts the symbolic matrix function fM(x) to the
symbolic function f(x) = [fM1_1(x), fM1_2(x)]. The generated elements fM1_1 and fM1_2 do
not appear in the MATLAB workspace.
Examples
Create 2-by-1 and 2-by-2 symbolic matrix variables to represent the matrices X and A.
syms X [2 1] matrix
syms A [2 2] matrix
Create two symbolic matrix functions to represent the functions F X, A and ∂F X, A / ∂ XT . When
creating the symbolic matrix functions, keep existing definitions of the symbolic variables X and A in
the workspace. The symbolic matrix functions require matrices of the same sizes as X and A as their
input arguments.
Assign the function F X, A = X T A X and find its derivative ∂F X, A / ∂ XT . The results are in matrix
notation in terms of X and A.
F(X,A) = X.'*A*X
F(X, A) = X T A X
dF(X,A) = diff(F,X.')
dF(X, A) = A X + AT X
Convert the symbolic matrix functions from data type symfunmatrix to symfun. The results are in
scalar notation in terms of the matrix elements of X and A. These functions accept scalars as their
input arguments.
7-1478
symfunmatrix2symfun
Fsymfun = symfunmatrix2symfun(F)
Fsymfun(X1, X2, A1_1, A1_2, A2_1, A2_2) = X1 A1, 1 X1 + A1, 2 X2 + X2 A2, 1 X1 + A2, 2 X2
dFsymfun = symfunmatrix2symfun(dF)
Input Arguments
fM — Input
symbolic matrix function
Tips
• To show all the functions in Symbolic Math Toolbox that accept symbolic matrix functions as input,
use the command methods symfunmatrix.
Version History
Introduced in R2022a
See Also
syms | symfun | symfunmatrix
Topics
“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
“Use Symbolic Objects to Represent Mathematical Objects” on page 1-20
7-1479
7 Functions
symmatrix
Create symbolic matrix variable
Syntax
X = symmatrix('X',[nrow ncol])
X = symmatrix('X',n)
X = symmatrix('X')
X = symmatrix(S)
Description
X = symmatrix('X',[nrow ncol]) creates an nrow-by-ncol symbolic matrix variable X.
Symbolic matrix variables represent matrices, vectors, and scalars in compact matrix notation. For
more information, see “Create Symbolic Matrix Variables” on page 1-13.
Examples
Create two symbolic matrix variables with size 2-by-3. Nonscalar symbolic matrix variables are
displayed as bold characters in the Live Editor and Command Window.
A = symmatrix('A',[2 3])
A = A
B = symmatrix('B',[2 3])
B = B
Add the two matrices. The summation of the two symbolic matrix variables is denoted by the matrix
notation A+B.
X = A + B
X = A+B
Symbolic matrix variables represent matrices, vectors, and scalars in compact matrix notation. When
representing nonscalars, these variables are noncommutative. When mathematical formulas involve
7-1480
symmatrix
matrices and vectors, writing them using symbolic matrix variables is more concise and clear than
writing them componentwise.
A = symmatrix('A',[2 2]);
B = symmatrix('B',[2 2]);
Check the commutation relation for multiplication between two symbolic matrix variables.
A*B - B*A
ans = A B − B A
isequal(A*B,B*A)
ans = logical
0
Check the commutation relation for addition between two symbolic matrix variables.
isequal(A+B,B+A)
ans = logical
1
A = symmatrix('A',3)
A = A
X = symmatrix('X',[3 1])
X = X
Find the Hessian matrix of X T AX. Derived equations involving symbolic matrix variables are
displayed in typeset as they would be in textbooks.
f = X.'*A*X;
H = diff(f,X,X.')
H = AT + A
Create a Hilbert matrix of order 4. The data type of the matrix is double.
H = hilb(4)
7-1481
7 Functions
H = 4×4
class(H)
ans =
'double'
Convert the numeric matrix to a symbolic matrix variable. The data type of the converted matrix is
symmatrix.
X = symmatrix(H)
X =
Σ1
where
1 1 1
1
2 3 4
1 1 1 1
2 3 4 5
Σ1 =
1 1 1 1
3 4 5 6
1 1 1 1
4 5 6 7
class(X)
ans =
'symmatrix'
A = symmatrix('A',2)
A = A
B = symmatrix('B',2)
B = B
Perform matrix multiplication between A and B. The multiplication of the two symbolic matrix
variables is represented by the matrix notation AB.
X = A*B
X = AB
7-1482
symmatrix
Convert the symbolic matrix variable X to a matrix of symbolic scalar variables S. The multiplication
of two matrices of symbolic scalar variables is represented by the elements of the matrix product.
S = symmatrix2sym(X)
S =
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
Input Arguments
X — Variable name
character vector
Variable name, specified as a character vector. Argument X must be a valid variable name. That is, X
must begin with a letter and can contain only alphanumeric characters and underscores. To verify
that the name is a valid variable name, use isvarname.
Example: x, y12, z_1
Vector or matrix dimensions, specified as a vector of integers. nrow is the number of rows, and ncol
is the number of columns. As a shortcut, you can create a square symbolic matrix variable by
specifying only one integer. For example, X = symmatrix('X',3) creates a square 3-by-3 symbolic
matrix variable.
Example: [2 3], [2,3]
Numeric matrix or matrix of symbolic scalar variables to be converted to symbolic matrix variable,
specified as a number, numeric matrix, symbolic scalar variable, or a matrix of symbolic scalar
variables.
Example: 10, eye(3), pi, hilb(3)
Limitations
• Differentiation functions, such as jacobian and laplacian, currently do not accept symbolic
matrix variables as input. To evaluate differentiation with respect to vectors and matrices, you can
use the diff function instead.
• To show all the functions in Symbolic Math Toolbox that accept symbolic matrix variables as input,
use the command methods symmatrix.
Alternative Functionality
Alternative Approaches for Creating Symbolic Matrix Variables
To create several symbolic matrix variables in one function call, use syms var1 ... varN [nrow
ncol] matrix. For more details, see syms.
7-1483
7 Functions
Version History
Introduced in R2021a
See Also
syms | sym | symfun | symfunmatrix | str2sym | symvar | symmatrix2sym
Topics
“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
“Use Symbolic Objects to Represent Mathematical Objects” on page 1-20
7-1484
symmatrix2sym
symmatrix2sym
Convert symbolic matrix variable to array of scalar variables
Syntax
S = symmatrix2sym(M)
Description
S = symmatrix2sym(M) converts a symbolic matrix variable M of type symmatrix to an array of
symbolic scalar variables S of type sym.
The output array is the same size as the input symbolic matrix variable and its components are filled
with automatically generated elements. For example, syms M [1 3] matrix; S =
symmatrix2sym(M) creates the matrix S = [M1_1, M1_2, M1_3]. The generated elements M1_1,
M1_2, and M1_3 do not appear in the MATLAB workspace.
Examples
Create two symbolic matrix variables with size 2-by-3. Nonscalar symbolic matrix variables are
displayed as bold characters in the Live Editor and Command Window.
syms A B [2 3] matrix
A
A = A
B = B
Add the two matrices. The result is represented by the matrix notation A+B.
X = A + B
X = A+B
class(X)
ans =
'symmatrix'
Convert the symbolic matrix variable X to a matrix of symbolic scalar variables Y. The result is
denoted by the sum of the matrix components.
Y = symmatrix2sym(X)
Y =
7-1485
7 Functions
class(Y)
ans =
'sym'
Show that the converted result in Y is equal to the sum of two matrices of symbolic scalar variables.
syms A B [2 3]
Y2 = A + B
Y2 =
A1, 1 + B1, 1 A1, 2 + B1, 2 A1, 3 + B1, 3
A2, 1 + B2, 1 A2, 2 + B2, 2 A2, 3 + B2, 3
isequal(Y,Y2)
ans = logical
1
syms A [3 3] matrix
syms X [3 1] matrix
f = X.'*A*X;
H = diff(f,X,X.')
H = AT + A
Convert the result from a symbolic matrix variable H to a matrix of symbolic scalar variables S.
S = symmatrix2sym(H)
S =
2 A1, 1 A1, 2 + A2, 1 A1, 3 + A3, 1
A1, 2 + A2, 1 2 A2, 2 A2, 3 + A3, 2
A1, 3 + A3, 1 A2, 3 + A3, 2 2 A3, 3
7-1486
symmatrix2sym
syms A [1 3] matrix
Find the 2-norm of the vector A. The result is a symbolic matrix variable with symmatrix data type.
N = norm(A)
N = A 2
class(N)
ans =
'symmatrix'
Convert N to a symbolic scalar variable to express the 2-norm in terms of the components of A. The
result is a symbolic scalar variable with sym data type.
N = symmatrix2sym(N)
N =
2 2 2
A1, 1 + A1, 2 + A1, 3
class(N)
ans =
'sym'
syms A B [3 1] matrix
C = transpose(A)*B
C = AT B
Convert C to a symbolic scalar variable to express the dot product in terms of the components of A
and B.
C = symmatrix2sym(C)
C = A1 B1 + A2 B2 + A3 B3
syms A B [2 3] matrix
Concatenate the two matrices vertically using the command vertcat(A,B) or [A; B].
7-1487
7 Functions
C = [A; B]
C =
A
B
C = symmatrix2sym(C)
C =
A1, 1 A1, 2 A1, 3
A2, 1 A2, 2 A2, 3
B1, 1 B1, 2 B1, 3
B2, 1 B2, 2 B2, 3
Input Arguments
M — Input
symbolic matrix variable
Tips
• To show all the functions in Symbolic Math Toolbox that accept symbolic matrix variables as input,
use the command methods symmatrix.
Version History
Introduced in R2021a
See Also
sym | syms | symfun | str2sym | symmatrix | symfunmatrix2symfun
Topics
“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
“Use Symbolic Objects to Represent Mathematical Objects” on page 1-20
7-1488
sympref
sympref
Set symbolic preferences
Syntax
oldVal = sympref(pref,value)
oldVal = sympref(pref)
oldPrefs = sympref(prefs)
oldPrefs = sympref()
Description
oldVal = sympref(pref,value) sets the symbolic preference pref to value and returns the
previous value of the preference to oldVal. You can set the preference to its default value using
sympref(pref,'default').
Symbolic preferences can affect the computation of the symbolic functions fourier, ifourier, and
heaviside, and the display format of symbolic output.
oldPrefs = sympref(prefs) sets multiple symbolic preferences to the values in the structure
prefs and returns the previous values of all preferences to oldPrefs. You can set all symbolic
preferences to their default values using sympref('default').
Note Symbolic preferences persist through successive MATLAB sessions. Opening a new session
does not restore the default preferences.
Examples
∫
∞
F w =c f t ei swt dt,
−∞
where c and s are parameters with the default values 1 and –1, respectively. Other common values for
c are 1/ 2π and 1/ 2π, and other common values for s are 1, −2π, and 2π.
F = −π δ w − 1 − δ w + 1 i
7-1489
7 Functions
Find the same Fourier transform with c = 1/ 2π and s = 1. Set the parameter values by using the
'FourierParameters' preference. Represent π exactly by using sym. Specify the values of c and s
as the vector [1/(2*sym(pi)) 1]. Store the previous values returned by sympref so that you can
restore them later.
oldVal = 1 −1
F = fourier(sin(t),t,w)
F =
δ w−1 i δ w+1 i
−
2 2
The preferences you set using sympref persist through your current and future MATLAB® sessions.
Restore the previous values of c and s to oldVal.
sympref('FourierParameters',oldVal);
Alternatively, you can restore the default values of c and s by specifying the 'default' option.
sympref('FourierParameters','default');
In Symbolic Math Toolbox™, the default value of the Heaviside function at the origin is 1/2. Return
the value of heaviside(0). Find the Z-transform of heaviside(x) for this default value of
heaviside(0).
syms x
H = heaviside(sym(0))
H =
1
2
Z = ztrans(heaviside(x))
Z =
1 1
+
z−1 2
Other common values for the Heaviside function at the origin are 0 and 1. Set heaviside(0) to 1
using the 'HeavisideAtOrigin' preference. Store the previous value returned by sympref so that
you can restore it later.
oldVal = sympref('HeavisideAtOrigin',1)
oldVal =
1
2
Check if the new value of heaviside(0) is 1. Find the Z-transform of heaviside(x) for this value.
H = heaviside(sym(0))
7-1490
sympref
H = 1
Z = ztrans(heaviside(x))
Z =
1
+1
z−1
The preferences you set using sympref persist through your current and future MATLAB® sessions.
Restore the previous value of heaviside(0) to oldVal.
sympref('HeavisideAtOrigin',oldVal);
Alternatively, you can restore the default value of 'HeavisideAtOrigin' by specifying the
'default' option.
sympref('HeavisideAtOrigin','default');
By default, symbolic expressions in live scripts are displayed in abbreviated output format, and
typeset in mathematical notation. You can turn off abbreviated output format and typesetting using
symbolic preferences.
Create a symbolic expression and return the output, which is abbreviated by default.
syms a b c d x
f = a*x^3 + b*x^2 + c*x + d;
outputAbbrev = sin(f) + cos(f) + tan(f) + log(f) + 1/f
outputAbbrev =
1
cos σ1 + log σ1 + sin σ1 + tan σ1 +
σ1
where
σ1 = a x3 + b x2 + c x + d
Turn off abbreviated output format by setting the 'AbbreviateOutput' preference to false.
Redisplay the expression.
sympref('AbbreviateOutput',false);
outputLong = sin(f) + cos(f) + tan(f) + log(f) + 1/f
outputLong =
cos a x3 + b x2 + c x + d + log a x3 + b x2 + c x + d + sin a x3 + b x2 + c x + d + tan a x3 + b x2 + c x + d
1
+
a x3 + b x2 + c x + d
Create another symbolic expression and return the output, which is typeset in mathematical notation
by default. Turn off rendered output and use ASCII output instead by setting the 'TypesetOutput'
preference to false. First, show the typeset output.
7-1491
7 Functions
syms a b c d x
f = exp(a^b)+pi
b
f = π + ea
Turn off typesetting by setting the 'TypesetOutput' preference to false. Redisplay the
expression.
sympref('TypesetOutput',false);
f = exp(a^b)+pi
f =
pi + exp(a^b)
The preferences you set using sympref persist through your current and future MATLAB® sessions.
Restore the default values of 'AbbreviateOutput' and 'TypesetOutput' by specifying the
'default' option.
sympref('AbbreviateOutput','default');
sympref('TypesetOutput','default');
Display symbolic results in floating-point output format, that is the short, fixed-decimal format with 4
digits after the decimal point.
eq =
2000 x 1
x2 − + =0
π 2
sols =
2 2000000 − π2 − 2000
−
2π
2 2000000 − π2 + 2000
2π
Set the 'FloatingPointOutput' preference to true. Display the quadratic equation and its
solutions in floating-point format.
sympref('FloatingPointOutput',true);
eq
eq = x2 − 636.6198 x + 0.5000 = 0
7-1492
sympref
sols
sols =
7.8540e−04
636.6190
The floating-point format displays each symbolic number in the short, fixed-decimal format with 4
digits after the decimal point. Setting the 'FloatingPointOutput' preference does not affect the
floating-point precision in a symbolic computation. To compute symbolic numbers using floating-point
arithmetic, use the vpa function.
Now restore the default value of 'FloatingPointOutput' by specifying the 'default' option.
Compute the floating-point approximation of the solutions in 8 significant digits using vpa.
sympref('FloatingPointOutput','default');
sols = vpa(sols,8)
sols =
0.00078539913
636.61899
Create a symbolic polynomial expression consisting of multiple variables. Display the polynomial in
the default order.
syms x y a b
p1 = b^2*x^2 + a^2*x + y^3 + 2
2
p1 = a2 x + b x2 + y3 + 2
The default option sorts the output in alphabetical order, without distinguishing the different symbolic
variables in each monomial term.
Now display the same polynomial in ascending order by setting the preference
'PolynomialDisplayStyle' to 'ascend'.
sympref('PolynomialDisplayStyle','ascend');
p1
2
p1 = 2 + y3 + a2 x + b x2
The 'ascend' option sorts the output in ascending order based on the importance of the variables.
Here, the most important variable x with the highest order in a monomial term is displayed last.
sympref('PolynomialDisplayStyle','descend');
p1
2
p1 = b x2 + a2 x + y3 + 2
7-1493
7 Functions
The preferences you set using sympref persist through your current and future MATLAB® sessions.
Restore the default value of 'PolynomialDisplayStyle' by specifying the 'default' option.
sympref('PolynomialDisplayStyle','default');
By default, a symbolic matrix in live scripts is set in parentheses (round brackets). You can specify the
use of square brackets instead by using sympref.
syms x y
A = [x*y, 2; 4, y^2]
A =
xy 2
4 y2
Display the matrix with square brackets by setting the 'MatrixWithSquareBrackets' preference
to true.
sympref('MatrixWithSquareBrackets',true);
A
A =
xy 2
4 y2
The preferences you set using sympref persist through your current and future MATLAB® sessions.
Restore the default value by specifying the 'default' option.
sympref('MatrixWithSquareBrackets','default');
Instead of saving and restoring individual preferences one by one, you can use sympref to save and
restore all symbolic preferences simultaneously.
Return a structure containing the values of all symbolic preferences by using sympref().
oldPrefs = sympref()
7-1494
sympref
Access the value of each symbolic preference by addressing the field of the structure. Alternatively,
you can use the command sympref(pref).
val1 = oldPrefs.FourierParameters
val1 = 1 −1
val2 = oldPrefs.HeavisideAtOrigin
val2 =
1
2
val3 = sympref('FourierParameters')
val3 = 1 −1
To modify multiple symbolic preferences simultaneously, you can create a structure prefs that
contains the preference values. Use the command sympref(prefs) to set multiple preferences.
prefs.FourierParameters = [1/(2*sym(pi)) 1]
prefs.HeavisideAtOrigin = 1
sympref(prefs);
Because symbolic preferences persist through your current and future MATLAB® sessions, you need
to restore your previous preferences. Restore the saved preferences using sympref(oldPrefs).
sympref(oldPrefs);
Alternatively, you can set all symbolic preferences to their default values by specifying the
'default' option.
sympref('default');
Input Arguments
pref — Symbolic preference
character vector | string
Symbolic preference, specified as a character vector or string. The value options for each symbolic
preference follow.
7-1495
7 Functions
Default:
sym([1,-1]). See “Change Parameter Values of Fourier
Transform” on page 7-1489.
'HeavisideAtOrigi Scalar value, specified Set the value of the Heaviside function
n' as a numeric or heaviside(0) at the origin.
symbolic number.
See “Change Value of Heaviside Function at Origin”
Default: sym(1/2). on page 7-1490.
'AbbreviateOutput Logical value Specify whether or not to use abbreviated output
' (boolean). format of symbolic variables and expressions in Live
Scripts.
Default: logical 1
(true). See “Modify Display of Symbolic Expressions in Live
Scripts” on page 7-1491.
'TypesetOutput' Logical value Typeset or use ASCII characters for the output of
(boolean). symbolic variables and expressions in Live Scripts.
7-1496
sympref
Value of symbolic preference, specified as 'default' or a valid value of the specified preference
pref.
Symbolic preferences, specified as a structure array. You can set multiple preferences by declaring
the field names and the valid preference values.
Output Arguments
oldVal — Value of symbolic preference
valid value
Value of symbolic preference, returned as a valid value. oldVal represents the existing value of the
preference pref before the call to sympref.
7-1497
7 Functions
All symbolic preferences, returned as a structure array. oldPrefs represent the existing values of all
preferences before the call to sympref.
Tips
• The clear command does not reset or affect symbolic preferences. Use sympref to manipulate
symbolic preferences.
• The symbolic preferences you set using sympref also determine the output generated by the
latex and mathml functions.
• Setting the 'FloatingPointOutput' preference affects only the output display format of
symbolic numbers. To change the output display format of numeric numbers, use the format
function. To compute symbolic numbers using floating-point precision, use the vpa or digits
functions.
Version History
Introduced in R2015a
See Also
fourier | heaviside | ifourier | digits | vpa | taylor | latex | mathml
Topics
“Change Output Display Format of Symbolic Results in the Live Editor” on page 2-11
“Change Output Format of Symbolic and Variable-Precision Arithmetic” on page 2-8
7-1498
symprod
symprod
Product of series
Syntax
F = symprod(f,k,a,b)
F = symprod(f,k)
Description
F = symprod(f,k,a,b) returns the product of the series with terms that expression f specifies,
which depend on symbolic variable k. The value of k ranges from a to b. If you do not specify k,
symprod uses the variable that symvar determines. If f is a constant, then the default variable is x.
F = symprod(f,k) returns the product of the series that expression f specifies, which depend on
symbolic variable k. The value of k starts at 1 with an unspecified upper bound. The product F is
returned in terms of k where k represents the upper bound. This product F differs from the indefinite
product. If you do not specify k, symprod uses the variable that symvar determines. If f is a
constant, then the default variable is x.
Examples
Find Product of Series Specifying Bounds
syms k
P1 = symprod(1 - 1/k^2, k, 2, Inf)
P2 = symprod(k^2/(k^2 - 1), k, 2, Inf)
P1 =
1/2
P2 =
2
syms k
P1 = symprod(1 - 1/k^2, k, [2 Inf])
P2 = symprod(k^2/(k^2 - 1), k, [2; Inf])
P1 =
1/2
P2 =
2
7-1499
7 Functions
syms k x
P = symprod(exp(k*x)/x, k, 1, 10000)
P =
exp(50005000*x)/x^10000
When you do not specify the bounds of a series are unspecified, the variable k starts at 1. In the
returned expression, k itself represents the upper bound.
P1 = ∏ k,
k
P2 = ∏ 2k −2 1 .
k k
syms k
P1 = symprod(k, k)
P2 = symprod((2*k - 1)/k^2, k)
P1 =
factorial(k)
P2 =
(1/2^(2*k)*2^(k + 1)*factorial(2*k))/(2*factorial(k)^3)
Input Arguments
f — Expression defining terms of series
symbolic expression | symbolic function | symbolic vector | symbolic matrix | symbolic number
Expression defining terms of series, specified as a symbolic expression, function, constant, or a vector
or matrix of symbolic expressions, functions, or constants.
k — Product index
symbolic variable
Product index, specified as a symbolic variable. If you do not specify this variable, symprod uses the
default variable that symvar(expr,1) determines. If f is a constant, then the default variable is x.
Lower bound of product index, specified as a number, symbolic number, variable, expression, or
function (including expressions and functions with infinities).
7-1500
symprod
Upper bound of product index, specified as a number, symbolic number, variable, expression, or
function (including expressions and functions with infinities).
More About
Definite Product
Indefinite Product
f (i) = ∏ xi
i
This definition holds under the assumption that the following identity is true for all values of i.
f i+1
= xi
f i
Version History
Introduced in R2011b
See Also
cumprod | cumsum | int | syms | symsum | symvar
7-1501
7 Functions
symReadSSCParameters
Load parameters from Simscape component
Syntax
[names,values,units] = symReadSSCParameters(componentName)
Description
[names,values,units] = symReadSSCParameters(componentName) returns cell arrays
containing the names, values, and units of all parameters from the Simscape component called
componentName.
Examples
Load the names, values, and units of the parameters of a Simscape component.
Suppose you have the Simscape component friction.ssc in your current folder.
type('friction.ssc');
parameters
brkwy_trq = { 25, 'N*m' }; % Breakaway friction torque
Col_trq = { 20, 'N*m' }; % Coulomb friction torque
visc_coef = { 0.001, 'N*m*s/rad' }; % Viscous friction coefficient
trans_coef = { 10, 's/rad' }; % Transition approximation coefficient
vel_thr = { 1e-4, 'rad/s' }; % Linear region velocity threshold
end
parameters (Access=private)
brkwy_trq_th = { 24.995, 'N*m' }; % Breakaway torque at threshold velocity
end
function setup
% Parameter range checking
if brkwy_trq <= 0
pm_error('simscape:GreaterThanZero','Breakaway friction torque' )
end
if Col_trq <= 0
pm_error('simscape:GreaterThanZero','Coulomb friction torque' )
end
if Col_trq > brkwy_trq
pm_error('simscape:LessThanOrEqual','Coulomb friction torque',...
'Breakaway friction torque')
end
if visc_coef < 0
pm_error('simscape:GreaterThanOrEqualToZero','Viscous friction coefficient')
7-1502
symReadSSCParameters
end
if trans_coef <= 0
pm_error('simscape:GreaterThanZero','Transition approximation coefficient')
end
if vel_thr <= 0
pm_error('simscape:GreaterThanZero','Linear region velocity threshold')
end
equations
if (abs(w) <= vel_thr)
% Linear region
t == brkwy_trq_th * w / vel_thr;
elseif w > 0
t == visc_coef * w + Col_trq + ...
(brkwy_trq - Col_trq) * exp(-trans_coef * w);
else
t == visc_coef * w - Col_trq - ...
(brkwy_trq - Col_trq) * exp(-trans_coef * abs(w));
end
end
end
Load the names, values, and units of the parameters of the component friction.ssc.
[names,values,units] = symReadSSCParameters('friction.ssc');
In this example, all elements of the resulting cell arrays are scalars. You can convert the cell arrays to
symbolic vectors.
names_sym = cell2sym(names)
names_sym =
[ Col_trq, brkwy_trq, brkwy_trq_th, trans_coef, vel_thr, visc_coef]
values_sym = cell2sym(values)
values_sym =
[ 20, 25, 4999/200, 10, 1/10000, 1/1000]
Create individual symbolic variables from the elements of the cell array names in the MATLAB
workspace. This command creates the symbolic variables Col_trq, brkwy_trq, brkwy_trq_th,
trans_coef, vel_thr, and visc_coef as sym objects in the workspace.
syms(names)
Input Arguments
componentName — Simscape component name
file name enclosed in single quotes
7-1503
7 Functions
Simscape component name, specified as a file name enclosed in single quotes. The file must have the
extension .ssc. If you do not provide the file extension, symReadSSCParameters assumes it to
be .ssc. The component must be on the MATLAB path or in the current folder.
Example: 'MyComponent.ssc'
Output Arguments
names — Names of all parameters of Simscape component
cell array
Version History
Introduced in R2016a
See Also
symReadSSCVariables | symWriteSSC
7-1504
symReadSSCVariables
symReadSSCVariables
Load variables from Simscape component
Syntax
[names,values,units] = symReadSSCVariables(componentName)
[names,values,units] = symReadSSCVariables(
componentName,'ReturnFunctions',true)
Description
[names,values,units] = symReadSSCVariables(componentName) returns cell arrays
containing the names, values, and units of all variables from the Simscape component called
componentName.
[names,values,units] = symReadSSCVariables(
componentName,'ReturnFunctions',true) returns the names as symbolic functions of variable
t.
Examples
Load the names, values, and units of the variables of a Simscape component.
Suppose you have the Simscape component friction.ssc in your current folder.
type('friction.ssc');
parameters
brkwy_trq = { 25, 'N*m' }; % Breakaway friction torque
Col_trq = { 20, 'N*m' }; % Coulomb friction torque
visc_coef = { 0.001, 'N*m*s/rad' }; % Viscous friction coefficient
trans_coef = { 10, 's/rad' }; % Transition approximation coefficient
vel_thr = { 1e-4, 'rad/s' }; % Linear region velocity threshold
end
parameters (Access=private)
brkwy_trq_th = { 24.995, 'N*m' }; % Breakaway torque at threshold velocity
end
function setup
% Parameter range checking
if brkwy_trq <= 0
pm_error('simscape:GreaterThanZero','Breakaway friction torque' )
end
if Col_trq <= 0
pm_error('simscape:GreaterThanZero','Coulomb friction torque' )
end
7-1505
7 Functions
equations
if (abs(w) <= vel_thr)
% Linear region
t == brkwy_trq_th * w / vel_thr;
elseif w > 0
t == visc_coef * w + Col_trq + ...
(brkwy_trq - Col_trq) * exp(-trans_coef * w);
else
t == visc_coef * w - Col_trq - ...
(brkwy_trq - Col_trq) * exp(-trans_coef * abs(w));
end
end
end
Load the names, values, and units of the variables of the component friction.ssc.
[names,values,units] = symReadSSCVariables('friction.ssc');
In this example, all elements of the resulting cell arrays are scalars. You can convert the cell arrays to
symbolic vectors.
names_sym = cell2sym(names)
names_sym =
[ t, w]
values_sym = cell2sym(values)
values_sym =
[ 0, 0]
Create individual symbolic variables from the elements of the cell array names in the MATLAB
workspace. This command creates the symbolic variables t and w as sym objects in the workspace.
syms(names)
7-1506
symReadSSCVariables
Load the names of the variables of a Simscape component while converting them to symbolic
functions of the variable t.
Suppose you have the Simscape component source.ssc in your current folder.
type('source.ssc');
component source
% Electrical Source
% Defines an electrical source with positive and negative external nodes.
% Also defines associated through and across variables.
nodes
p = foundation.electrical.electrical; % :top
n = foundation.electrical.electrical; % :bottom
end
variables(Access=protected)
i = { 0, 'A' }; % Current
v = { 0, 'V' }; % Voltage
end
branches
i : p.i -> n.i;
end
equations
v == p.v - n.v;
end
end
Load the names of the variables of the component source.ssc by setting 'ReturnFunctions' to
true.
[names,~,~] = symReadSSCVariables('source.ssc','ReturnFunctions',true);
In this example, all elements of the resulting cell arrays are scalars. You can convert the cell arrays to
symbolic vectors.
names_symfun = cell2sym(names)
names_symfun =
[ i(t), v(t)]
Create individual symbolic functions from the elements of the cell array names in the MATLAB
workspace. This command creates the symbolic functions i and v as symfun objects, and their
variable t as a sym object in the workspace.
syms(names)
Input Arguments
componentName — Simscape component name
file name enclosed in single quotes
7-1507
7 Functions
Simscape component name, specified as a file name enclosed in single quotes. The file must have the
extension .ssc. If you do not provide the file extension, symReadSSCVariables assumes it to
be .ssc. The component must be on the MATLAB path or in the current folder.
Example: 'MyComponent.ssc'
Output Arguments
names — Names of all variables of Simscape component
cell array
Version History
Introduced in R2016a
See Also
symReadSSCParameters | symWriteSSC
7-1508
syms
syms
Create symbolic scalar variables and functions, and matrix variables and functions
Syntax
syms var1 ... varN
syms var1 ... varN [n1 ... nM]
syms var1 ... varN n
syms ___ set
syms f(var1,...,varN)
syms f(var1,...,varN) [n1 ... nM]
syms f(var1,...,varN) n
syms(symArray)
syms
S = syms
Description
Symbolic Scalar Variables
syms var1 ... varN creates symbolic scalar variables var1 ... varN of type sym. Separate the
different variables with spaces. This syntax clears all previous definitions of var1 ... varN.
syms var1 ... varN [n1 ... nM] creates arrays of symbolic scalar variables var1 ... varN,
where each array has the size n1-by-...-by-nM and contains automatically generated symbolic scalar
variables as its elements. For example, syms a [1 3] creates the symbolic array a = [a1 a2 a3]
and the symbolic scalar variables a1, a2, and a3 in the MATLAB workspace. For multidimensional
arrays, these elements have the prefix a followed by the element’s index using _ as a delimiter, such
as a1_3_2.
syms var1 ... varN n creates n-by-n matrices of symbolic scalar variables filled with
automatically generated elements.
syms ___ set sets the assumption that the created symbolic scalar variables belong to set, and
clears other assumptions. Here, set can be real, positive, integer, or rational. You can also
combine multiple assumptions using spaces. For example, syms x positive rational creates a
symbolic scalar variable x with a positive rational value. Use this option in addition to any of the input
argument combinations in previous syntaxes.
7-1509
7 Functions
syms f(var1,...,varN) creates the symbolic function f of type symfun and the symbolic scalar
variables var1,...,varN of type sym, which represent the input arguments of f. This syntax clears
all previous definitions of var1,...,varN including symbolic assumptions. The evaluated symbolic
function f(var1,...,varN) is of type sym.
syms f(var1,...,varN) [n1 ... nM] creates an n1-by-...-by-nM symbolic array with
automatically generated symbolic functions as its elements. This syntax also generates the symbolic
scalar variables var1,...,varN that represent the input arguments of f. For example, syms f(x)
[1 2] creates the symbolic array f(x) = [f1(x) f2(x)], the symbolic functions f1 and f2, and
the symbolic scalar variable x in the MATLAB workspace. For multidimensional arrays, these
elements have the prefix f followed by the element’s index using _ as a delimiter, such as f1_3_2.
syms f(var1,...,varN) n creates an n-by-n matrix of symbolic functions filled with automatically
generated elements.
Symbolic Matrix Variables
syms var1 ... varN [nrow ncol] matrix creates symbolic matrix variables var1 ... varN
of type symmatrix, where each symbolic matrix variable has the size nrow-by-ncol. (since R2021a)
syms var1 ... varN n matrix creates n-by-n symbolic matrix variables. (since R2021a)
Symbolic Matrix Functions
syms f(var1,...,varN) [nrow ncol] matrix creates the symbolic matrix function f of type
symfunmatrix and the symbolic scalar variables var1,...,varN of type sym. The evaluated
symbolic matrix function f(var1,...,varN) is of type symmatrix and has the size nrow-by-ncol.
This syntax clears all previous definitions of var1,...,varN including symbolic assumptions. (since
R2022a)
syms f(var1,...,varN) n matrix creates a square symbolic matrix function, where the
evaluated symbolic matrix function f(var1,...,varN) has the size n-by-n. This syntax clears all
previous definitions of var1,...,varN including symbolic assumptions. (since R2022a)
syms(symArray) creates the symbolic scalar variables and functions contained in symArray, where
symArray is either a vector of symbolic scalar variables or a cell array of symbolic scalar variables
and functions. This syntax clears all previous definitions of variables specified in symArray including
symbolic assumptions. Use this syntax only when such an array is returned by another function, such
as solve or symReadSSCVariables.
Names of Symbolic Objects
syms lists the names of all symbolic scalar variables, functions, matrix variables, matrix functions,
and arrays in the MATLAB workspace.
7-1510
syms
S = syms returns a cell array of the names of all symbolic scalar variables, functions, matrix
variables, matrix functions, and arrays.
Examples
syms x y
x
x = x
y = y
Create a 1-by-4 vector of symbolic scalar variables a with the automatically generated elements
a1, …, a4. This command also creates the symbolic scalar variables a1, ..., a4 in the MATLAB
workspace.
syms a [1 4]
a
a = a1 a2 a3 a4
whos
a 1x4 8 sym
a1 1x1 8 sym
a2 1x1 8 sym
a3 1x1 8 sym
a4 1x1 8 sym
You can change the naming format of the generated elements by using a format character vector.
Declare the symbolic scalar variables by enclosing each variable name in single quotes. syms
replaces %d in the format character vector with the index of the element to generate the element
names.
p_b
7-1511
7 Functions
Create a 3-by-4 matrix of symbolic scalar variables with automatically generated elements. The
elements are of the form Ai, j, which generates the symbolic matrix variables A1, 1, …, A3, 4.
syms A [3 4]
A
A =
A1, 1 A1, 2 A1, 3 A1, 4
A2, 1 A2, 2 A2, 3 A2, 4
A3, 1 A3, 2 A3, 3 A3, 4
Create symbolic scalar variables x and y, and assume that they are integers.
syms x y integer
Create another scalar variable z, and assume that it has a positive rational value.
Check assumptions.
assumptions
ans = x ∈ ℤ y ∈ ℤ z ∈ ℚ 0 < z
Alternatively, check assumptions on each variable. For example, check assumptions set on the
variable x.
assumptions(x)
ans = x ∈ ℤ
assume([x y z],'clear')
assumptions
ans =
Create a 1-by-3 symbolic array a, and assume that the array elements have real values.
syms a [1 3] real
assumptions
ans = a1 ∈ ℝ a2 ∈ ℝ a3 ∈ ℝ
7-1512
syms
Both s and f are abstract symbolic functions. They do not have symbolic expressions assigned to
them, so the bodies of these functions are s(t) and f(x,y), respectively.
f(x, y) = x + 2 y
ans = 5
Create a symbolic function and specify its formula by using a matrix of symbolic scalar variables.
syms x
M = [x x^3; x^2 x^4];
f(x) = M
f(x) =
x x3
x2 x4
ans =
2 8
4 16
Compute the value of this function for x = [1 2 3; 4 5 6]. The result is a cell array of symbolic
matrices.
xVal = [1 2 3; 4 5 6];
y = f(xVal)
7-1513
7 Functions
y{1}
ans =
123
456
Create a 2-by-2 symbolic matrix with automatically generated symbolic functions as its elements.
syms f(x,y) 2
f
f(x, y) =
f 1, 1 x, y f 1, 2 x, y
f 2, 1 x, y f 2, 2 x, y
Assign symbolic expressions to the symbolic functions f1_1(x,y) and f2_2(x,y). These functions
are displayed as f 1, 1(x, y) and f 2, 2(x, y) in the Live Editor. When you assign these expressions, the
symbolic matrix f still contains the initial symbolic functions in its elements.
f1_1(x,y) = 2*x;
f2_2(x,y) = x - y;
f
f(x, y) =
f 1, 1 x, y f 1, 2 x, y
f 2, 1 x, y f 2, 2 x, y
Substitute the expressions assigned to f1_1(x,y) and f2_2(x,y) by using the subs function.
A = subs(f)
A(x, y) =
2x f 1, 2 x, y
f 2, 1 x, y x−y
Evaluate the value of the symbolic matrix A, which contains the substituted expressions, at x = 2
and y = 3.
A(2,3)
ans =
4 f 1, 2 2, 3
f 2, 1 2, 3 −1
Create two symbolic matrix variables with size 2-by-3. Nonscalar symbolic matrix variables are
displayed as bold characters in the Live Editor and Command Window.
7-1514
syms
syms A B [2 3] matrix
A
A = A
B = B
Add the two matrices. The result is represented by the matrix notation A+B.
X = A + B
X = A+B
ans =
'symmatrix'
Convert the symbolic matrix variable X to a matrix of symbolic scalar variables Y. The result is
denoted by the sum of the matrix components.
Y = symmatrix2sym(X)
Y =
A1, 1 + B1, 1 A1, 2 + B1, 2 A1, 3 + B1, 3
A2, 1 + B2, 1 A2, 2 + B2, 2 A2, 3 + B2, 3
ans =
'sym'
Show that the converted result in Y is equal to the sum of two matrices of symbolic scalar variables.
syms A B [2 3]
Y2 = A + B
Y2 =
A1, 1 + B1, 1 A1, 2 + B1, 2 A1, 3 + B1, 3
A2, 1 + B2, 1 A2, 2 + B2, 2 A2, 3 + B2, 3
isequal(Y,Y2)
ans = logical
1
Symbolic matrix variables represent matrices, vectors, and scalars in compact matrix notation. When
representing nonscalars, these variables are noncommutative. When mathematical formulas involve
7-1515
7 Functions
matrices and vectors, writing them using symbolic matrix variables is more concise and clear than
writing them componentwise.
syms A B [2 2] matrix
Check the commutation relation for multiplication between two symbolic matrix variables.
A*B - B*A
ans = A B − B A
isequal(A*B,B*A)
ans = logical
0
Check the commutation relation for addition between two symbolic matrix variables.
isequal(A+B,B+A)
ans = logical
1
syms A 3 matrix
syms X [3 1] matrix
Find the Hessian matrix of X T AX. Derived equations involving symbolic matrix variables are
displayed in typeset as they would be in textbooks.
f = X.'*A*X
f = XT A X
H = diff(f,X,X.')
H = AT + A
r 2
Create the function v r, t = t
, where r is a 1-by-3 vector and t is a scalar.
Create r as a symbolic matrix variable and t as a symbolic scalar variable. Create v r, t as a symbolic
matrix function and keep existing definitions of r and t in the workspace.
7-1516
syms
syms r [1 3] matrix
syms t
syms v(r,t) [1 1] matrix keepargs
v(r,t) = norm(r)/t
v(r, t) = r 2 t−1
The symbolic matrix function accepts scalars, vectors, and matrices as its input arguments. Evaluate
the function for the vector value r = 1, 2, 2 and the scalar value t = 3.
vEval =
1
Σ
3 1 2
where
Σ1 = 1 2 2
Convert the evaluated function from the symmatrix data type to the sym data type.
vSym = symmatrix2sym(vEval)
vSym = 1
Certain functions, such as solve and symReadSSCVariables, can return a vector of symbolic scalar
variables or a cell array of symbolic scalar variables and functions. These variables or functions do
not automatically appear in the MATLAB workspace. Create these variables or functions from the
vector or cell array by using syms.
Solve the equation sin(x) == 1 by using solve. The parameter k in the solution does not appear in
the MATLAB workspace.
syms x
eqn = sin(x) == 1;
[sol,parameter,condition] = solve(eqn,x,'ReturnConditions',true);
parameter
parameter = k
Create the parameter k by using syms. The parameter k now appears in the MATLAB workspace.
syms(parameter)
Similarly, use syms to create the symbolic objects contained in a vector or cell array. Examples of
functions that return a cell array of symbolic objects are symReadSSCVariables and
symReadSSCParameters.
7-1517
7 Functions
Create some symbolic scalar variables, functions, matrix variables, matrix functions, and arrays.
syms a f(x)
syms A [2 1]
syms B [2 2] matrix
syms g(B) [2 2] matrix keepargs
Display a list of all symbolic scalar variables, functions, matrix variables, matrix functions, and arrays
that currently exist in the MATLAB workspace by using syms.
syms
A A1 A2 B a f g x
S = 8x1 cell
{'A' }
{'A1'}
{'A2'}
{'B' }
{'a' }
{'f' }
{'g' }
{'x' }
Return all symbolic objects as a cell array by using the syms function. Use the cellfun function to
delete all symbolic objects in the cell array symObj.
symObj = syms;
cellfun(@clear,symObj)
Check that you deleted all symbolic objects by calling syms. The output is empty, meaning no
symbolic objects exist in the MATLAB workspace.
syms
Input Arguments
var1 ... varN — Symbolic scalar variables, matrices, arrays, or matrix variables
valid variable names separated by spaces
7-1518
syms
Symbolic scalar variables, matrices, arrays, or matrix variables, specified as valid variable names
separated by spaces. That is, each variable name must begin with a letter and can contain only
alphanumeric characters and underscores. To verify that a variable name is valid, use isvarname.
Example: x y123 z_1
[n1 ... nM] — Dimensions of vector, matrix, or array of symbolic scalar variables
vector of nonnegative integers
Dimensions of the square matrix, specified as a nonnegative scalar integer. For example, syms x 3
matrix creates a square 3-by-3 symbolic matrix variable.
Example: 3
You can combine multiple assumptions using spaces. For example, syms x positive rational
creates a symbolic scalar variable x with a positive rational value.
Example: rational
Symbolic function or matrix function with its input arguments, specified as function and variable
names with parentheses. The function name f and the variable names var1...varN must be valid
variable names. That is, they must begin with a letter and can contain only alphanumeric characters
and underscores. To verify that a variable name is valid, use isvarname.
Example: F(r,t), f(x,y)
Symbolic scalar variables and functions to create, specified as a vector of symbolic scalar variables or
a cell array of symbolic scalar variables and functions. Such a vector or array is typically the output of
another function, such as solve or symReadSSCVariables.
7-1519
7 Functions
Output Arguments
S — Names of all symbolic scalar variables, functions, matrix variables, matrix functions,
and arrays
cell array of character vectors
Names of all symbolic scalar variables, functions, matrix variables, matrix functions, and arrays in the
MATLAB workspace, returned as a cell array of character vectors.
Limitations
• Differentiation functions, such as divergence, curl, jacobian, and laplacian, currently do
not accept symbolic matrix variables and symbolic matrix functions as input. To evaluate
differentiation with respect to vectors and matrices, use the diff function instead.
• To show all the functions in Symbolic Math Toolbox that accept symbolic matrix variables and
symbolic matrix functions as input, use the command methods symmatrix and methods
symfunmatrix.
Tips
• You can create multiple symbolic objects in one call. For example, syms f(x) g(t) y creates
two symbolic functions (f and g) and three symbolic scalar variables (x, t, and y).
• syms is a shortcut for sym, symfun, symmatrix, and symfunmatrix. This shortcut lets you
create several symbolic objects with one function call. For example, you can use sym and create
each symbolic scalar variable separately. However, when you create variables using sym, any
existing assumptions on the created variables are retained. You can also use symfun to create
symbolic functions.
• In functions and scripts, do not use syms to create symbolic scalar variables with the same names
as MATLAB functions. For these names, MATLAB does not create symbolic scalar variables, but
keeps the names assigned to the MATLAB functions. If you want to create a symbolic scalar
variable with the same name as a MATLAB function inside a function or a script, use sym instead.
For example, use alpha = sym('alpha').
• Avoid using syms within functions or parallel for loops because it generates variables without
direct output assignment and modifies the global state of the workspace. Using syms within
functions can create side effects and other unexpected behaviors. Instead, use sym with left-side
output assignment, such as t = sym('t'). For more details, see “Choose syms or sym Function”
on page 2-4.
• These variable names are invalid with syms: integer, real, rational, positive, and clear.
To create symbolic scalar variables with these names, use sym. For example, real =
sym('real').
• clear x does not clear the symbolic object of its assumptions, such as real, positive, or any
assumptions set by assume, sym, or syms. To remove assumptions, use one of these options:
7-1520
syms
• When you replace one or more elements of a numeric vector or matrix with a symbolic number,
MATLAB converts that number to a double-precision number.
A = eye(3);
A(1,1) = sym(pi)
A =
3.1416 0 0
0 1.0000 0
0 0 1.0000
You cannot replace elements of a numeric vector or matrix with a symbolic scalar variable,
expression, or function because these elements cannot be converted to double-precision numbers.
For example, syms a; A(1,1) = a throws an error.
• When evaluating a symbolic matrix function, you must substitute values that have the same size as
the defined input arguments. For example, see “Create Function of Vector and Scalar” on page 7-
1516. For comparison, this example returns an error:
syms X [2 2] matrix
syms f(X) [1 1] matrix keepargs
f(ones(4))
Version History
Introduced before R2006a
R2022b: Return the names of all symbolic objects in the MATLAB workspace
Behavior changed in R2022b
You can list the names of all symbolic objects in the MATLAB workspace using syms and return them
as a cell array using S = syms.
Starting in R2022b, the returned names of all symbolic objects include all symbolic matrix variables
and matrix functions of type symmatrix and symfunmatrix in the MATLAB workspace. In previous
releases, syms only returns the names of all symbolic scalar variables, functions, and arrays of type
sym and symfun.
Symbolic matrix functions allow you to represent parameter-dependent functions that operate on
scalars, vectors, and matrices in compact matrix notation. Using them, you can represent matrix- and
vector-based expressions in Symbolic Math Toolbox and perform linear algebra calculations. For
example, see “Create Function of Vector and Scalar” on page 7-1516.
R2021b: syms clears assumptions on symbolic variables when creating symbolic functions
Behavior changed in R2021b
7-1521
7 Functions
When creating symbolic functions with symbolic variables as input arguments, syms clears all
previously set assumptions on the symbolic variables. For example:
syms x y z real
syms t real positive
assumptions
ans =
syms f(x,y,z,t)
assumptions
ans =
To set assumptions on the input arguments of symbolic functions, create the symbolic functions first,
and then set the assumptions on the symbolic variables (or recreate the symbolic variables with set
assumptions). For example:
syms g(x,y,z,t)
assume(x,'real')
assume(t,'positive')
assumptions
ans =
syms y z real
assumptions
ans =
Symbolic matrix variables offer a concise typeset display and show mathematical formulas with more
clarity. Using them, you can represent matrix- and vector-based expressions in Symbolic Math
Toolbox and perform linear algebra calculations. For example, see “Commutation Relation of
Symbolic Matrix Variables” on page 7-1515 and “Find Hessian Matrix” on page 7-1516.
syms now clears any assumptions on the symbolic scalar variables that it creates. For example,
syms x real
assume(x <= 5);
assumptions(x)
7-1522
syms
ans =
x <= 5
syms x
assumptions(x)
ans =
To retain existing assumptions on a cleared variable, recreate it using sym instead of syms. For
example,
syms x real
assume(x <= 5);
clear x
x = sym('x');
assumptions(x)
ans =
x <= 5
The syntaxes syms x clear and the equivalent syms('x','clear') now issue a warning that
they will be removed in a future release.
In previous releases, both syntaxes cleared all assumptions applied to x. To update your code, call
syms and specify the symbolic scalar variables whose assumptions you want to clear. For example,
syms x clears all assumptions applied to x.
See Also
assume | assumeAlso | assumptions | displayFormula | isvarname | sym | symfun |
symmatrix | symfunmatrix | symvar
Topics
“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
“Use Symbolic Objects to Represent Mathematical Objects” on page 1-20
“Choose syms or sym Function” on page 2-4
“Use Assumptions on Symbolic Variables” on page 1-41
“Add Subscripts, Superscripts, and Accents to Symbolic Variables in the Live Editor” on page 2-14
“Change Output Format of Symbolic and Variable-Precision Arithmetic” on page 2-8
7-1523
7 Functions
symsum
Symbolic sum of series
Syntax
F = symsum(f,k,a,b)
F = symsum(f,k)
Description
F = symsum(f,k,a,b) returns the symbolic definite sum on page 7-1527 of the series f with
respect to the summation index k from the lower bound a to the upper bound b. If you do not specify
k, symsum uses the variable determined by symvar as the summation index. If f is a constant, then
the default variable is x.
F = symsum(f,k) returns the indefinite sum on page 7-1527 (antidifference) of the series f with
respect to the summation index k. The f argument defines the series such that the indefinite sum F
satisfies the relation F(k+1) - F(k) = f(k). If you do not specify k, symsum uses the variable
determined by symvar as the summation index. If f is a constant, then the default variable is x.
Examples
syms k n
F1 = symsum(k,k,1,n)
F1 =
n n+1
2
2 2 2 2
Find the sum of the square numbers 1 + 2 + 3 + . . . + n2 = ∑nk = 1 k .
syms k n
F2 = symsum(k^2,k,1,n)
F2 =
n 2n+1 n+1
6
3 3 3 3
Find the sum of the cubic numbers 1 + 2 + 3 + . . . + n3 = ∑nk = 1 k .
syms k n
F3 = symsum(k^3,k,1,n)
F3 =
7-1524
symsum
2
n2 n + 1
4
10
2
F1 = ∑ k
k=0
∞ 1
F2 = ∑ 2
k=1k
∞ xk
F3 = ∑ k!
k=1
syms k x
F1 = symsum(k^2,k,0,10)
F1 = 385
F2 = symsum(1/k^2,k,1,Inf)
F2 =
π2
6
F3 = symsum(x^k/factorial(k),k,1,Inf)
F3 = ex − 1
F1 = symsum(k^2,k,[0 10])
F1 = 385
F2 = symsum(1/k^2,k,[1;Inf])
F2 =
π2
6
F3 = symsum(x^k/factorial(k),k,[1 Inf])
F3 = ex − 1
7-1525
7 Functions
F1 = ∑k
k
F2 = ∑ 2k
k
1
F3 = ∑ 2
k k
syms k
F1 = symsum(k,k)
F1 =
2
k k
−
2 2
F2 = symsum(2^k,k)
k
F2 = 2
F3 = symsum(1/k^2,k)
F3 =
−ψ′ k if 0 < k
ψ′ 1 − k if k ≤ 0
If you know that the coefficient ak is a function of some integer variable k, use the symsum function.
For example, find the sum F x = ∑8k = 1 kxk.
syms x k
F(x) = symsum(k*x^k,k,1,8)
F(x) = 8 x8 + 7 x7 + 6 x6 + 5 x5 + 4 x4 + 3 x3 + 2 x2 + x
F(2)
ans = 3586
Alternatively, if you know that the coefficients ak are a vector of values, you can use the sum function.
For example, the coefficients are a1, …, a8 = 1, …, 8. Declare the term xk as a vector by using
subs(x^k,k,1:8).
a = 1:8;
G(x) = sum(a.*subs(x^k,k,1:8))
G(x) = 8 x8 + 7 x7 + 6 x6 + 5 x5 + 4 x4 + 3 x3 + 2 x2 + x
7-1526
symsum
G(2)
ans = 3586
Input Arguments
f — Expression defining terms of series
symbolic expression | symbolic function | symbolic vector | symbolic matrix | symbolic number
Expression defining terms of series, specified as a symbolic expression, function, vector, matrix, or
symbolic number.
k — Summation index
symbolic variable
Summation index, specified as a symbolic variable. If you do not specify this variable, symsum uses
the default variable determined by symvar(expr,1). If f is a constant, then the default variable is
x.
Lower bound of the summation index, specified as a number, symbolic number, variable, expression,
or function (including expressions and functions with infinities).
Upper bound of the summation index, specified as a number, symbolic number, variable, expression,
or function (including expressions and functions with infinities).
More About
Definite Sum
b
∑ fk = fa + fa + 1 + … + fb .
k=a
Indefinite Sum
F(x) = ∑f x,
x
such that
F x+1 −F x = f x .
7-1527
7 Functions
Version History
Introduced before R2006a
See Also
cumsum | int | sum | symprod | syms | symvar | rewrite
Topics
“Symbolic Summation” on page 3-200
7-1528
symtrue
symtrue
Symbolic logical constant true
Syntax
symtrue
T = symtrue(n)
T = symtrue(sz)
T = symtrue(sz1,...,szN)
Description
symtrue is the symbolic logical constant for the true condition.
T = symtrue(sz) returns an array of symbolic logical symtrues where the size vector, sz, defines
size(T). For example, symtrue([2 3]) returns a 2-by-3 array of symbolic logical symtrues.
Examples
eq = 4 < x2
Simplify the condition represented by the symbolic inequality eq. The simplify function returns the
symbolic logical constant symtrue since the condition always holds for the assumption x > 2.
T = simplify(eq)
T = symtrue
ans =
'sym'
7-1529
7 Functions
You can also use isAlways to check if the inequality holds under the assumption being made. In this
example, isAlways returns logical 1 (true).
TF = isAlways(eq)
TF = logical
1
T = symtrue(3)
T =
symtrue symtrue symtrue
symtrue symtrue symtrue
symtrue symtrue symtrue
class(T)
ans =
'sym'
T = symtrue(3,2,2)
T(:,:,1) =
symtrue symtrue
symtrue symtrue
symtrue symtrue
T(:,:,2) =
symtrue symtrue
symtrue symtrue
symtrue symtrue
Alternatively, you can use a size vector to specify the size of the array.
T = symtrue([3,2,2])
T(:,:,1) =
symtrue symtrue
symtrue symtrue
symtrue symtrue
T(:,:,2) =
symtrue symtrue
symtrue symtrue
symtrue symtrue
7-1530
symtrue
Create a truth table for the and operation applied to the two symbolic logical constants, symtrue and
symfalse.
A = [symtrue symfalse]
A = symtrue symfalse
B = [symtrue; symfalse]
B =
symtrue
symfalse
TF = and(A,B)
TF =
symtrue symfalse
symfalse symfalse
Combine symbolic logical constants with logical operators and, not, or, and xor (or their shortcuts).
TF = xor(symtrue,or(symfalse,symfalse))
TF = symtrue
TF = symtrue
T1 = logical(symtrue)
T1 = logical
1
Convert the symbolic logical constant symtrue to numeric values in double precision and variable
precision.
T2 = double(symtrue)
T2 = 1
T3 = vpa(symtrue)
7-1531
7 Functions
T3 = 1.0
whos
T1 1x1 1 logical
T2 1x1 8 double
T3 1x1 8 sym
Input Arguments
n — Size of square matrix
scalar
Size of square matrix, specified as an integer. n sets the output array size to n-by-n. For example,
symtrue(3) returns a 3-by-3 array of symbolic logical symtrues.
sz — Size vector
row vector of integers
Size vector, specified as a row vector of integers. For example, symtrue([2 3]) returns a 2-by-3
array of symbolic logical symtrues.
Size inputs, specified by a comma-separated list of integers. For example, symtrue(2,3) returns a
2-by-3 array of symbolic logical symtrues.
Output Arguments
T — Symbolic logical constant for true condition
scalar | vector | matrix | N-D array
7-1532
symtrue
Symbolic logical constant for true condition, returned as a scalar, vector, matrix, or N-D array.
Data Types: sym
Tips
• The command sym(true) returns a symbolic number 1, and sym(symtrue) returns symtrue.
• When you combine two arrays of symbolic logical constants with logical operations using and, or,
or xor function, the arrays must either be the same size or have sizes that are compatible. For
more information on the required input sizes for basic array operations, see “Compatible Array
Sizes for Basic Operations”.
Version History
Introduced in R2020a
See Also
isAlways | symfalse | and | or | not | xor
7-1533
7 Functions
symType
Determine type of symbolic object
Syntax
s = symType(symObj)
Description
s = symType(symObj) returns the type of a symbolic object. For example, symType(sym('x'))
returns "variable".
Examples
Symbolic Number
a = sym('3/9');
s = symType(a)
s =
"rational"
Now construct a symbolic array by including symbolic numbers in the array elements. Determine the
symbolic type of each array element.
s = 1x5 string
"integer" "rational" "vpareal" "complex" "constant"
syms f(x)
Determine the type of the function. Because f(x) is an unassigned symbolic function, it has the
symbolic type "symfun".
s = symType(f)
s =
"symfun"
7-1534
symType
f(x) = x^2;
s = symType(f)
s =
"expression"
f(x) = x;
s = symType(f)
s =
"variable"
s = symType(diff(f))
s =
"integer"
Determine the type of various symbolic objects when solving for inequalities.
syms y(x)
y(x) = 100 - 5*x^2
y(x) = 100 − 5 x2
Set two inequalities to the quadratic function. Check the symbolic type of each inequality.
s = 1x2 string
"equation" "equation"
Solve the inequalities using solve. Return the solutions by setting 'ReturnConditions' to true.
s = symType(sols)
s =
"logicalexpression"
7-1535
7 Functions
Input Arguments
symObj — Symbolic objects
symbolic numbers | symbolic variables | symbolic expressions | symbolic functions | symbolic units
Symbolic objects, specified as symbolic numbers, symbolic variables, symbolic expressions, symbolic
functions, or symbolic units.
Output Arguments
s — Symbolic types
string array
Symbolic types, returned as a string array. This table shows output values for various symbolic
objects.
Version History
Introduced in R2019a
See Also
sym | syms | symfun | isSymType | symFunType | hasSymType
7-1536
symunit
symunit
Units of measurement
Syntax
u = symunit
Description
u = symunit returns the units collection. Then, specify any unit by using u.unit. For example,
specify 3 meters as 3*u.m. Common alternate names for units are supported, such as u.meter and
u.metre. Plurals are not supported. For details about the list of available units, see “Units and Unit
Systems List” on page 2-60.
Examples
Before specifying units, load units by using symunit. Then, specify a unit by using dot notation.
Specify a length of 3 meters. You can also use aliases u.meter or u.metre.
u = symunit;
length = 3*u.m
length = 3 m
Specify the acceleration due to gravity of 9.81 meters per second squared. Because units are
symbolic expressions, numeric inputs are converted to exact symbolic values. Here, 9.81 is
converted to 981/100.
g = 9.81*u.m/u.s^2
g =
981 m
100 s2
For more information about the differences between symbolic and numeric arithmetic, see “Choose
Numeric or Symbolic Arithmetic” on page 2-32.
Units behave like symbolic expressions when you perform standard operations on them. For numeric
operations, separate the value from the units, substitute for any symbolic parameters, and convert
the result to double.
7-1537
7 Functions
u = symunit;
d = 5*u.km;
t = 2*u.hr;
s = d/t
s =
5 km
2 h
The value 5/2 is symbolic. You may prefer double output, or require double output for a MATLAB®
function that does not accept symbolic values. Convert to double by separating the numeric value
using separateUnits and then using double.
[sNum,sUnits] = separateUnits(s)
sNum =
5
2
sUnits =
km
h
sNum = double(sNum)
sNum = 2.5000
For the complete units workflow, see “Units of Measurement Tutorial” on page 2-47.
Use your preferred unit by rewriting units using unitConvert. Also, instead of specifying specific
units, you can specify that the output should be in terms of SI units.
Calculate the force required to accelerate 2 kg by 5 m/s². The expression is not automatically
rewritten in terms of Newtons.
u = symunit;
m = 2*u.kg;
a = 5*u.m/u.s^2;
F = m*a
F =
kg m
10
s2
F = unitConvert(F,u.N)
F = 10 N
Convert 5 cm to inches.
length = 5*u.cm;
length = unitConvert(length,u.in)
7-1538
symunit
length =
250
in
127
length = unitConvert(length,'SI')
length =
1
m
20
Simplify expressions containing units of the same dimension by using simplify. Units are not
automatically simplified or checked for consistency unless you call simplify.
u = symunit;
expr = 300*u.cm + 40*u.inch + 2*u.m
expr = 300 cm + 40 in + 2 m
expr = simplify(expr)
expr =
752
m
125
simplify automatically chooses the unit to return. To convert to a specific unit, use unitConvert.
expr = unitConvert(expr,u.ft)
expr =
7520
ft
381
To represent absolute temperatures, use degrees kelvin so that you do not have to distinguish an
absolute temperature from a temperature difference.
Convert 23 degrees Celsius to K, 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
7-1539
7 Functions
absK = unitConvert(T,u.K,'Temperature','absolute')
absK =
5923
K
20
Limitations
• When using symbolic units, the value of 0 times a symbolic unit is returned as a dimensionless 0.
To preserve the unit when multiplying a symbolic unit by 0, use a cell array to represent the zero
measurement.
For example, you can define 0 degrees Celsius as a cell array and convert it to degrees Fahrenheit
by using the unitConvert function.
u = symunit;
tC = {0,u.Celsius};
tF = unitConvert(tC,u.Fahrenheit,'Temperature','Absolute')
tF =
32*[Fahrenheit]
Tips
• You can use tab expansion to find names of units. Type u., press Tab, and continue typing.
• 1 represents a dimensionless unit. Hence, isUnit(sym(1)) returns logical 1 (true).
• Certain non-linear units, such as decibels, are not implemented because arithmetic operations are
not possible for these units.
• Instead of using dot notation to specify units, you can alternatively use string input for
symunit(unit). For example, symunit("m") specifies the unit meter.
Version History
Introduced in R2017a
For more information, see “Units and Unit Systems List” on page 2-60.
7-1540
symunit
• G_0 – conductance
• e_0 – vacuum electric permittivity or electric constant
• F_c – Faraday constant
• mu_0 – vacuum magnetic permeability
• sigma – Stefan-Boltzmann constant
• phi_0 – magnetic flux quantum
• R_c – molar gas constant
• m_p – proton mass
• R_inf – Rydberg constant
For more information, see “Units and Unit Systems List” on page 2-60.
See Also
checkUnits | isUnit | newUnit | separateUnits | symunit2str | unitConversionFactor |
unitConvert | unitInfo
Topics
“Units of Measurement Tutorial” on page 2-47
“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)
7-1541
7 Functions
symunit2str
Convert unit to character vector
Syntax
symunit2str(unit)
symunit2str(unit,toolbox)
Description
symunit2str(unit) converts the symbolic unit unit to a character vector.
Examples
Convert Unit to Character Vector
unitStr =
'km'
Convert symbolic units to character vectors representing units in other toolboxes by specifying the
toolbox name as the second argument to symunit2str. The allowed toolboxes are 'Aerospace',
'SimBiology', 'Simscape', or 'Simulink'. The unit must exist in the target toolbox to be valid.
unit =
'km/h-s'
unit =
'molecule/second'
7-1542
symunit2str
unit =
'gee/km'
unit = symunit2str(u.rad/u.s,'Simulink')
unit =
'rad/s'
Input Arguments
unit — Symbolic unit to convert
symbolic unit
Version History
Introduced in R2017a
See Also
checkUnits | findUnits | isUnit | newUnit | separateUnits | symunit | str2symunit |
unitConversionFactor
Topics
“Units of Measurement Tutorial” on page 2-47
“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)
7-1543
7 Functions
symvar
Find symbolic variables in symbolic input
Syntax
symvar(s)
symvar(s,n)
Description
symvar(s) returns a vector of all symbolic variables in s. The variables are in alphabetical order
with uppercase letters preceding lowercase letters.
symvar(s,n) chooses the n symbolic variables in s that are alphabetically closest to x and returns
them in alphabetical order. If s is a symbolic function, symvar(s,n) returns the input arguments of
s before other variables in s.
Examples
Find all symbolic variables in an expression. symvar returns the variables in alphabetical order.
syms wa wb yx ya
sum = wa + wb + ya + yx;
symvar(sum)
ans =
[ wa, wb, ya, yx]
Find the first three symbolic variables in an expression. symvar chooses variables that are
alphabetically closest to x and returns them in alphabetical order.
syms a x y b
f = a*x^2/(sin(3*y-b));
symvar(f,3)
ans =
[ b, x, y]
Find all symbolic variables in this function. For a symbolic function, symvar returns the function
inputs before other variables.
syms x y a b
f(x,y) = a*x^2/(sin(3*y-b));
symvar(f)
ans =
[ x, y, a, b]
7-1544
symvar
g(x,y) = 1;
symvar(g)
ans =
[ x, y]
symvar(f,3)
ans =
[ x, y, b]
When a symbolic function, such as solve, needs to find the default independent variable in symbolic,
the function uses symvar. Find the default independent variable for symbolic expressions.
syms v z
g = v + z;
symvar(g,1)
ans =
z
ans =
aaa
syms X1 x2 xa xb
g = X1 + x2 + xa + xb;
symvar(g,1)
ans =
x2
When differentiating, integrating, substituting, or solving equations, MATLAB uses the variable
returned by symvar(s,1) as a default variable. For a symbolic expression or matrix, symvar(s,1)
returns the variable closest to x. For a function, symvar(s,1) returns the first input argument of s.
Input Arguments
s — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
n — Number of variables
integer
7-1545
7 Functions
Number of variables, specified as an integer or Inf. If n exceeds the number of variables in s, then
symvar returns the number of variables in s.
Tips
• symvar treats the constants pi, i, and j as variables.
• If there are no symbolic variables in s, symvar returns the empty vector.
Algorithms
When symvar sorts the symbolic variables alphabetically, all uppercase letters have precedence over
lowercase: 0 1 ... 9 A B ... Z a b ... z.
Version History
Introduced in R2008b
See Also
argnames | sym | symfun | syms
Topics
“Find Symbolic Variables in Expressions, Functions, and Matrices” on page 2-2
7-1546
symWriteSSC
symWriteSSC
Create new Simscape component
Syntax
symWriteSSC(newComponentName,templateComponentName,eqns)
symWriteSSC(newComponentName,templateComponentName,eqns,Name,Value)
Description
symWriteSSC(newComponentName,templateComponentName,eqns) creates a new Simscape
component newComponentName using an existing component templateComponentName as a
template and adding eqns. Thus, the new component has both the existing equations taken from the
template component and the added equations.
symWriteSSC(newComponentName,templateComponentName,eqns,Name,Value) uses
additional options specified by one or more Name,Value pair arguments.
Examples
Create a new Simscape component by using an existing component as a template and adding an
equation.
Suppose you have the Simscape component spring.ssc in your current folder.
type('spring.ssc');
parameters
spr_rate = { 10, 'N*m/rad' };
end
variables
phi = { value = { 0, 'rad'}, priority = priority.high };
end
function setup
if spr_rate <= 0
pm_error('simscape:GreaterThanZero','Spring rate' )
end
end
equations
w == phi.der;
t == spr_rate*phi;
end
end
7-1547
7 Functions
Create symbolic variables with names of the parameters and variables of the component you are
going to use when creating new equations. Also create a symbolic variable, u, to denote the energy of
the rotational spring.
eq = u == spr_rate*phi^2/2;
symWriteSSC('myRotationalSpring.ssc','spring.ssc',eq)
type('myRotationalSpring.ssc');
component myRotationalSpring
parameters
spr_rate = { 10, 'N*m/rad' };
end
variables
phi = { value = { 0, 'rad'}, priority = priority.high };
end
function setup
if spr_rate <= 0
pm_error('simscape:GreaterThanZero','Spring rate' )
end
end
equations
w == phi.der;
t == spr_rate*phi;
u == phi^2*spr_rate*(1.0/2.0);
end
end
Create a Simscape component with the title and descriptive text different from those of the template
component.
Suppose you have the Simscape component spring.ssc in your current folder. This component does
not have any title or descriptive text.
type('spring.ssc');
7-1548
symWriteSSC
parameters
spr_rate = { 10, 'N*m/rad' };
end
variables
phi = { value = { 0, 'rad'}, priority = priority.high };
end
function setup
if spr_rate <= 0
pm_error('simscape:GreaterThanZero','Spring rate' )
end
end
equations
w == phi.der;
t == spr_rate*phi;
end
end
Create symbolic variables with names of the parameters and variables of the component you are
going to use when creating new equations. Also create a symbolic variable, u, to denote the energy of
the rotational spring.
eq = u == spr_rate*phi^2/2;
Create the new component, myRotationalSpring.ssc, based on the spring.ssc component. Add
the equation eq, the title “Rotational Spring”, and a few lines of descriptive text to the new
component.
symWriteSSC('myRotationalSpring.ssc','spring.ssc',eq,...
'H1Header','% Rotational Spring',...
'HelpText',{'% The block represents an ideal mechanical rotational linear spring.',...
'% Connections R and C are mechanical rotational conserving ports.'...
'% The block positive direction is from port R to port C. This means'...
'% that the torque is positive if it acts in the direction from R to C.'})
type('myRotationalSpring.ssc');
component myRotationalSpring
% Rotational Spring
% The block represents an ideal mechanical rotational linear spring.
% Connections R and C are mechanical rotational conserving ports.
% The block positive direction is from port R to port C. This means
% that the torque is positive if it acts in the direction from R to C.
7-1549
7 Functions
parameters
spr_rate = { 10, 'N*m/rad' };
end
variables
phi = { value = { 0, 'rad'}, priority = priority.high };
end
function setup
if spr_rate <= 0
pm_error('simscape:GreaterThanZero','Spring rate' )
end
end
equations
w == phi.der;
t == spr_rate*phi;
u == phi^2*spr_rate*(1.0/2.0);
end
end
Input Arguments
newComponentName — Name of Simscape component to create
file name enclosed in single quotes
Name of Simscape component to create, specified as a file name enclosed in single quotes. File must
have the extension .ssc. If you do not provide file extension, symWriteSSC assumes it to be .ssc. If
you do not specify the absolute path, symWriteSSC creates the new component in the current folder.
Example: 'MyNewComponent.ssc'
Name of template Simscape component, specified as a file name enclosed in single quotes. File must
have the extension .ssc. If you do not provide the file extension, symWriteSSC assumes it to
be .ssc. The component must be on the MATLAB path or in the current folder.
Example: 'TemplateComponent.ssc'
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
7-1550
symWriteSSC
H1Header — Title
row vector of characters
Title specified as a row vector of characters (type char) starting with %. If the first character is not
%, then symWriteSSC adds %.
If the template component has a title and you use H1Header, the new component will have the title
specified by H1Header. If the template component has a title and you call symWriteSSC without
H1Header, the new component will have the same title as the template component.
Example: 'H1Header','% New title'
Descriptive text, specified as a cell array of row vectors of characters. Each row vector must start
with %. If the first character is not %, then symWriteSSC adds %.
If the template component has descriptive text and you use HelpText, the new component will have
only the text specified by HelpText. In this case, symWriteSSC does not copy the descriptive text of
the template component to the new component. If the template component has a title and you call
symWriteSSC without HelpText, the new component will have the same descriptive text as the
template component.
Example: 'HelpText',{'% Description of the','% new component'}
Version History
Introduced in R2016a
See Also
symReadSSCParameters | symReadSSCVariables | simscapeEquation
7-1551
7 Functions
tan
Symbolic tangent function
Syntax
tan(X)
Description
tan(X) returns the tangent function on page 7-1554 of X.
Examples
Tangent Function for Numeric and Symbolic Arguments
Compute the tangent function for these numbers. Because these numbers are not symbolic objects,
tan returns floating-point results.
A =
2.1850 0.0000 0.5774 -1.2540 -225.9508
Compute the tangent function for the numbers converted to symbolic objects. For many symbolic
(exact) numbers, tan returns unresolved symbolic calls.
symA =
[ -tan(2), 0, 3^(1/2)/3, -tan((2*pi)/7), tan(11)]
vpa(symA)
ans =
[ 2.1850398632615189916433061023137,...
0,...
0.57735026918962576450914878050196,...
-1.2539603376627038375709109783365,...
-225.95084645419514202579548320345]
syms x
fplot(tan(x),[-pi pi])
grid on
7-1552
tan
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing tan.
syms x
diff(tan(x), x)
diff(tan(x), x, x)
ans =
tan(x)^2 + 1
ans =
2*tan(x)*(tan(x)^2 + 1)
int(tan(x), x)
ans =
-log(cos(x))
taylor(tan(x), x)
7-1553
7 Functions
ans =
(2*x^5)/15 + x^3/3 + x
Rewrite the tangent function in terms of the sine and cosine functions:
rewrite(tan(x), 'sincos')
ans =
sin(x)/cos(x)
rewrite(tan(x), 'exp')
ans =
-(exp(x*2i)*1i - 1i)/(exp(x*2i) + 1)
tan numerically evaluates these units automatically: radian, degree, arcmin, arcsec, and
revolution.
u = symunit;
syms x
f = [x*u.degree 2*u.radian];
tanf = tan(f)
tanf =
[ tan((pi*x)/180), tan(2)]
You can calculate tanf by substituting for x using subs and then using double or vpa.
Input Arguments
X — Input
symbolic number | symbolic scalar variable | symbolic matrix variable | symbolic expression |
symbolic function | symbolic matrix function | symbolic vector | symbolic matrix
Input, specified as a symbolic number, scalar variable, matrix variable, expression, function, matrix
function, or as a vector or matrix of symbolic numbers, scalar variables, expressions, or functions.
More About
Tangent Function
opposite side a
tan(α) = = .
adjacent side b
7-1554
tan
eiα − e−iα
tan α = .
i eiα + e−iα
Version History
Introduced before R2006a
See Also
acos | asin | atan | acsc | asec | acot | sin | cos | csc | sec | cot
7-1555
7 Functions
tanh
Symbolic hyperbolic tangent function
Syntax
tanh(X)
Description
tanh(X) returns the hyperbolic tangent function of X.
Examples
Hyperbolic Tangent Function for Numeric and Symbolic Arguments
Compute the hyperbolic tangent function for these numbers. Because these numbers are not symbolic
objects, tanh returns floating-point results.
A = tanh([-2, -pi*i, pi*i/6, pi*i/3, 5*pi*i/7])
A =
-0.9640 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.5774i...
0.0000 + 1.7321i 0.0000 - 1.2540i
Compute the hyperbolic tangent function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, tanh returns unresolved symbolic calls.
symA = tanh(sym([-2, -pi*i, pi*i/6, pi*i/3, 5*pi*i/7]))
symA =
[ -tanh(2), 0, (3^(1/2)*1i)/3, 3^(1/2)*1i, -tanh((pi*2i)/7)]
ans =
[ -0.96402758007581688394641372410092,...
0,...
0.57735026918962576450914878050196i,...
1.7320508075688772935274463415059i,...
-1.2539603376627038375709109783365i]
7-1556
tanh
Many functions, such as diff, int, taylor, and rewrite, can handle expressions containing tanh.
Find the first and second derivatives of the hyperbolic tangent function:
syms x
diff(tanh(x), x)
diff(tanh(x), x, x)
ans =
1 - tanh(x)^2
ans =
2*tanh(x)*(tanh(x)^2 - 1)
int(tanh(x), x)
ans =
log(cosh(x))
taylor(tanh(x), x)
7-1557
7 Functions
ans =
(2*x^5)/15 - x^3/3 + x
rewrite(tanh(x), 'exp')
ans =
(exp(2*x) - 1)/(exp(2*x) + 1)
Input Arguments
X — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix
Version History
Introduced before R2006a
See Also
acosh | asinh | atanh | acoth | asech | acsch | sinh | cosh | coth | sech | csch
7-1558
taylor
taylor
Taylor series
Syntax
T = taylor(f,var)
T = taylor(f,var,a)
T = taylor( ___ ,Name,Value)
Description
T = taylor(f,var) approximates f with the Taylor series expansion on page 7-1565 of f up to the
fifth order at the point var = 0. If you do not specify var, then taylor uses the default variable
determined by symvar(f,1).
T = taylor(f,var,a) approximates f with the Taylor series expansion of f at the point var = a.
T = taylor( ___ ,Name,Value) specifies options using one or more name-value arguments in
addition to any of the input argument combinations in previous syntaxes. For example, you can
specify the expansion point, truncation order, or order mode of the Taylor series expansion.
Examples
Find the Maclaurin series expansions of the exponential, sine, and cosine functions up to the fifth
order.
syms x
T1 = taylor(exp(x))
T1 =
x5 x4 x3 x2
+ + + +x+1
120 24 6 2
T2 = taylor(sin(x))
T2 =
x5 x3
− +x
120 6
T3 = taylor(cos(x))
T3 =
x4 x2
− +1
24 2
You can use the sympref function to modify the output order of symbolic polynomials. Redisplay the
polynomials in ascending order.
7-1559
7 Functions
sympref('PolynomialDisplayStyle','ascend');
T1
T1 =
x2 x3 x4 x5
1+x+ + + +
2 6 24 120
T2
T2 =
x3 x5
x− +
6 120
T3
T3 =
x2 x4
1− +
2 24
The display format you set using sympref persists through your current and future MATLAB®
sessions. Restore the default value by specifying the 'default' option.
sympref('default');
Find the Taylor series expansions at x = 1 for these functions. The default expansion point is 0. To
specify a different expansion point, use ExpansionPoint.
syms x
T = taylor(log(x),x,'ExpansionPoint',1)
T =
2 3 4 5
x−1 x−1 x−1 x−1
x− + − + −1
2 3 4 5
T =
2 3 5
π x x−1 x−1 x−1 1
− + − + +
4 2 4 12 40 2
Find the Maclaurin series expansion for f = sin(x)/x. The default truncation order is 6. The Taylor
series approximation of this expression does not have a fifth-degree term, so taylor approximates
this expression with the fourth-degree polynomial.
syms x
f = sin(x)/x;
T6 = taylor(f,x);
7-1560
taylor
Use Order to control the truncation order. For example, approximate the same expression up to the
orders 7 and 9.
T8 = taylor(f,x,'Order',8);
T10 = taylor(f,x,'Order',10);
Plot the original expression f and its approximations T6, T8, and T10. Note how the accuracy of the
approximation depends on the truncation order.
fplot([T6 T8 T10 f])
xlim([-4 4])
grid on
legend('approximation of sin(x)/x with error O(x^6)', ...
'approximation of sin(x)/x with error O(x^8)', ...
'approximation of sin(x)/x with error O(x^{10})', ...
'sin(x)/x','Location','Best')
title('Taylor Series Expansion')
Find the Taylor series expansion of this expression. By default, taylor uses an absolute order, which
is the truncation order of the computed series.
syms x
T = taylor(1/exp(x) - exp(x) + 2*x,x,'Order',5)
7-1561
7 Functions
T =
x3
−
3
Find the Taylor series expansion with a relative truncation order by using OrderMode. For some
expressions, a relative truncation order provides more accurate approximations.
T =
x7 x5 x3
− − −
2520 60 3
Find the Maclaurin series expansion of this multivariate expression. If you do not specify the vector of
variables, taylor treats f as a function of one independent variable.
syms x y z
f = sin(x) + cos(y) + exp(z);
T = taylor(f)
T =
x5 x3
− + x + cos y + ez
120 6
Find the multivariate Maclaurin series expansion by specifying the vector of variables.
syms x y z
f = sin(x) + cos(y) + exp(z);
T = taylor(f,[x,y,z])
T =
x5 x3 y4 y2 z5 z4 z3 z2
− +x+ − + + + + +z+2
120 6 24 2 120 24 6 2
You can use the sympref function to modify the output order of a symbolic polynomial. Redisplay the
polynomial in ascending order.
sympref('PolynomialDisplayStyle','ascend');
T
T =
z2 z3 z4 z5 y2 y4 x3 x5
2+z+ + + + − + +x− +
2 6 24 120 2 24 6 120
The display format you set using sympref persists through your current and future MATLAB
sessions. Restore the default value by specifying the 'default' option.
sympref('default');
7-1562
taylor
Find the multivariate Taylor series expansion by specifying both the vector of variables and the vector
of values defining the expansion point.
syms x y
f = y*exp(x - 1) - x*log(y);
T = taylor(f,[x y],[1 1],'Order',3)
T =
2 2
x−1 y−1
x+ +
2 2
If you specify the expansion point as a scalar a, taylor transforms that scalar into a vector of the
same length as the vector of variables. All elements of the expansion vector equal a.
T = taylor(f,[x y],1,'Order',3)
T =
2 2
x−1 y−1
x+ +
2 2
Find the error estimate when approximating a function f x = log x + 1 using the Taylor series
expansion. Here, consider the Taylor approximation up to the 7th order (with the truncation order
n = 8) at the expansion point a = 0.
The error or remainder in the Taylor approximation is given by the Lagrange form:
n
f c n
Rn − 1 x = x−a .
n!
The upper bound of the error estimate can be calculated by finding a positive real number M such
n
that f c ≤ M for all c between a and x.
Find the Taylor series expansion of the function f x = log x + 1 up to the 7th order by specifying
Order as 8.
syms x
f = log(x+1)
f = log x + 1
T = taylor(f,'Order',8)
T =
x7 x6 x5 x4 x3 x2
− + − + − +x
7 6 5 4 3 2
8
To estimate the error in the Taylor approximation, first compute the term f c .
syms c
fn(c) = subs(diff(f,8),x,c)
7-1563
7 Functions
fn(c) =
5040
− 8
c+1
For positive values of x, the upper bound of the error estimate can be calculated by using the relation
8
f c ≤ 5040 (because c must be a positive value between 0 and a positive x). Next, find the upper
bound of the error estimate Rupper(x) by using the Lagrange from R7 x and the relation
8
f c ≤ 5040.
Rupper(x) = 5040*x^8/factorial(8)
Rupper(x) =
x8
8
Evaluate the Taylor series expansion at the point x = 0 . 5. Find the upper bound of the error estimate
in the Taylor approximation.
Teval = subs(T,x,0.5)
Teval =
909
2240
Rmax = double(Rupper(0.5))
Rmax = 4.8828e-04
For comparison, evaluate the exact function at x = 0 . 5 and find the remainder in the Taylor
approximation.
feval = subs(f,x,0.5)
feval =
3
log
2
R = double(abs(feval-Teval))
R = 3.3846e-04
Input Arguments
f — Input to approximate
symbolic expression | symbolic function | symbolic vector | symbolic matrix | symbolic
multidimensional array
Input to approximate, specified as a symbolic expression or function. It also can be a vector, matrix,
or multidimensional array of symbolic expressions or functions.
Expansion variable, specified as a symbolic variable. If you do not specify var, then taylor uses the
default variable determined by symvar(f,1).
7-1564
taylor
a — Expansion point
0 (default) | number | symbolic number | symbolic variable | symbolic function | symbolic expression
Expansion point, specified as a number, or a symbolic number, variable, function, or expression. The
expansion point cannot depend on the expansion variable. You also can specify the expansion point as
a name-value argument. If you specify the expansion point both ways, then the name-value argument
takes precedence.
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: taylor(log(x),x,'ExpansionPoint',1,'Order',9)
Expansion point, specified as a number, or a symbolic number, variable, function, or expression. The
expansion point cannot depend on the expansion variable. You can also specify the expansion point
using the input argument a. If you specify the expansion point both ways, then the name-value
argument takes precedence.
Truncation order of the Taylor series expansion, specified as a positive integer or a symbolic positive
integer. taylor computes the Taylor series approximation with the order n - 1. The truncation
order n is the exponent in the O-term: O(varn).
Order mode indicator, specified as 'absolute' or 'relative'. This indicator specifies whether to
use absolute or relative order when computing the Taylor polynomial approximation.
Absolute order is the truncation order of the computed series. Relative order n means that the
exponents of var in the computed series range from the leading order m to the highest exponent m +
n - 1. Here m + n is the exponent of var in the O-term: O(varm + n).
More About
Taylor Series Expansion
A Taylor series expansion represents an analytic function f(x) as an infinite sum of terms around the
expansion point x = a:
∞ (m)
f′ a f″ a 2 f (a) m
f (x) = f a +
1!
x−a +
2!
x−a +…= ∑ m!
⋅ x−a
m=0
A Taylor series expansion requires a function to have derivatives up to an infinite order around the
expansion point.
7-1565
7 Functions
Tips
• If you use both the third argument a and ExpansionPoint to specify the expansion point, then
the value specified by ExpansionPoint prevails.
• If var is a vector, then the expansion point a must be a scalar or a vector of the same length as
var. If var is a vector and a is a scalar, then a is expanded into a vector of the same length as var
with all elements equal to a.
• If the expansion point is infinity or negative infinity, then taylor computes the Laurent series
expansion, which is a power series in 1/var.
• You can use the sympref function to modify the output order of symbolic polynomials.
• If taylor cannot find the Taylor series expansion, then use series to find the more general
Puiseux series expansion.
Version History
Introduced before R2006a
See Also
pade | series | symvar | coeffs | polynomialDegree | sympref
Topics
“Taylor Series” on page 3-182
7-1566
taylortool
taylortool
Taylor series calculator
Syntax
taylortool
taylortool(f)
t = taylortool( ___ )
Description
taylortool initiates a GUI that computes the Taylor series expansion. The GUI that graphs a
function against the Nth partial sum of its Taylor series about a base point x = a. The default
function, value of N, base point, and interval of computation for taylortool are f = x*cos(x), N
= 7, a = 0, and [-2*pi,2*pi], respectively.
taylortool(f) initiates the GUI that computes the Taylor series expansion of the given expression
f.
t = taylortool( ___ ) returns the Figure object. Use t to query or modify properties of the
figure after it is created.
Examples
Open a GUI that computes the Taylor series expansion. By default, the GUI shows the Taylor series
expansion of the function f x = x cos x . The blue solid line shows the function f x and the red
dashed line shows its Taylor approximation.
taylortool
7-1567
7 Functions
Next, find the Taylor series expansion of the function cos x . Assign an output variable to
taylortool to return the Figure object.
syms x
t = taylortool(cos(x))
7-1568
taylortool
t =
Figure (Taylor Tool) with properties:
Number: []
Name: 'Taylor Tool'
Color: [0.9400 0.9400 0.9400]
Position: [112.5000 75 390 315]
Units: 'points'
close(t)
Input Arguments
f — Input to approximate
symbolic expression | symbolic function
7-1569
7 Functions
Version History
Introduced before R2006a
See Also
funtool | rsums | taylor
Topics
“Taylor Series” on page 3-182
7-1570
texlabel
texlabel
TeX representation of symbolic expression
Syntax
texlabel(expr)
texlabel(expr,'literal')
Description
texlabel(expr) converts the symbolic expression expr into the TeX equivalent for use in character
vectors. texlabel converts Greek variable names, such as delta, into Greek letters. Annotation
functions, such as title, xlabel, and text can use the TeX character vector as input. To obtain the
LaTeX representation, use latex.
Examples
Generate TeX Character Vector
Use texlabel to generate TeX character vectors for these symbolic expressions.
ans =
'{sin}({x}) + {x}^{3}'
ans =
'{3} {exp}(- ({y} + {1})^{2} - {x}^{2}) ({x} - {1})^{2}'
ans =
'{\lambda_{12}}^{{3}/{2}}/{\pi} - {\delta}^{{2}/{3}} {\pi}'
To make texlabel interpret Greek variable names literally, include the argument 'literal'.
texlabel(lambda12,'literal')
ans =
'{lambda12}'
Plot y = x^2 using fplot. Show the plotted expression y by using texlabel to generate a TeX
character vector that text inserts into the figure.
syms x
y = x^2;
7-1571
7 Functions
fplot(y)
ylabel = texlabel(y);
text(1, 15, ['y = ' ylabel]);
Input Arguments
expr — Expression to be converted
symbolic expression
Version History
Introduced before R2006a
See Also
latex | text | title | xlabel | ylabel | zlabel
7-1572
times, .*
times, .*
Symbolic array multiplication
Syntax
A.*B
times(A,B)
Description
A.*B performs element-wise multiplication of A and B.
Examples
Multiply Matrix by Scalar
A = sym('a', [2 3])
A =
[ a1_1, a1_2, a1_3]
[ a2_1, a2_2, a2_3]
Multiply the matrix by the symbolic expression sin(b). Multiplying a matrix by a scalar means
multiplying each element of the matrix by that scalar.
syms b
A.*sin(b)
ans =
[ a1_1*sin(b), a1_2*sin(b), a1_3*sin(b)]
[ a2_1*sin(b), a2_2*sin(b), a2_3*sin(b)]
H = sym(hilb(3))
d = diag(sym([1 2 3]))
H =
[ 1, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
d =
[ 1, 0, 0]
[ 0, 2, 0]
[ 0, 0, 3]
7-1573
7 Functions
Multiply the matrices by using the element-wise multiplication operator .*. This operator multiplies
each element of the first matrix by the corresponding element of the second matrix. The dimensions
of the matrices must be the same.
H.*d
ans =
[ 1, 0, 0]
[ 0, 2/3, 0]
[ 0, 0, 3/5]
syms f(x)
f(x) = x^2;
f1 = (x^2 + 5*x + 6).*f
f1(x) =
x^2*(x^2 + 5*x + 6)
Input Arguments
A — Input
number | symbolic number | symbolic scalar variable | symbolic matrix variable | symbolic function |
symbolic matrix function | symbolic expression | symbolic vector | symbolic matrix | symbolic array
Input, specified as a number, or a symbolic number, scalar variable, matrix variable, function, matrix
function, expression, or vector, matrix, or array of symbolic scalar variables. Inputs A and B must be
the same size unless one is a scalar. A scalar value expands into an array of the same size as the other
input.
B — Input
number | symbolic number | symbolic scalar variable | symbolic matrix variable | symbolic function |
symbolic matrix function | symbolic expression | symbolic vector | symbolic matrix | symbolic array
Input, specified as a number, or a symbolic number, scalar variable, matrix variable, function, matrix
function, expression, or vector, matrix, or array of symbolic scalar variables. Inputs A and B must be
the same size unless one is a scalar. A scalar value expands into an array of the same size as the other
input.
Version History
Introduced before R2006a
7-1574
times, .*
See Also
ctranspose | ldivide | minus | mldivide | mpower | mrdivide | mtimes | plus | power |
rdivide | transpose
7-1575
7 Functions
toeplitz
Symbolic Toeplitz matrix
Syntax
toeplitz(c,r)
toeplitz(r)
Description
toeplitz(c,r) generates a nonsymmetric Toeplitz matrix on page 7-1578 having c as its first
column and r as its first row. If the first elements of c and r are different, toeplitz issues a warning
and uses the first element of the column.
toeplitz(r) generates a symmetric Toeplitz matrix if r is real. If r is complex, but its first element
is real, then this syntax generates the Hermitian Toeplitz matrix formed from r. If the first element of
r is not real, then the resulting matrix is Hermitian off the main diagonal, meaning that
Tij = conjugate(Tji) for i ≠ j.
Examples
Generate Toeplitz Matrix
Generate the Toeplitz matrix from these vectors. Because these vectors are not symbolic objects, you
get floating-point results.
c = [1 2 3 4 5 6];
r = [1 3/2 3 7/2 5];
toeplitz(c,r)
ans =
1.0000 1.5000 3.0000 3.5000 5.0000
2.0000 1.0000 1.5000 3.0000 3.5000
3.0000 2.0000 1.0000 1.5000 3.0000
4.0000 3.0000 2.0000 1.0000 1.5000
5.0000 4.0000 3.0000 2.0000 1.0000
6.0000 5.0000 4.0000 3.0000 2.0000
Now, convert these vectors to a symbolic object, and generate the Toeplitz matrix:
c = sym([1 2 3 4 5 6]);
r = sym([1 3/2 3 7/2 5]);
toeplitz(c,r)
ans =
[ 1, 3/2, 3, 7/2, 5]
[ 2, 1, 3/2, 3, 7/2]
[ 3, 2, 1, 3/2, 3]
[ 4, 3, 2, 1, 3/2]
[ 5, 4, 3, 2, 1]
[ 6, 5, 4, 3, 2]
7-1576
toeplitz
syms a b c d
T = toeplitz([a b c d])
T =
[ a, b, c, d]
[ conj(b), a, b, c]
[ conj(c), conj(b), a, b]
[ conj(d), conj(c), conj(b), a]
If you specify that all elements are real, then the resulting Toeplitz matrix is symmetric:
syms a b c d real
T = toeplitz([a b c d])
T =
[ a, b, c, d]
[ b, a, b, c]
[ c, b, a, b]
[ d, c, b, a]
For further computations, clear the assumptions by recreating the variables using syms:
syms a b c d
T = toeplitz(sym([1, 2, i]))
T =
[ 1, 2, 1i]
[ 2, 1, 2]
[ -1i, 2, 1]
If the first element of the vector is real, then the resulting Toeplitz matrix is Hermitian:
isAlways(T == T')
ans =
3×3 logical array
1 1 1
1 1 1
1 1 1
If the first element is not real, then the resulting Toeplitz matrix is Hermitian off the main diagonal:
T = toeplitz(sym([i, 2, 1]))
T =
[ 1i, 2, 1]
[ 2, 1i, 2]
[ 1, 2, 1i]
isAlways(T == T')
7-1577
7 Functions
ans =
3×3 logical array
0 1 1
1 0 1
1 1 0
Generate a Toeplitz matrix using these vectors to specify the first column and the first row. Because
the first elements of these vectors are different, toeplitz issues a warning and uses the first
element of the column:
syms a b c
toeplitz([a b c], [1 b/2 a/2])
Warning: First element of given column does not match first element of given row.
Column wins diagonal conflict.
ans =
[ a, b/2, a/2]
[ b, a, b/2]
[ c, b, a]
Input Arguments
c — First column of Toeplitz matrix
vector | symbolic vector
More About
Toeplitz Matrix
A Toeplitz matrix is a matrix that has constant values along each descending diagonal from left to
right. For example, matrix T is a symmetric Toeplitz matrix:
t0 t1 t2 tk
t−1 t0 t1 ⋯
t−2 t−1 t0
T= ⋮ ⋱ ⋮
t0 t1 t2
⋯ t−1 t0 t1
t−k t−2 t−1 t0
Tips
• Calling toeplitz for numeric arguments that are not symbolic objects invokes the MATLAB
toeplitz function.
7-1578
toeplitz
Version History
Introduced in R2013a
See Also
toeplitz
7-1579
7 Functions
transpose, .'
Symbolic matrix transpose
Syntax
A.'
transpose(A)
Description
A.' computes the nonconjugate transpose on page 7-1581 of A.
Examples
Transpose of Real Matrix
syms x y real
A = [x x x; y y y]
A =
[ x, x, x]
[ y, y, y]
A.'
ans =
[ x, y]
[ x, y]
[ x, y]
If all elements of a matrix represent real numbers, then its complex conjugate transform equals its
nonconjugate transform.
isAlways(A' == A.')
ans =
3×2 logical array
1 1
1 1
1 1
syms x y real
A = [x + y*i x - y*i; y + x*i y - x*i]
7-1580
transpose, .'
A =
[ x + y*1i, x - y*1i]
[ y + x*1i, y - x*1i]
Find the nonconjugate transpose of this matrix. The nonconjugate transpose operator, A.', performs
a transpose without conjugation. That is, it does not change the sign of the imaginary parts of the
elements.
A.'
ans =
[ x + y*1i, y + x*1i]
[ x - y*1i, y - x*1i]
For a matrix of complex numbers with nonzero imaginary parts, the nonconjugate transform is not
equal to the complex conjugate transform.
isAlways(A.' == A','Unknown','false')
ans =
2×2 logical array
0 0
0 0
Input Arguments
A — Input
number | symbolic number | symbolic scalar variable | symbolic matrix variable | symbolic function |
symbolic matrix function | symbolic expression | symbolic vector | symbolic matrix | symbolic array
Input, specified as a number, or a symbolic number, scalar variable, matrix variable, function, matrix
function, expression, or vector, matrix, or array of symbolic scalar variables.
More About
Nonconjugate Transpose
The nonconjugate transpose of a matrix interchanges the row and column index for each element,
reflecting the elements across the main diagonal. The diagonal elements themselves remain
unchanged. This operation does not affect the sign of the imaginary parts of complex elements.
For example, if B = A.' and A(3,2) is 1+1i, then the element B(2,3) is 1+1i.
Version History
Introduced before R2006a
7-1581
7 Functions
See Also
ctranspose | ldivide | minus | mldivide | mpower | mrdivide | mtimes | plus | power |
rdivide | times
7-1582
triangularPulse
triangularPulse
Triangular pulse function
Syntax
triangularPulse(a,b,c,x)
triangularPulse(a,c,x)
triangularPulse(x)
Description
triangularPulse(a,b,c,x) returns the “Triangular Pulse Function” on page 7-1587.
Examples
syms x
fplot(triangularPulse(x), [-2 2])
7-1583
7 Functions
Compute the triangular pulse function for these numbers. Because these numbers are not symbolic
objects, you get floating-point results.
[triangularPulse(-2, 0, 2, -3)
triangularPulse(-2, 0, 2, -1/2)
triangularPulse(-2, 0, 2, 0)
triangularPulse(-2, 0, 2, 3/2)
triangularPulse(-2, 0, 2, 3)]]
ans =
0
0.7500
1.0000
0.2500
0
Compute the same values symbolically by converting the numbers to symbolic objects.
[triangularPulse(sym(-2), 0, 2, -3)
triangularPulse(-2, 0, 2, sym(-1/2))
triangularPulse(-2, sym(0), 2, 0)
triangularPulse(-2, 0, 2, sym(3/2))
triangularPulse(-2, 0, sym(2), 3)]
7-1584
triangularPulse
ans =
0
3/4
1
1/4
0
syms x
triangularPulse(x)
ans =
triangularPulse(-1, 0, 1, x)
syms a c x
triangularPulse(a, c, x)
ans =
triangularPulse(a, a/2 + c/2, c, x)
Depending on the relation between inputs, the triangularPulse has special values.
syms a b c x
assume(a < x < b)
triangularPulse(a, b, c, x)
ans =
(a - x)/(a - b)
For further computations, remove the assumption by recreating the variables using syms:
syms a b x
ans =
-(c - x)/(b - c)
7-1585
7 Functions
syms b c x
syms a b c x
assume(b < c)
triangularPulse(b, b, c, x)
ans =
-((c - x)*rectangularPulse(b, c, x))/(b - c)
assume(a < b)
triangularPulse(a, b, b, x)
ans =
((a - x)*rectangularPulse(a, b, x))/(a - b)
syms a b c
Input Arguments
a — Input
-1 (default) | number | symbolic scalar
Input, specified as a number or a symbolic scalar. This argument specifies the rising edge of the
triangular pulse function.
b — Input
number | symbolic scalar
Input, specified as a number or a symbolic scalar. This argument specifies the peak of the triangular
pulse function. If you specify a and c, then (a + c)/2. Otherwise, 0.
c — Input
1 (default) | number | symbolic scalar
Input, specified as a number or a symbolic scalar. This argument specifies the falling edge of the
triangular pulse function.
x — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
7-1586
triangularPulse
More About
Triangular Pulse Function
If a < x < b, then the triangular pulse function equals (x - a)/(b - a).
If b < x < c, then the triangular pulse function equals (c - x)/(c - b).
The triangular pulse function is also called the triangle function, hat function, tent function, or
sawtooth function.
Tips
• If a, b, and c are variables or expressions with variables, triangularPulse assumes that a <=
b <= c. If a, b, and c are numerical values that do not satisfy this condition, triangularPulse
throws an error.
• If a = b = c, triangularPulse returns 0.
• If a = b or b = c, the triangular function can be expressed in terms of the rectangular function.
Version History
Introduced in R2012b
See Also
dirac | heaviside | rectangularPulse
7-1587
7 Functions
tril
Return lower triangular part of symbolic matrix
Syntax
tril(A)
tril(A,k)
Description
tril(A) returns a triangular matrix that retains the lower part of the matrix A. The upper triangle of
the resulting matrix is padded with zeros.
tril(A,k) returns a matrix that retains the elements of A on and below the k-th diagonal. The
elements above the k-th diagonal equal to zero. The values k = 0, k > 0, and k < 0 correspond to
the main, superdiagonals, and subdiagonals, respectively.
Examples
Lower Triangular Part of Symbolic Matrix
Display the matrix retaining only the lower triangle of the original symbolic matrix:
syms a b c
A = [a b c; 1 2 3; a + 1 b + 2 c + 3];
tril(A)
ans =
[ a, 0, 0]
[ 1, 2, 0]
[ a + 1, b + 2, c + 3]
Display the matrix that retains the elements of the original symbolic matrix on and below the first
superdiagonal:
syms a b c
A = [a b c; 1 2 3; a + 1 b + 2 c + 3];
tril(A, 1)
ans =
[ a, b, 0]
[ 1, 2, 3]
[ a + 1, b + 2, c + 3]
Display the matrix that retains the elements of the original symbolic matrix on and below the first
subdiagonal:
7-1588
tril
syms a b c
A = [a b c; 1 2 3; a + 1 b + 2 c + 3];
tril(A, -1)
ans =
[ 0, 0, 0]
[ 1, 0, 0]
[ a + 1, b + 2, 0]
Input Arguments
A — Input
matrix | symbolic matrix
k — Diagonal
number | symbolic number
Version History
Introduced before R2006a
See Also
diag | triu
7-1589
7 Functions
triu
Return upper triangular part of symbolic matrix
Syntax
triu(A)
triu(A,k)
Description
triu(A) returns a triangular matrix that retains the upper part of the matrix A. The lower triangle of
the resulting matrix is padded with zeros.
triu(A,k) returns a matrix that retains the elements of A on and above the k-th diagonal. The
elements below the k-th diagonal equal to zero. The values k = 0, k > 0, and k < 0 correspond to
the main, superdiagonals, and subdiagonals, respectively.
Examples
Upper Triangular Part of Symbolic Matrix
Display the matrix retaining only the upper triangle of the original symbolic matrix:
syms a b c
A = [a b c; 1 2 3; a + 1 b + 2 c + 3];
triu(A)
ans =
[ a, b, c]
[ 0, 2, 3]
[ 0, 0, c + 3]
Display the matrix that retains the elements of the original symbolic matrix on and above the first
superdiagonal:
syms a b c
A = [a b c; 1 2 3; a + 1 b + 2 c + 3];
triu(A, 1)
ans =
[ 0, b, c]
[ 0, 0, 3]
[ 0, 0, 0]
Display the matrix that retains the elements of the original symbolic matrix on and above the first
subdiagonal:
7-1590
triu
syms a b c
A = [a b c; 1 2 3; a + 1 b + 2 c + 3];
triu(A, -1)
ans =
[ a, b, c]
[ 1, 2, 3]
[ 0, b + 2, c + 3]
Input Arguments
A — Input
matrix | symbolic matrix
k — Diagonal
number | symbolic number
Version History
Introduced before R2006a
See Also
diag | tril
7-1591
7 Functions
unitConversionFactor
Conversion factor between units
Syntax
C = unitConversionFactor(unit1,unit2)
C = unitConversionFactor(unit1,unit2,'Force',true)
Description
C = unitConversionFactor(unit1,unit2) returns the conversion factor C between units
unit1 and unit2 so that unit1 = C*unit2.
Examples
u = symunit;
inch2cm = unitConversionFactor(u.inch,u.cm)
inch2cm =
127/50
inch2cm = double(inch2cm)
inch2cm =
2.5400
Find the conversion factor between Newtons and kg m/s2. The conversion factor is 1.
convFactor =
1
Convert between units quickly by using text input as a shortcut. Convert 3 inch to cm.
3*double(unitConversionFactor("inch","cm"))
7-1592
unitConversionFactor
ans =
7.6200
Convert between dimensionally incompatible units by specifying the argument 'Force' as true.
Convert between Watts and Joules. unitConversionFactor returns the factor 1/[s] because 1 W
= 1 J/s.
u = symunit;
convFactor = unitConversionFactor(u.W, u.J, 'Force', true)
convFactor =
1/[s]
unitConversionFactor(u.W, u.J)
Input Arguments
unit — Units
character vector | string | symbolic units
Version History
Introduced in R2017a
See Also
checkUnits | findUnits | isUnit | newUnit | separateUnits | symunit | str2symunit |
symunit2str
Topics
“Units of Measurement Tutorial” on page 2-47
“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)
7-1593
7 Functions
unitConvert
Convert units to other units of measurement
Syntax
unitConvert(expr,units)
unitConvert(expr,unitSystem)
unitConvert(expr,unitSystem,'Derived')
Description
unitConvert(expr,units) converts symbolic units in the expression expr to the units units,
where units can be a compound unit or a vector of units.
Examples
u = symunit;
length = unitConvert(5*u.cm,u.in)
length =
250
in
127
Convert length to floating point by separating the value using separateUnits and converting
using double. Alternatively, keep the units by using vpa instead of double.
double(separateUnits(length))
ans = 1.9685
7-1594
unitConvert
vpa(length)
ans = 1.968503937007874015748031496063 in
For more complex workflows, see “Unit Conversions and Unit Systems” on page 2-53.
Calculate the force required to accelerate 2 kg by 5 m/s². The result is not automatically in newtons.
m = 2*u.kg;
a = 5*u.m/u.s^2;
F = m*a
F =
kg m
10
s2
F = 10 N
Convert 5 km per hour to meters per second by specifying meters per second as a compound unit.
u = symunit;
unitConvert(5*u.km/u.hr,u.m/u.s)
ans =
25 m
18 s
Specify multiple units for conversion by specifying the second argument as a vector of units. This
syntax lets you specify units for every dimension to get the desired units.
ans =
25000 cm
3 min
Instead of converting to specific units, you can convert to units of a unit system, such as SI, CGS, or
US.
Convert 5 meters to the 'US' unit system. unitConvert returns the result in feet.
7-1595
7 Functions
u = symunit;
unitConvert(5*u.m,'US')
ans =
6250
ft
381
Convert 10 newtons to derived units in CGS by using the input 'Derived'. The result is in dynes.
Repeat the conversion without the input 'Derived' to get a result in base units.
F = 10*u.N;
cgsDerived = unitConvert(F,'CGS','Derived')
cgsBase = unitConvert(F,'CGS')
cgsBase =
cm g
1000000
s2
To represent absolute temperatures, use degrees kelvin so that you do not have to distinguish an
absolute temperature from a temperature difference.
Convert 23 degrees Celsius to K, 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
Input Arguments
expr — Input
symbolic number | symbolic variable | symbolic expression | symbolic function | symbolic vector |
symbolic matrix | symbolic multidimensional array
7-1596
unitConvert
Units to convert input to, specified as a symbolic unit or vector of symbolic units.
Unit system to convert input to, specified as a string or character vector. By default, the SI, CGS, and
US unit systems are available. You can also define custom unit systems. See “Unit Conversions and
Unit Systems” on page 2-53.
Limitations
• When using symbolic units, the value of 0 times a symbolic unit is returned as a dimensionless 0.
To preserve the unit when multiplying a symbolic unit by 0, use a cell array to represent the zero
measurement.
For example, you can define 0 degrees Celsius as a cell array and convert it to degrees Fahrenheit
by using the unitConvert function.
u = symunit;
tC = {0,u.Celsius};
tF = unitConvert(tC,u.Fahrenheit,'Temperature','Absolute')
tF =
32*[Fahrenheit]
Version History
Introduced in R2018b
See Also
baseUnits | derivedUnits | newUnit | newUnitSystem | symunit
Topics
“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)
7-1597
7 Functions
unitInfo
Information on units of measurement
Syntax
unitInfo(unit)
unitInfo(dim)
unitInfo
A = unitInfo( ___ )
Description
unitInfo(unit) returns information for the symbolic unit unit.
A = unitInfo( ___ ) returns the output in A using any of the input arguments in the previous
syntaxes. Dimensions are returned as strings, and units are returned as symbolic units.
Examples
Find information on unit u.Wb where u = symunit. The unitInfo function specifies that Wb is the
SI unit of magnetic flux.
u = symunit;
unitInfo(u.Wb)
unitInfo('MagneticFlux')
abWb - abweber
Mx - maxwell
phi_0 - magnetic flux quantum
statWb - statweber
Wb - weber ['SI']
7-1598
unitInfo
unitInfo(u.m/u.s^2)
unitInfo
"AbsorbedDose"
"AbsorbedDoseOrDoseEquivalent"
"AbsorbedDoseRate"
"Acceleration"
...
...
"Length"
"Luminance"
"LuminousEfficacy"
...
...
"Torque"
"Velocity"
"Volume"
u = symunit;
dimC = unitInfo(u.C)
dimC =
"ElectricCharge"
unitsEC = unitInfo(dimC)
unitsEC =
[abC]
[C]
[e]
[Fr]
[statC]
unitInfo(unitsEC(3))
7-1599
7 Functions
Store [e]. Then, find the number of electrons in a coulomb of electric charge.
electronCharge = unitsEC(3);
numElectrons = simplify(u.C/electronCharge)
numElectrons =
5000000000000000000000000000/801088317
Show that approximately 6.24 x 1018 electrons are in a coulomb by converting the high-precision
symbolic result to double.
numElectrons = double(numElectrons)
numElectrons =
6.2415e+18
Input Arguments
unit — Unit name
symbolic unit | character vector | string
Unit name, specified as a symbolic unit, character vector, or string. If unit is not a known base or
derived unit in “Units and Unit Systems List” on page 2-60, then A = unitInfo(unit) returns an
empty string "".
Example: unitInfo(u.m) where u = symunit
dim — Dimension
character vector | string
Version History
Introduced in R2017b
See Also
rewrite | simplify | symunit
Topics
“Units of Measurement Tutorial” on page 2-47
“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)
7-1600
unitSystems
unitSystems
List available unit systems
Syntax
unitSystems
Description
unitSystems returns a row vector of available unit systems.
Examples
Get available unit systems by using unitSystems. Add a custom unit system and check that
unitSystems lists it as available.
unitSystems
ans =
1×6 string array
"CGS" "EMU" "ESU" "GU" "SI" "US"
Add a custom unit system that modifies the SI base units. For details, see newUnitSystem and “Unit
Conversions and Unit Systems” on page 2-53.
u = symunit;
SIUnits = baseUnits('SI');
newUnits = subs(SIUnits,[u.m u.s],[u.km u.hr]);
newUnitSystem('SI_km_hr',newUnits)
ans =
"SI_km_hr"
unitSystems
ans =
1×7 string array
"CGS" "EMU" "ESU" "GU" "SI" "SI_km_hr" "US"
After calculations, remove the new unit system and check that it is unavailable.
7-1601
7 Functions
removeUnitSystem('SI_km_hr');
unitSystems
ans =
1×6 string array
"CGS" "EMU" "ESU" "GU" "SI" "US"
Version History
Introduced in R2017b
See Also
baseUnits | derivedUnits | newUnitSystem | removeUnitSystem | rewrite | symunit
Topics
“Units of Measurement Tutorial” on page 2-47
“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)
7-1602
vectorPotential
vectorPotential
Vector potential of vector field
Syntax
vectorPotential(V,X)
vectorPotential(V)
Description
vectorPotential(V,X) computes the vector potential of the vector field on page 7-1604 V with
respect to the vector X in Cartesian coordinates. The vector field V and the vector X are both three-
dimensional.
vectorPotential(V) returns the vector potential V with respect to a vector constructed from the
first three symbolic variables found in V by symvar.
Examples
Compute Vector Potential of Field
Compute the vector potential of this row vector field with respect to the vector [x, y, z]:
syms x y z
vectorPotential([x^2*y, -1/2*y^2*x, -x*y*z], [x y z])
ans =
-(x*y^2*z)/2
-x^2*y*z
0
Compute the vector potential of this column vector field with respect to the vector [x, y, z]:
syms x y z
f(x,y,z) = 2*y^3 - 4*x*y;
g(x,y,z) = 2*y^2 - 16*z^2+18;
h(x,y,z) = -32*x^2 - 16*x*y^2;
A = vectorPotential([f; g; h], [x y z])
A(x, y, z) =
z*(2*y^2 + 18) - (16*z^3)/3 + (16*x*y*(y^2 + 6*x))/3
2*y*z*(- y^2 + 2*x)
0
To check whether the vector potential exists for a particular vector field, compute the divergence of
that vector field:
syms x y z
V = [x^2 2*y z];
divergence(V, [x y z])
7-1603
7 Functions
ans =
2*x + 3
If the divergence is not equal to 0, the vector potential does not exist. In this case,
vectorPotential returns the vector with all three components equal to NaN:
vectorPotential(V, [x y z])
ans =
NaN
NaN
NaN
Input Arguments
V — Vector field
3-D symbolic vector of symbolic expressions or functions (default)
X — Input
vector of three symbolic variables
Input, specified as a vector of three symbolic variables with respect to which you compute the vector
potential.
More About
Vector Potential of a Vector Field
V = ∇ × A = curl(A)
Tips
• The vector potential exists if and only if the divergence of a vector field V with respect to X equals
0. If vectorPotential cannot verify that V has a vector potential, it returns the vector with all
three components equal to NaN.
Version History
Introduced in R2012a
See Also
curl | diff | divergence | gradient | jacobian | hessian | laplacian | potential
7-1604
vertcat
vertcat
Concatenate symbolic arrays vertically
Syntax
vertcat(A1,...,AN)
[A1;...;AN]
Description
vertcat(A1,...,AN) vertically concatenates the symbolic arrays A1,...,AN. For vectors and
matrices, all inputs must have the same number of columns. For multidimensional arrays, vertcat
concatenates inputs along the first dimension. The remaining dimensions must match.
Examples
Concatenate Two Symbolic Vectors Vertically
ans =
[ a1, a2, a3, a4]
[ b1, b2, b3, b4]
ans =
[ a1, a2, a3, a4]
[ b1, b2, b3, b4]
ans =
[ c11, c12, c13]
[ c21, c22, c23]
[ a1, a2, a3]
[ b11, b12, b13]
[ b21, b22, b23]
7-1605
7 Functions
A = [2 4; 1 7; 3 3];
A(:,:,2) = [8 9; 4 5; 6 2];
A = sym(A)
B = [8 3; 0 2];
B(:,:,2) = [6 2; 3 3];
B = sym(B)
A(:,:,1) =
[ 2, 4]
[ 1, 7]
[ 3, 3]
A(:,:,2) =
[ 8, 9]
[ 4, 5]
[ 6, 2]
B(:,:,1) =
[ 8, 3]
[ 0, 2]
B(:,:,2) =
[ 6, 2]
[ 3, 3]
vertcat(A,B)
ans(:,:,1) =
[ 2, 4]
[ 1, 7]
[ 3, 3]
[ 8, 3]
[ 0, 2]
ans(:,:,2) =
[ 8, 9]
[ 4, 5]
[ 6, 2]
[ 6, 2]
[ 3, 3]
Input Arguments
A1,...,AN — Input arrays
symbolic scalar variable | symbolic matrix variable | symbolic matrix function | symbolic vector |
symbolic matrix | symbolic multidimensional array
Input arrays, specified as symbolic scalar variables, matrix variables, matrix functions, or vectors,
matrices, or multidimensional arrays of symbolic scalar variables.
7-1606
vertcat
Version History
Introduced before R2006a
See Also
cat | horzcat
7-1607
7 Functions
vpa
Variable-precision arithmetic (arbitrary-precision arithmetic)
Syntax
xVpa = vpa(x)
xVpa = vpa(x,d)
Description
xVpa = vpa(x) uses variable-precision arithmetic (arbitrary-precision floating-point numbers) to
evaluate each element of the symbolic input x to at least d significant digits, where d is the value of
the digits function. The default value of digits is 32.
xVpa = vpa(x,d) uses at least d significant digits instead of the value of digits.
Examples
Evaluate symbolic inputs with variable-precision floating-point arithmetic. By default, vpa calculates
values to 32 significant digits.
p = sym(pi);
pVpa = vpa(p)
pVpa = 3.1415926535897932384626433832795
syms x
a = sym(1/3);
f = a*sin(2*p*x);
fVpa = vpa(f)
V = [x/p a^3];
VVpa = vpa(V)
MVpa =
0 0.80901699437494742410229341718282
e3.1415926535897932384626433832795 x 0.87356852683023186835397746476334 x
7-1608
vpa
By default, vpa evaluates inputs to 32 significant digits. You can change the number of significant
digits by using the digits function.
Approximate the expression 100001/10001 with seven significant digits using digits. Save the old
value of digits returned by digits(7). The vpa function returns only five significant digits, which
can mean the remaining digits are zeros.
digitsOld = digits(7);
y = sym(100001)/10001;
yVpa = vpa(y)
yVpa = 9.9991
Check if the remaining digits are zeros by using a higher precision value of 25. The result shows that
the remaining digits are in fact zeros that are part of a repeating decimal.
digits(25)
yVpa = vpa(y)
yVpa = 9.999100089991000899910009
Alternatively, to override digits for a single vpa call, change the precision by specifying the second
argument.
pVpa = vpa(pi,100)
pVpa = 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342
digits(digitsOld)
While symbolic results are exact, they might not be in a convenient form. You can use vpa to
numerically approximate exact symbolic results.
Solve a high-degree polynomial for its roots using solve. The solve function cannot symbolically
solve the high-degree polynomial and represents the roots using root.
syms x
y = solve(x^4 - x + 1, x)
y =
root z4 − z + 1, z, 1
root z4 − z + 1, z, 2
root z4 − z + 1, z, 3
root z4 − z + 1, z, 4
7-1609
7 Functions
yVpa =
0.72713608449119683997667565867496 − 0.43001428832971577641651985839602 i
0.72713608449119683997667565867496 + 0.43001428832971577641651985839602 i
−0.72713608449119683997667565867496 − 0.93409928946052943963903028710582 i
−0.72713608449119683997667565867496 + 0.93409928946052943963903028710582 i
The value of the digits function specifies the minimum number of significant digits used. Internally,
vpa can use more digits than digits specifies. These additional digits are called guard digits
because they guard against round-off errors in subsequent calculations.
a = 0.3333
Approximate the result a using 20 digits. The result shows that the toolbox internally used more than
four digits when computing a. The last digits in the result are incorrect because of the round-off
error.
aVpa = vpa(a,20)
aVpa = 0.33333333333303016843
Evaluate 1/10 with the default 32-digit precision and then with the 10-digit precision.
a = vpa(1/10,32)
a = 0.1
b = vpa(1/10,10)
b = 0.1
roundoff = 0.000000000000000000086736173798840354720600815844403
The difference is not equal to zero because b was calculated with only 10 digits of precision and
contains a larger round-off error than a. When you find a - b, vpa approximates b with 32 digits.
Demonstrate this behavior.
7-1610
vpa
roundoff = a - vpa(b,32)
roundoff = 0.000000000000000000086736173798840354720600815844403
Unlike exact symbolic values, double-precision values inherently contain round-off errors. When you
call vpa on a double-precision input, vpa cannot restore the lost precision, even though it returns
more digits than the double-precision value. However, vpa can recognize and restore the precision of
1
p pπ p 2 q q
expressions of the form q , q , q
, 2 , and 10 , where p and q are modest-sized integers.
First, demonstrate that vpa cannot restore precision for a double-precision input. Call vpa on a
double-precision result and the same symbolic result.
dp = log(3);
s = log(sym(3));
dpVpa = vpa(dp)
dpVpa = 1.0986122886681095600636126619065
sVpa = vpa(s)
sVpa = 1.0986122886681096913952452369225
d = sVpa - dpVpa
d = 0.00000000000000013133163257501600766255995767652
As expected, the double-precision result differs from the exact result at the 16th decimal place.
1
p pπ p q q
Demonstrate that vpa restores precision for expressions of the form q , q , q 2 , 2 , and 10 , where p
and q are modest-sized integers, by finding the difference between the vpa call on the double-
precision result and on the exact symbolic result. The differences are 0 . 0 showing that vpa restores
lost precision for the double-precision input.
d = vpa(1/3) - vpa(1/sym(3))
d = 0.0
d = vpa(pi) - vpa(sym(pi))
d = 0.0
d = vpa(1/sqrt(2)) - vpa(1/sqrt(sym(2)))
d = 0.0
d = vpa(2^66) - vpa(2^sym(66))
d = 0.0
d = vpa(10^25) - vpa(10^sym(25))
d = 0.0
7-1611
7 Functions
π
π 2
Create a symbolic expression S that represents sin X , where X is a 2-by-1 symbolic matrix
π π
2 3
variable.
syms X [2 1] matrix
S = sin(hilb(2)*pi*X)
S =
sin Σ1 X
where
π
π
2
Σ1 =
π π
2 3
SVpa =
sin 3.1415926535897932384626433832795 X1 + 1.5707963267948966192313216916398 X2
sin 1.5707963267948966192313216916398 X1 + 1.0471975511965977461542144610932 X2
Input Arguments
x — Input to evaluate
number | vector | matrix | multidimensional array | symbolic number | symbolic vector | symbolic
matrix | symbolic multidimensional array | symbolic expression | symbolic function | symbolic
character vector | symbolic matrix variable
Number of significant digits, specified as a positive integer scalar. d must be greater than 1 and less
29
than 2 + 1.
Tips
• vpa does not convert fractions in the exponent to floating point. For example, vpa(a^sym(2/5))
returns a^(2/5).
• vpa uses more digits than the number of digits specified by digits. These extra digits guard
against round-off errors in subsequent calculations and are called guard digits.
7-1612
vpa
• When you call vpa on a numeric input, such as 1/3, 2^(-5), or sin(pi/4), the numeric
expression is evaluated to a double-precision number that contains round-off errors. Then, vpa is
called on that double-precision number. For accurate results, convert numeric expressions to
symbolic expressions with sym. For example, to approximate exp(1), use vpa(exp(sym(1))).
• If the second argument d is not an integer, vpa rounds it to the nearest integer with round.
• vpa restores precision for numeric inputs that match the forms p/q, pπ/q, (p/q)1/2, 2q, and 10q,
where p and q are modest-sized integers.
• Variable-precision arithmetic is different from IEEE Floating-Point Standard 754 in these ways:
Version History
Introduced before R2006a
You can evaluate a symbolic matrix variable of type symmatrix with variable-precision arithmetic.
The result is a symbolic expression with variable-precision numbers and scalar variables of type sym.
For an example, see “Evaluate Symbolic Matrix Variable with Variable-Precision Arithmetic” on page
7-1612.
Support for character vectors that do not define a number has been removed. Instead, first create
symbolic numbers and variables using sym and syms, and then use operations on them. For example,
use vpa((1 + sqrt(sym(5)))/2) instead of vpa('(1 + sqrt(5))/2').
See Also
digits | double | root | vpaintegral
Topics
“Increase Precision of Numeric Calculations” on page 2-36
“Recognize and Avoid Round-Off Errors” on page 3-317
“Increase Speed by Reducing Precision” on page 3-321
“Choose Numeric or Symbolic Arithmetic” on page 2-32
“Change Output Format of Symbolic and Variable-Precision Arithmetic” on page 2-8
7-1613
7 Functions
vpaintegral
Numerical integration using variable precision
Syntax
vpaintegral(f,a,b)
vpaintegral(f,x,a,b)
vpaintegral( ___ ,Name,Value)
Description
vpaintegral(f,a,b) numerically approximates f from a to b. The default variable x in f is found
by symvar.
vpaintegral( ___ ,Name,Value) uses additional options specified by one or more Name,Value
pair arguments.
Examples
Numerically Integrate Symbolic Expression
ans =
2.33333
ans =
2.33333
vpaintegral uses variable-precision arithmetic while the MATLAB integral function uses double-
precision arithmetic. Using the default values of tolerance, vpaintegral can handle values that
cause the MATLAB integral function to overflow or underflow.
7-1614
vpaintegral
syms u x
f = besseli(5,25*x).*exp(-x*25);
fun = @(u)besseli(5,25*u).*exp(-u*25);
usingVpaintegral =
0.688424
The digits function does not affect vpaintegral. Instead, increase the precision of vpainteral
by decreasing the integration tolerances. Conversely, increase the speed of numerical integration by
increasing the tolerances. Control the tolerance used by vpaintegral by changing the relative
tolerance RelTol and absolute tolerance AbsTol, which affect the integration through the condition
Q − I ≤ max(AbsTol, Q · RelTol)
where Q = Calculated Integral
I = Exact Integral.
ans =
1.3475263146739901712314731279612
Integrate 1/(2*z-1) over the triangular path from 0 to 1+1i to 1-1i back to 0 by specifying
waypoints.
syms z
vpaintegral(1/(2*z-1), [0 0], 'Waypoints', [1+1i 1-1i])
ans =
- 8.67362e-19 - 3.14159i
Reversing the direction of the integral, by changing the order of the waypoints and exchanging the
limits, changes the sign of the result.
Multiple Integrals
2 3
∫ ∫ xy dx dy .
−1 1
7-1615
7 Functions
syms x y
vpaintegral(vpaintegral(x*y, x, [1 3]), y, [-1 2])
ans =
6.0
The limits of integration can be symbolic expressions or functions. Integrate over the triangular
region 0 ≤ x ≤ 1 and |y| < x by specifying the limits of the integration over y in terms of x.
ans =
0.89734
Input Arguments
f — Expression or function to integrate
symbolic number | symbolic variable | symbolic vector | symbolic matrix | symbolic multidimensional
array | symbolic function | symbolic expression
Limits of integration, specified as a list of two numbers, symbolic numbers, symbolic variables,
symbolic functions, or symbolic expressions.
x — Integration variable
symbolic variable
Integration variable, specified as a symbolic variable. If x is not specified, the integration variable is
found by symvar.
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: 'RelTol',1e-20
Relative error tolerance, specified as a positive real number. The default is 1e-6. The RelTol
argument determines the accuracy of the integration only if RelTol · Q > AbsTol, where Q is the
calculated integral. In this case, vpaintegral satisfies the condition Q − I ≤ RelTol · Q , where I is
the exact integral value. To use only RelTol and turn off AbsTol, set AbsTol to 0.
Example: 1e-8
7-1616
vpaintegral
Absolute error tolerance, specified as a non-negative real number. The default is 1e-10. AbsTol
determines the accuracy of the integration if AbsTol > RelTol · Q , where Q is the calculated integral.
In this case, vpaintegral satisfies the condition Q − I ≤ AbsTol, where I is the exact integral
value. To turn off AbsTol and use only RelTol, set AbsTol to 0.
Example: 1e-12
Maximum evaluations of input, specified as a positive integer or a positive symbolic integer. The
default value is 10^5. If the number of evaluations of f is greater than MaxFunctionCalls, then
vpaintegral throws an error. For unlimited evaluations, set MaxFunctionCalls to Inf.
Tips
• Ensure that the input is integrable. If the input is not integrable, the output of vpaintegral is
unpredictable.
• The digits function does not affect vpaintegral. To increase precision, use the RelTol and
AbsTol arguments instead.
Version History
Introduced in R2016b
See Also
diff | int | integral | vpa
Topics
“Integration” on page 3-176
7-1617
7 Functions
vpasolve
Solve symbolic equations numerically
Syntax
S = vpasolve(eqn,var)
S = vpasolve(eqn,var,init_param)
Y = vpasolve(eqns,vars)
Y = vpasolve(eqns,vars,init_param)
[y1,...,yN] = vpasolve(eqns,vars)
[y1,...,yN] = vpasolve(eqns,vars,init_param)
Description
S = vpasolve(eqn,var) numerically solves the equation eqn for the variable var. If you do not
specify var, vpasolve solves for the default variable determined by symvar. For example,
vpasolve(x + 1 == 2, x) numerically solves the equation x + 1 = 2 for x.
By default, vpasolve finds the solutions to 32 significant digits. To change the number of significant
digits, use the digits function.
S = vpasolve(eqn,var,init_param) numerically solves the equation eqn for the variable var
using the initial guess or search range init_param.
Y = vpasolve(eqns,vars) numerically solves the system of equations eqns for the variables
vars. This syntax returns a structure array Y that contains the solutions. The fields in the structure
array correspond to the variables specified by vars. If you do not specify vars, vpasolve solves for
the default variables determined by symvar.
[y1,...,yN] = vpasolve(eqns,vars) numerically solves the system of equations eqns for the
variables vars. This syntax assigns the solutions to the variables y1,...,yN. If you do not specify
vars, vpasolve solves for the default variables determined by symvar.
___ = vpasolve( ___ ,'Random',true) uses a random initial guess for finding solutions. Use
this input to avoid returning the same solution repeatedly for nonpolynomial equations. If you specify
initial guesses for all variables, setting 'Random' to true has no effect.
Examples
7-1618
vpasolve
Solve a polynomial equation. For polynomial equations, vpasolve returns all solutions.
syms x
S = vpasolve(2*x^4 + 3*x^3 - 4*x^2 - 3*x + 2 == 0, x)
S =
−2.0
−1.0
0.5
1.0
Solve a nonpolynomial equation. For nonpolynomial equations, vpasolve returns the first solution
that it finds.
S = vpasolve(sin(x) == 1/2, x)
S = 0.52359877559829887307710723054658
Find multiple solutions of the equation 200sin(x) = x3 − 1 by specifying the initial guesses when using
vpasolve.
syms x
eqnLeft = 200*sin(x);
eqnRight = x^3 - 1;
fplot([eqnLeft eqnRight])
title([texlabel(eqnLeft) ' = ' texlabel(eqnRight)])
7-1619
7 Functions
The plot shows that the equation has three solutions. If you do not specify the initial guess, vpasolve
returns the first solution that it finds.
S1 = vpasolve(eqnLeft == eqnRight, x)
S1 = −0.0050000214585835715725440675982988
Find one of the other solutions by specifying an initial guess that is close to that solution.
S2 = vpasolve(eqnLeft == eqnRight, x, -3)
S2 = −3.0009954677086430679926572924945
S3 = vpasolve(eqnLeft == eqnRight, x, 4)
S3 = 3.0098746383859522384063444361906
Solve a system of equations. Use one output argument to return the solutions in the form of a
structure array.
syms u v
Y = vpasolve([v^3 + 2*u == v, v^2 == u], [u,v])
7-1620
vpasolve
v: [3x1 sym]
uSol =
0
5.8284271247461900976033774484194
0.1715728752538099023966225515806
vSol = Y.v
vSol =
0
−2.4142135623730950488016887242097
0.4142135623730950488016887242097
Y =
When solving a system of equations, use multiple output arguments to assign the solutions directly to
output variables. The order in which the solver returns the solutions follows the order in which you
specify the variables.
syms x y
[sol_x, sol_y] = vpasolve([x*sin(10*x) == y^3, y^2 == exp(-2*x/3)], [x,y])
sol_x = 88.90707209659114864849280774681
sol_y = 0.00000000000013470479710676694388973703681918
You can specify ranges of solutions of an equation. For example, if you want to restrict your search to
only real solutions, you cannot use assumptions because vpasolve ignores assumptions. Instead,
specify a search interval. For the following equation, if you do not specify ranges, the numeric solver
returns all six solutions of the equation.
syms x
S = vpasolve(x^6 - x^2 == 3, x)
7-1621
7 Functions
S =
−1.2929423350084724369196550436382
1.2929423350084724369196550436382
−0.50188125716943915856832436499602 − 1.0429452224956770037495194222175 i
−0.50188125716943915856832436499602 + 1.0429452224956770037495194222175 i
0.50188125716943915856832436499602 − 1.0429452224956770037495194222175 i
0.50188125716943915856832436499602 + 1.0429452224956770037495194222175 i
Suppose you need only real solutions of this equation. You cannot use assumptions on variables
because vpasolve ignores them.
assume(x,'real')
S = vpasolve(x^6 - x^2 == 3, x)
S =
−1.2929423350084724369196550436382
1.2929423350084724369196550436382
−0.50188125716943915856832436499602 − 1.0429452224956770037495194222175 i
−0.50188125716943915856832436499602 + 1.0429452224956770037495194222175 i
0.50188125716943915856832436499602 − 1.0429452224956770037495194222175 i
0.50188125716943915856832436499602 + 1.0429452224956770037495194222175 i
Specify the search range to restrict the returned results to particular ranges. For example, to return
only real solutions of this equation, specify the search interval as [-Inf Inf].
S =
−1.2929423350084724369196550436382
1.2929423350084724369196550436382
S = 1.2929423350084724369196550436382
The search range can also contain complex numbers, such as [-1, 1+2i]. In this case, vpasolve
uses a rectangular search area in the complex plane where -1 specifies the bottom-left corner of the
search area and 1+2i specifies the top-right corner of that area.
S =
−0.50188125716943915856832436499602 + 1.0429452224956770037495194222175 i
0.50188125716943915856832436499602 + 1.0429452224956770037495194222175 i
syms x y
eqn1 = exp(-x^2-y^2)*(x-4) - exp((-x^2-y^2)/2)*(x-2) == 0
7-1622
vpasolve
eqn1 =
2 2 x2 y2
e−x − y x − 4 − e− 2 − 2 x−2 =0
eqn2 =
2 2 x2 y2
e−x − y y − 2 − e− 2 − 2 y−4 =0
Find the solution for the variables x and y without specifying initial guess. vpasolve cannot find a
solution and it returns an empty object.
solX =
solY =
Now specify the initial guesses x = 2 and y = 4. vpasolve returns the solutions that are close to
the initial guesses.
solX = 1.9999092125057125429174334656647
solY = 4.0000907874942874570825665343353
By default, vpasolve returns the same solution on every call. To find more than one solution for
nonpolynomial equations, set 'Random' to true. This makes vpasolve use a random initial guess
which can lead to different solutions on successive calls.
If 'Random' is not specified, vpasolve returns the same solution on every call.
syms x
f = x-tan(x);
for n = 1:3
S = vpasolve(f,x)
end
S = 0
S = 0
S = 0
When 'Random' is set to true, vpasolve returns a distinct solution on every call.
7-1623
7 Functions
for n = 1:3
S = vpasolve(f,x,'Random',true)
end
S = −227.76107684764829218924973598808
S = 102.09196646490764333652956578441
S = 61.244730260374400372753016364097
S = vpasolve(f,x,[10 12],'Random',true)
S = 10.904121659428899827148702790189
Input Arguments
eqn — Equation to solve
symbolic equation | symbolic expression
Variable to solve equation for, specified as a symbolic variable. If var is not specified, symvar
determines the variables.
Variables to solve system of equations for, specified as a symbolic vector or symbolic matrix. These
variables are specified as a vector or comma-separated list. If vars is not specified, symvar
determines the variables.
Initial guess or search range for a solution, specified as a numeric value, vector, or matrix with two
columns.
• If init_param is a number or, in the case of multivariate equations, a vector of numbers, then the
numeric solver uses it as an initial guess. If init_param is specified as a scalar while the system
of equations is multivariate, then the numeric solver uses the scalar value as an initial guess for
7-1624
vpasolve
all variables. For an example, see “Find Multiple Solutions by Specifying Initial Guesses” on page
7-1619.
• If init_param is a matrix with two columns, then the two entries of the rows specify the bounds
of an initial guess for the corresponding variables. To specify an initial guess in a matrix of search
ranges, specify both columns as the initial guess value.
• If you specify init_param as a search range [a b] and the values a,b are complex numbers,
then vpasolve searches for the solutions in the rectangular search area in the complex plane.
Here, a specifies the bottom-left corner of the rectangular search area, and b specifies the top-
right corner of that area. For an example, see “Specify Ranges of Solutions” on page 7-1621.
• To omit a search range for a variable, set the search range for that variable to [NaN, NaN] in
init_param. All other uses of NaN in init_param will error.
Output Arguments
S — Solutions of univariate equation
symbolic value | symbolic array
Solutions of univariate equation, returned as symbolic value or symbolic array. The size of a symbolic
array corresponds to the number of the solutions.
Solutions of system of equations, returned as a structure array. The number of fields in the structure
array corresponds to the number of variables to be solved for.
Variables that are assigned solutions of system of equations, returned as an array of numeric or
symbolic variables. The number of output variables or symbolic arrays must equal the number of
variables to be solved for. If you explicitly specify independent variables vars, then the solver uses
the same order to return the solutions. If you do not specify vars, the toolbox sorts independent
variables alphabetically, and then assigns the solutions for these variables to the output variables or
symbolic arrays.
Tips
• If vpasolve cannot find a solution, it returns an empty object. Provide initial guess to help the
solver finding a solution. For an example, see “Provide Initial Guess to Find Solutions” on page 7-
1622.
• For polynomial equations, vpasolve returns all solutions. For nonpolynomial equations, there is
no general method of finding all solutions and vpasolve returns only one solution by default. To
find several different solutions for nonpolynomial, you can set 'Random' to true and use
vpasolve repeatedly.
• When you solve a system of equations with nonunique solutions, the behavior of vpasolve
depends on whether the system is polynomial or nonpolynomial. If polynomial, vpasolve returns
all solutions by introducing an arbitrary parameter. If nonpolynomial, a single numerical solution
is returned, if it exists.
7-1625
7 Functions
• When you solve a system of rational equations, vpasolve transforms the rational equations to
polynomials by multiplying out the denominators. vpasolve returns all solutions of the resulting
polynomial system, which also include the roots of the denominators.
• vpasolve ignores assumptions set on variables. You can restrict the returned results to particular
ranges by specifying appropriate search ranges using the argument init_param. However, if the
equations or expressions have other variables besides the variables to solve for as specified by
vars, then vpasolve returns the solutions for vars in terms of the other variables that are
complex in general.
• The output variables y1,...,yN do not specify the variables for which vpasolve solves
equations or systems. If y1,...,yN are the variables that appear in eqns, that does not
guarantee that vpasolve(eqns) will assign the solutions to y1,...,yN using the correct order.
Thus, for the call [a,b] = vpasolve(eqns), you might get the solutions for a assigned to b and
vice versa. To ensure the order of the returned solutions, specify the variables vars. For example,
the call [b,a] = vpasolve(eqns,[b,a]) assigns the solutions for a assigned to a and the
solutions for b assigned to b.
• You can solve equations symbolically using solve, and then numerically approximate the results
using vpa. Using this approach, you get numeric approximations of all solutions found by the
symbolic solver. However, this can reduce computational speed since solving symbolically and
postprocessing the results take more time than directly using the numeric solver vpasolve.
Algorithms
• When you set 'Random' to true and specify a search range for a variable, random initial guesses
within the search range are chosen using the internal random number generator (with uniform
distribution).
• When you set 'Random' to true and do not specify a search range for a variable, random initial
guesses are generated using a Cauchy distribution with a half-width of 100. This means the initial
guesses are real valued and have a large spread of values on repeated calls.
Version History
Introduced in R2012b
R2021b: vpasolve(eqns,vars) returns all solutions for the symbolic matrix vars
Behavior changed in R2021b
If vars is declared as a symbolic matrix, vpasolve(eqns,vars) now returns all solutions for vars.
For example, find the solutions of four equations with four unknowns. Declare the four unknowns as a
symbolic matrix. vpasolve(eqns,vars) now returns all solutions for the unknowns.
syms a b c d
eqn1 = b + c + d == 50;
eqn2 = a + c + d == 65;
eqn3 = a + b + d == 70;
eqn4 = a + b + c == 65;
vars = [a b; c d];
sol = vpasolve([eqn1 eqn2 eqn3 eqn4],vars)
sol =
struct with fields:
a: 33.333333333333333333333333333333
c: 13.333333333333333333333333333333
7-1626
vpasolve
b: 18.333333333333333333333333333333
d: 18.333333333333333333333333333333
syms a b c d
eqn1 = b + c + d == 50;
eqn2 = a + c + d == 65;
eqn3 = a + b + d == 70;
eqn4 = a + b + c == 65;
vars = [a b; c d];
sol = vpasolve([eqn1 eqn2 eqn3 eqn4],vars)
sol =
struct with fields:
a: [1×1 sym]
c: [1×1 sym]
See Also
dsolve | equationsToMatrix | fzero | isolate | linsolve | solve | symvar | vpa | digits
7-1627
7 Functions
vpasum
Numerical summation using variable precision
Syntax
s = vpasum(f,a,b)
s = vpasum(f,x,a,b)
Description
s = vpasum(f,a,b) numerically approximates the sum of a series defined by f from a to b. The
default summation variable x in f is determined by symvar. The summation bounds a and b must be
real.
Examples
1
Numerically sum the symbolic expression x
from 1 to 1,000.
1.2
syms x;
s = vpasum(1/1.2^x,1,1000)
s = 5.0
Find the summation of the symbolic function y(x) = x2 from a to b. Since the limits of summation must
be real values, assume that the bounds a and b are real.
syms y(x)
syms a b real
y(x) = x^2;
s = vpasum(y,a,b)
s =
∑bx = a x2
7-1628
vpasum
k log k
Find the symbolic summation of the series ∑∞
k = 1 −1 3
using symsum. Use vpa to numerically
k
evaluate the symbolic summation using 32 significant digits. Measure the time required to declare
the symbolic summation and evaluate its numerical value.
syms k
tic
y = symsum((-1)^k*log(k)/k^3,k,1,Inf)
y =
k
−1 log k
∑∞k = 1 3
k
yVpa = vpa(y)
yVpa = 0.059705906160195358363429266287926
toc
To increase computation performance (shorten computation time), use vpasum to evaluate the same
numerical summation without evaluating the symbolic summation.
tic
y = vpasum((-1)^k*log(k)/k^3,k,1,Inf)
y = 0.059705906160195358363429266287926
toc
Input Arguments
f — Expression or function to sum
symbolic number | symbolic variable | symbolic function | symbolic expression | symbolic vector |
symbolic matrix | symbolic multidimensional array
Expression or function to sum, specified as a symbolic number, variable, function, expression, vector,
matrix, or multidimensional array.
x — Summation variable
symbolic variable
7-1629
7 Functions
Summation variable, specified as a symbolic variable. If x is not specified, the integration variable is
determined by symvar(f).
Algorithms
Depending on whether the series is alternating or monotone, vpasum tries a number of strategies to
calculate its limit: Levin's u-transformation, the Euler–Maclaurin formula, or van Wijngaarden's trick.
b b p/2 B2m
∑
i=a
f (i) =
f (a) + f (b)
2
+ ∫ f (x) dx +
a
∑
m=1
(2m)!
f (b)
2m − 1
− f (a)
2m − 1
+ Rp,
where B2m represents the 2mth Bernoulli on page 7-99 number and Rp is an error term which
depends on a, b, p, and f.
Version History
Introduced in R2020b
References
[1] Olver, F. W. J., A. B. Olde Daalhuis, D. W. Lozier, B. I. Schneider, R. F. Boisvert, C. W. Clark, B. R.
Miller, B. V. Saunders, H. S. Cohl, and M. A. McClain, eds., Chapter 2.10 Sums and
Sequences, NIST Digital Library of Mathematical Functions, Release 1.0.26 of 2020-03-15.
See Also
vpa | vpaintegral | symsum
7-1630
whittakerM
whittakerM
Whittaker M function
Syntax
whittakerM(a,b,z)
Description
whittakerM(a,b,z) returns the value of the Whittaker M function on page 7-1633.
Examples
Compute Whittaker M Function for Numeric Input
Compute the Whittaker M function for these numbers. Because these numbers are not symbolic
objects, you get floating-point results.
[whittakerM(1, 1, 1), whittakerM(-2, 1, 3/2 + 2*i),...
whittakerM(2, 2, 2), whittakerM(3, -0.3, 1/101)]
ans =
0.7303 -9.2744 + 5.4705i 2.6328 0.3681
Compute the Whittaker M function for the numbers converted to symbolic objects. For most symbolic
(exact) numbers, whittakerM returns unresolved symbolic calls.
[whittakerM(sym(1), 1, 1), whittakerM(-2, sym(1), 3/2 + 2*i),...
whittakerM(2, 2, sym(2)), whittakerM(sym(3), -0.3, 1/101)]
ans =
[ whittakerM(1, 1, 1), whittakerM(-2, 1, 3/2 + 2i),
whittakerM(2, 2, 2), whittakerM(3, -3/10, 1/101)]
For symbolic variables and expressions, whittakerM also returns unresolved symbolic calls:
syms a b x y
[whittakerM(a, b, x), whittakerM(1, x, x^2),...
whittakerM(2, x, y), whittakerM(3, x + y, x*y)]
ans =
[ whittakerM(a, b, x), whittakerM(1, x, x^2),...
whittakerM(2, x, y), whittakerM(3, x + y, x*y)]
Solve this second-order differential equation. The solutions are given in terms of the Whittaker
functions.
syms a b w(z)
dsolve(diff(w, 2) + (-1/4 + a/z + (1/4 - b^2)/z^2)*w == 0)
7-1631
7 Functions
ans =
C2*whittakerM(-a,-b,-z) + C3*whittakerW(-a,-b,-z)
Verify that the Whittaker M function is a valid solution of this differential equation:
syms a b z
isAlways(diff(whittakerM(a,b,z), z, 2) +...
(-1/4 + a/z + (1/4 - b^2)/z^2)*whittakerM(a,b,z) == 0)
ans =
logical
1
syms a b z
isAlways(diff(whittakerM(-a,-b,-z), z, 2) +...
(-1/4 + a/z + (1/4 - b^2)/z^2)*whittakerM(-a,-b,-z) == 0)
ans =
logical
1
whittakerM(sym(-3/2), 1, 1)
ans =
exp(1/2)
syms a b x
whittakerM(0, b, x)
ans =
4^b*x^(1/2)*gamma(b + 1)*besseli(b, x/2)
whittakerM(a + 1/2, a, x)
ans =
x^(a + 1/2)*exp(-x/2)whittakerM(a, a - 5/2, x)
ans =
(2*x^(a - 2)*exp(-x/2)*(2*a^2 - 7*a + x^2/2 -...
x*(2*a - 3) + 6))/pochhammer(2*a - 4, 2)
syms a b z
diff(whittakerM(a,b,z), z)
ans =
(whittakerM(a + 1, b, z)*(a + b + 1/2))/z -...
(a/z - 1/2)*whittakerM(a, b, z)
7-1632
whittakerM
ans =
[ exp(-1/2)*1i, exp(x^2/2)*(x^2)^(1/2)]
[ 0, x^(1/2)*exp(x/2)]
Input Arguments
a — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
If a is a vector or matrix, whittakerM returns the beta function for each element of a.
b — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
If b is a vector or matrix, whittakerM returns the beta function for each element of b.
z — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
If x is a vector or matrix, whittakerM returns the beta function for each element of z.
More About
Whittaker M Function
The Whittaker functions Ma,b(z) and Wa,b(z) are linearly independent solutions of this differential
equation:
2 2
d w 1 a 1/4 − b
+ − + + w=0
dz 2 4 z z2
1
Ma, b z = e−z/2 zb + 1/2 M b − a + , 1 + 2b, z
2
7-1633
7 Functions
Tips
• All non-scalar arguments must have the same size. If one or two input arguments are non-scalar,
then whittakerM expands the scalars into vectors or matrices of the same size as the non-scalar
arguments, with all elements equal to the corresponding scalar.
Version History
Introduced in R2012a
References
[1] Slater, L. J. “Cofluent Hypergeometric Functions.” Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New
York: Dover, 1972.
See Also
hypergeom | kummerU | whittakerW
7-1634
whittakerW
whittakerW
Whittaker W function
Syntax
whittakerW(a,b,z)
Description
whittakerW(a,b,z) returns the value of the Whittaker W function on page 7-1637.
Examples
Compute Whittaker W Function for Numeric Input
Compute the Whittaker W function for these numbers. Because these numbers are not symbolic
objects, you get floating-point results.
[whittakerW(1, 1, 1), whittakerW(-2, 1, 3/2 + 2*i),...
whittakerW(2, 2, 2), whittakerW(3, -0.3, 1/101)]
ans =
1.1953 -0.0156 - 0.0225i 4.8616 -0.1692
Compute the Whittaker W function for the numbers converted to symbolic objects. For most symbolic
(exact) numbers, whittakerW returns unresolved symbolic calls.
[whittakerW(sym(1), 1, 1), whittakerW(-2, sym(1), 3/2 + 2*i),...
whittakerW(2, 2, sym(2)), whittakerW(sym(3), -0.3, 1/101)]
ans =
[ whittakerW(1, 1, 1), whittakerW(-2, 1, 3/2 + 2i),
whittakerW(2, 2, 2), whittakerW(3, -3/10, 1/101)]
For symbolic variables and expressions, whittakerW also returns unresolved symbolic calls:
syms a b x y
[whittakerW(a, b, x), whittakerW(1, x, x^2),...
whittakerW(2, x, y), whittakerW(3, x + y, x*y)]
ans =
[ whittakerW(a, b, x), whittakerW(1, x, x^2),
whittakerW(2, x, y), whittakerW(3, x + y, x*y)]
Solve this second-order differential equation. The solutions are given in terms of the Whittaker
functions.
syms a b w(z)
dsolve(diff(w, 2) + (-1/4 + a/z + (1/4 - b^2)/z^2)*w == 0)
7-1635
7 Functions
ans =
C2*whittakerM(-a, -b, -z) + C3*whittakerW(-a, -b, -z)
Verify that the Whittaker W function is a valid solution of this differential equation:
syms a b z
isAlways(diff(whittakerW(a, b, z), z, 2) +...
(-1/4 + a/z + (1/4 - b^2)/z^2)*whittakerW(a, b, z) == 0)
ans =
logical
1
Verify that whittakerW(-a, -b, -z) also is a valid solution of this differential equation:
syms a b z
isAlways(diff(whittakerW(-a, -b, -z), z, 2) +...
(-1/4 + a/z + (1/4 - b^2)/z^2)*whittakerW(-a, -b, -z) == 0)
ans =
logical
1
whittakerW(sym(-3/2), 1/2, 0)
ans =
4/(3*pi^(1/2))
syms a b x
whittakerW(0, b, x)
ans =
(x^(b + 1/2)*besselk(b, x/2))/(x^b*pi^(1/2))
whittakerW(a, -a + 1/2, x)
ans =
x^(1 - a)*x^(2*a - 1)*exp(-x/2)
whittakerW(a - 1/2, a, x)
ans =
(x^(a + 1/2)*exp(-x/2)*exp(x)*igamma(2*a, x))/x^(2*a)
syms a b z
diff(whittakerW(a,b,z), z)
ans =
- (a/z - 1/2)*whittakerW(a, b, z) -...
whittakerW(a + 1, b, z)/z
7-1636
whittakerW
syms x
A = [-1, x^2; 0, x];
whittakerW(-1/2, 0, A)
ans =
[ -exp(-1/2)*(ei(1) + pi*1i)*1i,...
exp(x^2)*exp(-x^2/2)*expint(x^2)*(x^2)^(1/2)]
[ 0,...
x^(1/2)*exp(-x/2)*exp(x)*expint(x)]
Input Arguments
a — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
If a is a vector or matrix, whittakerW returns the beta function for each element of a.
b — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
If b is a vector or matrix, whittakerW returns the beta function for each element of b.
z — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
If x is a vector or matrix, whittakerW returns the beta function for each element of z.
More About
Whittaker W Function
The Whittaker functions Ma,b(z) and Wa,b(z) are linearly independent solutions of this differential
equation:
2 2
d w 1 a 1/4 − b
+ − + + w=0
dz 2 4 z z2
7-1637
7 Functions
1
Wa, b z = e−z/2zb + 1/2U b − a + , 1 + 2b, z
2
Tips
• All non-scalar arguments must have the same size. If one or two input arguments are non-scalar,
then whittakerW expands the scalars into vectors or matrices of the same size as the non-scalar
arguments, with all elements equal to the corresponding scalar.
Version History
Introduced in R2012a
References
[1] Slater, L. J. “Cofluent Hypergeometric Functions.” Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun, eds.). New
York: Dover, 1972.
See Also
hypergeom | kummerU | whittakerM
7-1638
wrightOmega
wrightOmega
Wright omega function
Syntax
wrightOmega(x)
Description
wrightOmega(x) computes the Wright omega function on page 7-1641 of x. If z is a matrix,
wrightOmega acts elementwise on z.
Examples
Compute Wright Omega Function of Numeric Inputs
Compute the Wright omega function for these numbers. Because these numbers are not symbolic
objects, you get floating-point results:
wrightOmega(1/2)
ans =
0.7662
wrightOmega(pi)
ans =
2.3061wrightOmega(-1+i*pi)
ans =
-1.0000 + 0.0000
Compute the Wright omega function for the numbers converted to symbolic objects. For most
symbolic (exact) numbers, wrightOmega returns unresolved symbolic calls:
wrightOmega(sym(1/2))
ans =
wrightOmega(1/2)
wrightOmega(sym(pi))
ans =
wrightOmega(pi)
wrightOmega(-1+i*sym(pi))
ans =
-1
7-1639
7 Functions
Compute the Wright omega function for x and sin(x) + x*exp(x). For symbolic variables and
expressions, wrightOmega returns unresolved symbolic calls:
syms x
wrightOmega(x)
wrightOmega(sin(x) + x*exp(x))
ans =
wrightOmega(x)
ans =
wrightOmega(sin(x) + x*exp(x))
diff(wrightOmega(x), x, 2)
diff(wrightOmega(sin(x) + x*exp(x)), x)
ans =
wrightOmega(x)/(wrightOmega(x) + 1)^2 -...
wrightOmega(x)^2/(wrightOmega(x) + 1)^3
ans =
(wrightOmega(sin(x) + x*exp(x))*(cos(x) +...
exp(x) + x*exp(x)))/(wrightOmega(sin(x) + x*exp(x)) + 1)
Compute the Wright omega function for elements of matrix M and vector V:
ans =
0.5671 2.3061
0.6959 0.0415
ans =
lambertw(0, 1)
-1
Input Arguments
x — Input
number | vector | matrix | array | symbolic number | symbolic variable | symbolic array | symbolic
function | symbolic expression
Input, specified as a number, vector, matrix, or array, or a symbolic number, variable, array, function,
or expression.
7-1640
wrightOmega
More About
Wright omega Function
ωx =W Im x − π ex
2π
Version History
Introduced in R2011b
References
[1] Corless, R. M. and D. J. Jeffrey. “The Wright omega Function.” Artificial Intelligence, Automated
Reasoning, and Symbolic Computation (J. Calmet, B. Benhamou, O. Caprotti, L. Henocque,
and V. Sorge, eds.). Berlin: Springer-Verlag, 2002, pp. 76-89.
See Also
lambertW | log
7-1641
7 Functions
writeAnimation
Save animation as video file
Syntax
writeAnimation(filename)
writeAnimation(fig,filename)
writeAnimation( ___ ,Name,Value)
writeAnimation(vidObj)
writeAnimation(fig,vidObj)
Description
writeAnimation(filename) writes animation objects in the current figure to a GIF or AVI video
file. The animation objects must be created using the fanimator function. The extension of
filename sets the video format, and must be either '.gif' or '.avi'.
• If you do not specify the file extension, then writeAnimation chooses the '.avi' extension by
default.
• If you specify any other file extension, such as '.mp4' or '.mpg', then writeAnimation returns
an error message.
writeAnimation(fig,filename) writes animation objects in the figure fig to a GIF or AVI video
file.
writeAnimation( ___ ,Name,Value) writes animation objects with the specified Name,Value pair
arguments. Use this option with any of the input argument combinations in the previous syntaxes.
You can set the name-value pair settings to specify the properties of a GIF or AVI video file.
If you save an animation as a VideoWriter object, then the properties of the output video file follow
the properties of the VideoWriter object.
Examples
Create two symbolic variables, t and x. The variable t defines the time parameter of the animation.
Use t to set the center of the circle at (t,1) and x to parameterize the perimeter of the circle within
7-1642
writeAnimation
the range [-pi pi]. Create the circle animation object using fanimator. Set the x-axis and y-axis
to be equal length.
syms t x
fanimator(@fplot,cos(x)+t,sin(x)+1,[-pi pi])
axis equal
Enter the command playAnimation to play the animation. Save the animation as a GIF video file
named 'wheel.gif'.
writeAnimation('wheel.gif')
First, create two symbolic variables, t and x. The variable t defines the time parameter of the
animation. Use t to set the center of the circle at (t,1) and x to parameterize the perimeter of the
circle within the range [-pi pi]. Create the circle animation object using fanimator. Set the x-
axis and y-axis to be equal length.
syms t x
fanimator(@fplot,cos(x)+t,sin(x)+1,[-pi pi])
axis equal
7-1643
7 Functions
Next, save the animation as an MPEG-4 file. Create a video object that saves to a file named
'myFile' by using the VideoWriter function. Specify the video file format as 'MPEG-4'. Open the
video file, use writeAnimation to save the circle animation object, and close the video file.
vidObj = VideoWriter('myFile','MPEG-4');
open(vidObj)
writeAnimation(vidObj)
close(vidObj)
Create a circle animation object and save it as a GIF file that plays a specified number of loops.
First, create two symbolic variables, t and x. The variable t defines the time parameter of the
animation. Create a figure window for the animation.
syms t x
fig = figure;
Create the circle animation object using fanimator. Use t to set the center of the circle at (t,1)
and x to parameterize the perimeter of the circle within the range [-pi pi]. Set the x-axis and y-
axis to be equal length.
syms t x
fanimator(@fplot,cos(x)+t,sin(x)+1,[-pi pi])
axis equal
7-1644
writeAnimation
Next, save the animation in the figure fig as a GIF file named 'loop.gif' by using the
writeAnimation function. The writeAnimation function always plays the animation once in a
MATLAB figure window before saving the animation. When saving the animation as a GIF file, the
created GIF file plays the animation once and repeats the number of loops as specified. For this
example, set 'LoopCount' to 1. The GIF file plays the animation twice.
writeAnimation(fig,'loop.gif','LoopCount',1)
Note that to properly show the number of loops in a GIF video file, you must open the file in an
application with GIF decoder.
Input Arguments
filename — Video filename
string | character vector
Video filename, specified as a string scalar or character vector. The extension of filename sets the
video format, and must be either '.gif' or '.avi'. You must have permission to write the file.
• If you do not specify the file extension, then writeAnimation uses '.avi' by default.
• If filename already exists, then writeAnimation overwrites the file.
• If filename does not include a full path, then the function saves the animation to the current
folder.
7-1645
7 Functions
Video object, specified as a VideoWriter object. The VideoWriter object provides the option to
control the output video format when you save animation objects. For more information about
VideoWriter object in MATLAB, see VideoWriter.
Target figure, specified as a Figure object. For more information about Figure objects, see figure.
Before R2021a, use commas to separate each name and value, and enclose Name in quotes.
Example: 'FrameRate',15,'LoopCount',2
Range of the animation time parameter, specified as a two-element row vector. The two elements
must be real values that are increasing.
Example: [-2 4.5]
Frame rate, specified as a positive value. The frame rate defines the number of frames per unit time
when you write animation objects to a video file.
Example: 30
Backward option, specified as a logical value (boolean). If you specify true, then the function saves
the animation backwards or in reverse order.
Example: true
Animation loop count, specified as a nonnegative integer (from 0 to 65535) or Inf. This value sets
the number of repeated animation loops in a GIF file. Setting this value has no effect if you use a
video file format other than GIF.
• If you use the default value of 0, then the GIF file plays the animation once.
• If you set 'LoopCount' to an integer n, then the GIF file plays the animation once plus n repeats
(a total of n+1 times).
7-1646
writeAnimation
Example: 1
Version History
Introduced in R2019a
See Also
fanimator | animationToFrame | playAnimation | rewindAnimation | VideoWriter
7-1647
7 Functions
xor
Logical XOR for symbolic expressions
Syntax
xor(A,B)
Description
xor(A,B) represents the logical exclusive disjunction. xor(A,B) is true when either A or B is true. If
both A and B are true or false, xor(A,B) is false.
Examples
Set and Evaluate Condition
syms x
range = xor(x > -10, x < 10);
Replace variable x with 11 and 0. If you replace x with 11, then inequality x > -10 is valid and x <
10 is invalid. If you replace x with 0, both inequalities are valid. Note that subs only substitutes the
numeric values into the inequalities. It does not evaluate the inequalities to logical 1 or 0.
x1 = subs(range,x,11)
x2 = subs(range,x,0)
x1 =
-10 < 11 xor 11 < 10
x2 =
-10 < 0 xor 0 < 10
To evaluate these inequalities to logical 1 or 0, use isAlways. If only one inequality is valid, the
expression with xor evaluates to logical 1. If both inequalities are valid, the expression with xor
evaluates to logical 0.
isAlways(x1)
isAlways(x2)
ans =
logical
1
ans =
logical
0
Note that simplify does not simplify these logical expressions to logical 1 or 0. Instead, simplify
returns symbolic constants symtrue or symfalse.
7-1648
xor
s1 = simplify(x1)
s2 = simplify(x2)
s1 =
symtrue
s2 =
symfalse
logical(s1)
logical(s2)
ans =
logical
1
ans =
logical
0
Input Arguments
A, B — Operands
symbolic equations | symbolic inequalities | symbolic expressions | symbolic arrays
Operands, specified as symbolic equations, inequalities, expressions, or arrays. Inputs A and B must
either be the same size or have sizes that are compatible (for example, A is an M-by-N matrix and B is
a scalar or 1-by-N row vector). For more information, see “Compatible Array Sizes for Basic
Operations”.
Tips
• If you call simplify for a logical expression containing symbolic subexpressions, you can get the
symbolic constants symtrue and symfalse. These two constants are not the same as logical 1
(true) and logical 0 (false). To convert symbolic symtrue and symfalse to logical values, use
logical.
• assume and assumeAlso do not accept assumptions that contain xor.
Version History
Introduced in R2012a
Starting in R2016b with the addition of implicit expansion, some combinations of arguments for basic
operations that previously returned errors now produce results. For example, you previously could
not add a row and a column vector, but those operands are now valid for addition. In other words, an
expression like [1 2] + [1; 2] previously returned a size mismatch error, but now it executes.
7-1649
7 Functions
If your code uses element-wise operators and relies on the errors that MATLAB previously returned
for mismatched sizes, particularly within a try/catch block, then your code might no longer catch
those errors.
For more information on the required input sizes for basic array operations, see “Compatible Array
Sizes for Basic Operations”.
See Also
all | and | any | isAlways | not | or
7-1650
zeta
zeta
Riemann zeta function
Syntax
zeta(z)
zeta(n,z)
Description
zeta(z) evaluates the Riemann zeta function at the elements of z, where z is a numeric or symbolic
input.
Examples
Find Riemann Zeta Function for Numeric and Symbolic Inputs
ans =
-2.7784 + 0.0000i 0.0033 - 0.4182i 1.0823 + 0.0000i 1.1094 + 0.0000i
Find the Riemann zeta function symbolically by converting the inputs to symbolic objects using sym.
The zeta function returns exact results.
zeta(sym([0.7 i 4 11/3]))
ans =
[ zeta(7/10), zeta(1i), pi^4/90, zeta(11/3)]
zeta returns unevaluated function calls for symbolic inputs that do not have results implemented.
The implemented results are listed in “Algorithms” on page 7-1654.
Z =
[ zeta(x), zeta(sin(x))]
[ zeta((8*x)/11), zeta(x + y)]
For values of |z|>1000, zeta(z) might return an unevaluated function call. Use expand to force
zeta to evaluate the function call.
zeta(sym(1002))
expand(zeta(sym(1002)))
7-1651
7 Functions
ans =
zeta(1002)
ans =
(1087503...312*pi^1002)/15156647...375
syms x
expr = zeta(3,x)
expr =
zeta(3, x)
expr = subs(expr,x,4)
expr =
zeta(3, 4)
expr = vpa(expr)
expr =
-0.07264084989132137196244616781177
Zeros of the Riemann Zeta function zeta(x+i*y) are found along the line x = 1/2. Plot the
absolute value of the function along this line for 0<y<30 to view the first three zeros.
syms y
fplot(abs(zeta(1/2+1i*y)),[0 30])
grid on
7-1652
zeta
Input Arguments
z — Input
number | vector | matrix | multidimensional array | symbolic number | symbolic variable | symbolic
vector | symbolic matrix | symbolic multidimensional array | symbolic function | symbolic expression
Input, specified as a number, vector, matrix or multidimensional array, or a symbolic number, variable,
vector, matrix, multidimensional array, function or expression.
n — Order of derivative
nonnegative integer
More About
Riemann Zeta Function
∞
1
ζ(z) = ∑ z
k=1k
7-1653
7 Functions
The series converges only if the real part of z is greater than 1. The definition of the function is
extended to the entire complex plane, except for a simple pole z = 1, by analytic continuation.
Tips
• Floating point evaluation is slow for large values of n.
Algorithms
The following exact values are implemented.
• 1
ζ0 = −
2
• log π log 2
ζ 1, 0 = − −
2 2
• ζ ∞ =1
• If z < 0 and z is an even integer, ζ z = 0.
• If z < 0 and z is an odd integer
bernoulli 1 − z
ζ z = −
1−z
For z < − 1000, zeta(z) returns an unevaluated function call. To force evaluation, use
expand(zeta(z)).
• If z > 0 and z is an even integer
z
2π bernoulli z
ζ z =
2z!
For z > 1000, zeta(z) returns an unevaluated function call. To force evaluation, use
expand(zeta(z)).
• If n > 0, ζ n, ∞ = 0.
• If the argument does not evaluate to a listed special value, zeta returns the symbolic function
call.
Version History
Introduced before R2006a
See Also
bernoulli | hurwitzZeta | gamma | psi
7-1654
ztrans
ztrans
Z-transform
Syntax
ztrans(f)
ztrans(f,transVar)
ztrans(f,var,transVar)
Description
ztrans(f) finds the “Z-Transform” on page 7-1658 of f. By default, the independent variable is n
and the transformation variable is z. If f does not contain n, ztrans uses symvar.
Examples
syms n
f = sin(n);
ztrans(f)
ans =
(z*sin(1))/(z^2 - 2*cos(1)*z + 1)
Compute the Z-transform of exp(m+n). By default, the independent variable is n and the
transformation variable is z.
syms m n
f = exp(m+n);
ztrans(f)
ans =
(z*exp(m))/(z - exp(1))
Specify the transformation variable as y. If you specify only one variable, that variable is the
transformation variable. The independent variable is still n.
syms y
ztrans(f,y)
7-1655
7 Functions
ans =
(y*exp(m))/(y - exp(1))
Specify both the independent and transformation variables as m and y in the second and third
arguments, respectively.
ztrans(f,m,y)
ans =
(y*exp(n))/(y - exp(1))
Compute the Z-transform of the Heaviside function and the binomial coefficient.
syms n z
ztrans(heaviside(n-3),n,z)
ans =
(1/(z - 1) + 1/2)/z^3
ztrans(nchoosek(n,2))
ans =
z/(z - 1)^3
Find the Z-transform of the matrix M. Specify the independent and transformation variables for each
matrix entry by using matrices of the same size. When the arguments are nonscalars, ztrans acts on
them element-wise.
syms a b c d w x y z
M = [exp(x) 1; sin(y) i*z];
vars = [w x; y z];
transVars = [a b; c d];
ztrans(M,vars,transVars)
ans =
[ (a*exp(x))/(a - 1), b/(b - 1)]
[ (c*sin(1))/(c^2 - 2*cos(1)*c + 1), (d*1i)/(d - 1)^2]
If ztrans is called with both scalar and nonscalar arguments, then it expands the scalars to match
the nonscalars by using scalar expansion. Nonscalar arguments must be the same size.
syms w x y z a b c d
ztrans(x,vars,transVars)
ans =
[ (a*x)/(a - 1), b/(b - 1)^2]
[ (c*x)/(c - 1), (d*x)/(d - 1)]
7-1656
ztrans
Compute the Z-transform of symbolic functions. When the first argument contains symbolic functions,
then the second argument must be a scalar.
ans =
[ a/(a - exp(1)), b/(b - 1)^2]
syms f(n)
f(n) = 1/n;
F = ztrans(f,n,z)
F =
ztrans(1/n, n, z)
iztrans(F,z,n)
ans =
1/n
Input Arguments
f — Input
symbolic expression | symbolic function | symbolic vector | symbolic matrix
Independent variable, specified as a symbolic variable. This variable is often called the "discrete time
variable". If you do not specify the variable, then ztrans uses n. If f does not contain n, then
ztrans uses the function symvar.
Transformation variable, specified as a symbolic variable, expression, vector, or matrix. This variable
is often called the "complex frequency variable." By default, ztrans uses z. If z is the independent
variable of f, then ztrans uses w.
7-1657
7 Functions
More About
Z-Transform
The Z-transform F = F(z) of the expression f = f(n) with respect to the variable n at the point z is
∞
f n
Fz = ∑ n
.
n=0 z
Tips
• If any argument is an array, then ztrans acts element-wise on all elements of the array.
• If the first argument contains a symbolic function, then the second argument must be a scalar.
• To compute the inverse Z-transform, use iztrans.
Version History
Introduced before R2006a
See Also
fourier | ifourier | ilaplace | iztrans | kroneckerDelta | laplace
Topics
“Solve Difference Equations Using Z-Transform” on page 3-195
7-1658