Symbolic Math Toolbox User's Guide
Symbolic Math Toolbox User's Guide
User's Guide
R2016b
How to Contact MathWorks
Phone: 508-647-7000
Getting Started
1
Symbolic Math Toolbox Product Description . . . . . . . . . . . . 1-2
Key Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
v
Using Symbolic Math Toolbox Software
2
Find Symbolic Variables in Expressions, Functions,
Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
Find a Default Symbolic Variable . . . . . . . . . . . . . . . . . . . . . 2-4
Differentiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5
Derivatives of Expressions with Several Variables . . . . . . . . 2-6
More Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
Limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-19
One-Sided Limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-19
Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-22
Integration with Real Parameters . . . . . . . . . . . . . . . . . . . . 2-25
Integration with Complex Parameters . . . . . . . . . . . . . . . . . 2-27
High-Precision Numerical Integration Using Variable-Precision
Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-28
vi Contents
Abbreviate Common Terms in Long Expressions . . . . . . . . 2-58
vii
Conversion by Using Floating-Point Expansion . . . . . . . . . . 2-95
Conversion to Rational Symbolic Form with Error Term . . . 2-95
Conversion to Decimal Form . . . . . . . . . . . . . . . . . . . . . . . . 2-95
Eigenvalues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-105
viii Contents
Solve System of Linear Equations Using solve . . . . . . . . . 2-138
ix
Find Consistent Initial Conditions . . . . . . . . . . . . . . . . . . . 2-180
DAEs: Initial Conditions for ode15i . . . . . . . . . . . . . . . . . . 2-180
ODEs: Initial Conditions for ode15i . . . . . . . . . . . . . . . . . . 2-182
DAEs: Initial Conditions for ode15s and ode23t . . . . . . . . . 2-183
ODEs: Initial Conditions for ode15s and ode23t . . . . . . . . . 2-184
x Contents
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-230
xi
Copy Variables and Expressions Between MATLAB and
MuPAD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-51
Copy and Paste Using the System Clipboard . . . . . . . . . . . . 3-53
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 using
the MATLAB Live Editor. The toolbox provides libraries of functions in common
mathematical areas such as calculus, linear algebra, algebraic and ordinary differential
equations, equation simplification, and equation manipulation.
Key Features
Symbolic integration, differentiation, transforms, and linear algebra
Algebraic and ordinary differential equation (ODE) solvers
Simplification and manipulation of symbolic expressions
Plotting of analytical functions in 2D and 3D
Code generation from symbolic expressions for MATLAB, Simulink, Simscape, C,
Fortran, and LaTeX
Variable-precision arithmetic
1-2
Create Symbolic Numbers, Variables, and Expressions
Create a symbolic number by using sym and compare it to the same floating-point
number.
sym(1/3)
1/3
ans =
1/3
ans =
0.3333
The symbolic number is represented in exact rational form, while the floating-point
number is a decimal approximation. The symbolic result is not indented, while the
standard MATLAB result is indented.
sin(sym(pi))
sin(pi)
ans =
0
ans =
1.2246e-16
1-3
1 Getting Started
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 value y. Therefore, the commands are equivalent.
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 many variables, the syms syntax is inconvenient. Instead of using
syms, use sym to create many numbered variables.
A =
[ a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,...
a11, a12, a13, a14, a15, a16, a17, a18, a19, a20]
The syms command is a convenient shorthand for the sym syntax. Use the sym syntax
when you create many variables, when the variable value differs from the variable name,
or when you create a symbolic number, such as sym(5).
1+ 5
j=
2
The command
1-4
Create Symbolic Numbers, Variables, and Expressions
phi = (1 + sqrt(sym(5)))/2;
achieves this goal. Now you can perform various mathematical operations on phi. For
example,
f = phi^2 - phi - 1
returns
f =
(5^(1/2)/2 + 1/2)^2 - 5^(1/2)/2 - 3/2
Now 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
f = a*x^2 + b*x + c;
Tip To create a symbolic number, use the sym command. Do not use the syms function
to create a symbolic expression that is a constant. For example, to create the expression
whose value is 5, enter f = sym(5). The command f = 5 does not define f as a
symbolic expression.
syms a b
f = a + b
returns
f =
a + b
1-5
1 Getting Started
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. However, syms does not clear the following
assumptions of the variables: complex, real, integer, and positive. These assumptions are
stored separately from the symbolic object. For more information, see Delete Symbolic
Objects and Their Assumptions on page 1-28.
More About
Create Symbolic Functions on page 1-7
Create Symbolic Matrices on page 1-9
Perform Symbolic Computations on page 1-12
Use Assumptions on Symbolic Variables on page 1-27
1-6
Create Symbolic Functions
syms f(x, y)
This syntax creates the symbolic function f and symbolic variables x and y. If instead
of an arbitrary symbolic function you want to create a function defined by a particular
mathematical expression, use this two-step approach. First, create symbolic variables
representing the arguments of the function:
syms x y
Then assign a mathematical expression to the function. In this case, the assignment
operation also creates the new symbolic function:
f(x, y) = x^3*y^3
f(x, y) =
x^3*y^3
Note that the body of the function must be a symbolic number, variable, or expression.
Assigning a number, such as f(x,y) = 1, causes an error.
After creating a symbolic function, you can differentiate, integrate, or simplify it,
substitute its arguments with values, and perform other mathematical operations. For
example, find the second derivative on f(x, y) with respect to variable y. The result
d2fy is also a symbolic function.
d2fy = diff(f, y, 2)
d2fy(x, y) =
6*x^3*y
f(y + 1, y)
ans =
y^3*(y + 1)^3
1-7
1 Getting Started
More About
Create Symbolic Numbers, Variables, and Expressions on page 1-3
Create Symbolic Matrices on page 1-9
Perform Symbolic Computations on page 1-12
Use Assumptions on Symbolic Variables on page 1-27
1-8
Create Symbolic Matrices
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)))
From this example, you can see that using symbolic objects is very similar to using
regular MATLAB numeric objects.
1-9
1 Getting Started
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]
By applying sym to A
A = sym(A)
1-10
Create Symbolic Matrices
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]
More About
Create Symbolic Numbers, Variables, and Expressions on page 1-3
Create Symbolic Functions on page 1-7
Perform Symbolic Computations on page 1-12
Use Assumptions on Symbolic Variables on page 1-27
1-11
1 Getting Started
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:
1-12
Perform Symbolic Computations
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-4.
ans =
-2*cos(y)*sin(y)
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
1-13
1 Getting Started
For in-depth information on the int command including integration with real and
complex parameters, see Integration on page 2-22.
Suppose you want to integrate a symbolic expression. The first step is to create the
symbolic expression:
syms x
f = sin(x)^2;
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:
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-4.
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)
1-14
Perform Symbolic Computations
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)
ans =
int(sin(sinh(x)), x)
Solve Equations
You can solve different types of symbolic equations including:
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:
1-15
1 Getting Started
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-4.
x =
0
2
1-16
Perform Symbolic Computations
y =
0
2
z =
0
8
returns
f =
(5^(1/2)/2 + 1/2)^2 - 5^(1/2)/2 - 3/2
1-17
1 Getting Started
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:
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 2-60.
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
1-18
Perform Symbolic Computations
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)
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)
1-19
1 Getting Started
ans =
[ 312, 250, 170]
[ 78, -20, -118]
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-20
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)
A =
[ a, alpha, c]
[ beta, a, alpha]
[ alpha, c, a]
For more information, see Substitute Elements in Symbolic Matrices on page 2-75.
1-21
1 Getting Started
syms x
f = x^3 - 6*x^2 + 11*x - 6;
fplot(f)
1-22
Perform Symbolic Computations
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, Axis Labels, and Legend to Graph.
xlabel('x')
ylabel('y')
title(texlabel(f))
grid on
1-23
1 Getting Started
syms x y
eqn = (x^2 + y^2)^4 == (x^2 - y^2)^2;
fimplicit(eqn, [-1 1])
3-D Plot
1-24
Perform Symbolic Computations
syms t
fplot3(t^2*sin(10*t), t^2*cos(10*t), t)
syms x y
fsurf(x^2 + y^2)
1-25
1 Getting Started
More About
Create Symbolic Numbers, Variables, and Expressions on page 1-3
Create Symbolic Functions on page 1-7
Create Symbolic Matrices on page 1-9
Use Assumptions on Symbolic Variables on page 1-27
1-26
Use Assumptions on Symbolic Variables
Default Assumption
In Symbolic Math Toolbox, symbolic variables are complex variables by default. For
example, if you declare z as a symbolic variable using
syms z
then MATLAB assumes that z is a complex variable. You can always check if a symbolic
variable is assumed to be complex or real by using assumptions. If z is complex,
assumptions(z) returns an empty symbolic object:
assumptions(z)
ans =
Empty sym: 1-by-0
Set Assumptions
To set an assumption on a symbolic variable, use the assume function. For example,
assume that the variable x is nonnegative:
syms x
assume(x >= 0)
assume replaces all previous assumptions on the variable with the new assumption.
If you want to add a new assumption to the existing assumptions, use assumeAlso.
For example, add the assumption that x is also an integer. Now the variable x is a
nonnegative integer:
assumeAlso(x,'integer')
1-27
1 Getting Started
assume and assumeAlso let you state that a variable or an expression belongs to one of
these sets: integers, positive numbers, rational numbers, and real numbers.
Alternatively, you can set an assumption while declaring a symbolic variable using
sym or syms. For example, create the real symbolic variables a and b, and the positive
symbolic variable c:
a = sym('a', 'real');
b = sym('b', 'real');
c = sym('c', 'positive');
or more efficiently:
syms a b real
syms c positive
The assumptions that you can assign to a symbolic object with sym or syms are real,
rational, integer and positive.
assumptions(x)
To see all assumptions used for all symbolic variables in the MATLAB workspace, use
assumptions without input arguments:
assumptions
syms x
assume(x,'real')
1-28
Use Assumptions on Symbolic Variables
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 x
the assumption that x is real stays in the symbolic engine. If you declare a new symbolic
variable x later, it inherits the assumption that x is real instead of getting a default
assumption. If later you solve an equation and simplify an expression with the symbolic
variable x, you could get incomplete results. For example, the assumption that x is real
causes the polynomial x2+1 to have no roots:
syms x real
clear x
syms x
solve(x^2 + 1 == 0, x)
ans =
Empty sym: 0-by-1
The complex roots of this polynomial disappear because the symbolic variable x still has
the assumption that x is real stored in the symbolic engine. To clear the assumption,
enter
assume(x,'clear')
After you clear the assumption, the symbolic object stays in the MATLAB workspace.
If you want to remove both the symbolic object and its assumption, use two subsequent
commands:
assume(x,'clear')
2 To delete the symbolic object, enter
clear x
For details on clearing symbolic variables, see Clear Assumptions and Reset the
Symbolic Engine on page 3-66.
More About
Create Symbolic Numbers, Variables, and Expressions on page 1-3
1-29
1 Getting Started
1-30
2
2-2
Find Symbolic Variables in Expressions, Functions, Matrices
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 =
[ t, b]
Notice that the first two variables in this case are not a and b. When you call symvar
with two arguments, it sorts symbolic variables by their proximity to x.
ans =
[ w, x, y, z]
When you call symvar with two arguments, it returns the function inputs in front of
other variables:
2-3
2 Using Symbolic Math Toolbox Software
symvar(f, 2)
ans =
[ w, z]
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-4
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)
ans =
5*cos(5*x)
g = exp(x)*cos(x);
y = diff(g)
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
diff(g,2)
ans =
-2*exp(x)*sin(x)
You can get the same result by taking the derivative twice:
2-5
2 Using Symbolic Math Toolbox Software
diff(diff(g))
ans =
-2*exp(x)*sin(x)
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)
returns
ans =
0
diff(5)
MATLAB returns
ans =
[]
syms s t
f = sin(s*t);
the command
2-6
Differentiation
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-4. 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)
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
2-7
2 Using Symbolic Math Toolbox Software
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
2-8
Differentiation
diff(A)
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 Euclidean (x, y, z) to spherical ( r, l ,j)
coordinates as given by x = r cos l cos j , y = r cos l sin f , and z = r sin l . Note that l
corresponds to elevation or latitude while j 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, l , j )
For the purposes of toolbox syntax, use l for l and f for j . 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])
2-9
2 Using Symbolic Math Toolbox Software
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).
df diff(f, a)
da
diff(f, b, 2)
d2 f
db2
2-10
Functional Derivatives Tutorial
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
illustrate 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, 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 energies are a function of
its displacement from rest S(x,t), which varies with position x and time t. If d is the
density per unit length, the kinetic energy is
2-11
2 Using Symbolic Math Toolbox Software
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) = int(d/2*diff(S,t)^2,x,0,L);
V(x,t) = int(r/2*diff(S,x)^2,x,0,L);
The action 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) =
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) =
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.
2-12
Functional Derivatives Tutorial
eqn2(x, t) =
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
eqn4 = tmp(2) == C
eqn3 =
diff(V(t), t, t)/(v^2*V(t)) == C
eqn4 =
diff(U(x), x, x)/U(x) == C
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)
U(x) = simplify(U(x),'Steps',50)
V(t) =
-2*C3*sinh(C^(1/2)*t*v)
U(x) =
-2*C6*sinh(C^(1/2)*x)
2-13
2 Using Symbolic Math Toolbox Software
p1 = setdiff(symvar(U(x)),sym([C,x]))
p2 = setdiff(symvar(V(t)),sym([C,v,t]))
p1 =
C6
p2 =
C3
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)
assume(cond)
solC =
-(k^2*pi^2)/L^2
param =
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)]);
2-14
Functional Derivatives Tutorial
The parameters p1 and p2 determine the amplitude of the vibrations. Set p1 and p2 to 1
for simplicity.
S(x, t) =
-4*sin(pi*k*t)*sin(pi*k*x)
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 = subs(S,t,0.3);
figure(1)
hold on
grid on
tmp = children(S);
ymin = double(tmp(3));
for i = 1:4
yplot = subs(Splot,param,i);
fplot(yplot,[0 Length])
end
ylim([ymin -ymin])
legend('k = 1','k = 2','k = 3','k = 4','Location','best')
xlabel('Position (x)')
ylabel('Displacement (S)')
title('Modes of a string')
2-15
2 Using Symbolic Math Toolbox Software
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
2-16
Functional Derivatives Tutorial
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)
fplot(subs(1/5*symsum(S,param,1,5),t,0.3),[0 Length])
ylim([ymin -ymin])
grid on
xlabel('Position (x)')
ylabel('Displacement (S)')
title('Summation of first 5 modes')
The figure shows that summing modes allows you to model a qualitatively different
waveform. Here, we specified the initial condition is for all .
2-17
2 Using Symbolic Math Toolbox Software
The appropriate summation of modes can represent any waveform, which is the same as
using the Fourier series to represent the string's motion.
2-18
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')
2-19
2 Using Symbolic Math Toolbox Software
x
lim ,
x 0- x
enter
syms x
limit(x/abs(x), x, 0, 'left')
ans =
-1
2-20
Limits
x
lim = 1,
x 0+ x
enter
syms x
limit(x/abs(x), x, 0, 'right')
ans =
1
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.
lim f ( x) limit(f, x, a) or
x a
limit(f, a)
lim f ( x) limit(f, x, a, 'left')
x a-
2-21
2 Using Symbolic Math Toolbox Software
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.
g(t)dt = sin(at + b) / a
int(besselj(1, z)) or int(besselj(1, z),
J1 (z)dz = - J0 ( z) z)
2-22
Integration
The software could find the antiderivative on a larger computer, but runs out of time
or memory on the available machine.
f int(f)
syms x n int(f)
f = x^n;
ans =
piecewise(n == -1, log(x), n ~= -1,...
x^(n + 1)/(n + 1))
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.
2-23
2 Using Symbolic Math Toolbox Software
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
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
syms z
a = int(besselj(1,z)^2,0,1)
2-24
Integration
return
a =
hypergeom([3/2, 3/2], [2, 5/2, 3], -1)/12
a = double(a)
returns
a =
0.0717
2
e-ax
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, using the following commands:
syms x
a = sym(1/2);
f = exp(-a*x^2);
fplot(f)
2-25
2 Using Symbolic Math Toolbox Software
- ax 2
e dx
-
syms a
assume(a > 0)
2-26
Integration
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)
1
a + x2
2
dx
-
syms a x clear
f = 1/(a^2 + x^2);
F = int(f, x, -inf, inf)
syms is used with the clear option to clear the all assumptions on a. For more
information about symbolic variables and assumptions on them, see Delete Symbolic
Objects and Their Assumptions on page 1-28.
F =
(pi*signIm(1i/a))/a
2-27
2 Using Symbolic Math Toolbox Software
signIm = 1 signIm = 1
x
signIm = 0
signIm = -1 signIm = -1
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
syms u
f = besseli(5,25*x).*exp(-x*25);
fun = @(u)besseli(5,25*u).*exp(-u*25);
2-28
Integration
usingIntegral =
NaN
usingVpaintegral =
0.688424
2-29
2 Using Symbolic Math Toolbox Software
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 2-30
Computational Speed of symsum versus sum on page 2-31
Output Format Differences Between symsum and sum on page 2-31
10
1
S= k2 .
Consider the definite sum k= 1 First, find the terms of the definite sum by
substituting the 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 = symsum(f, k, 1, 10)
S_symsum =
2-30
Symbolic Summation
1968329/1270080
You can demonstrate that symsum can be faster than sum by summing a large definite
100000
S= k2 .
series such as k=1
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.
2-31
2 Using Symbolic Math Toolbox Software
isAlways(S_sum == S_symsum)
ans =
logical
1
2-32
Taylor Series
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):
f ( n) ( a)
(x - a)n n!
.
n =0
The command
pretty(T)
6 4 2
49 x 5 x 2 x 1
------ + ---- + ---- + -
131220 1458 81 9
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.
2-33
2 Using Symbolic Math Toolbox Software
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')
2-34
Taylor Series
Special thanks is given to Professor Gunnar Bckstrm of UMEA in Sweden for this
example.
2-35
2 Using Symbolic Math Toolbox Software
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
( x - x0 ) p (a0 + a1 ( x - x0 ) + ... + am ( x - x0 )
m
).
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 )
t + y( t) = ax ( t ) .
dt
2-36
Pad Approximant
F = tau*diff(y)+y == a*x;
F = laplace(F,t,s)
F =
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 =
F = simplify(F)
F =
For readability, replace the Laplace transforms of x(t) and y(t) with xS(s) and
yS(s).
F =
yS(s)*(s*tau + 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).
2-37
2 Using Symbolic Math Toolbox Software
F = F/xS(s);
F = subs(F,yS(s)/xS(s),H(s))
F =
H(s)*(s*tau + 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*tau + 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 =
exp(-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*exp(-3*s))/(s*(s*tau + 1))
2-38
Pad Approximant
To allow plotting of the response, set parameters a and tau to their 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.
stepPade22 =
Find the response to the input by multiplying the transfer function and the Pad
approximant of the input.
yPade22 = H(s)*stepPade22
yPade22 =
yPade22 = ilaplace(yPade22,s)
yPade22 =
To plot the response, set parameters a and tau to their values of 1 and 3, respectively.
yPade22 =
2-39
2 Using Symbolic Math Toolbox Software
(9*exp(-s))/4 - (11*exp(-s/3))/4 + 1
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')
2-40
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 =
yPade22Rel =
yPade22Rel =
yPade22Rel =
2-41
2 Using Symbolic Math Toolbox Software
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])
yPade45 = H(s)*stepPade45
yPade45 = subs(yPade45,[a tau],[1 3])
yPade45 = ilaplace(yPade45)
yPade45 = vpa(yPade45)
fplot(yPade45,[0 20])
title('Pade Approximant for dead-time step input')
legend('Response to dead-time step input',...
'Pade approximant [2 2]',...
'Relative Pade approximant [2 2]',...
2-42
Pad Approximant
stepPade45 =
yPade45 =
yPade45 =
yPade45 =
yPade45 =
3.2418384981662546679005910164486*exp(-1.930807068546914778929595950184*t)*cos(0.578156
2-43
2 Using Symbolic Math Toolbox Software
2-44
Find Asymptotes, Critical and Inflection Points
In this section...
Define a Function on page 2-45
Find Asymptotes on page 2-46
Find Maximum and Minimum on page 2-47
Find Inflection Point on page 2-49
Define a Function
The function in this example is
3 x2 + 6 x - 1
f ( x) = .
x2 + x - 3
syms x
num = 3*x^2 + 6*x -1;
denom = x^2 + x - 3;
f = num/denom
f =
(3*x^2 + 6*x - 1)/(x^2 + x - 3)
Plot the function f by using fplot. The fplot function automatically shows horizontal
asymptotes.
fplot(f)
2-45
2 Using Symbolic Math Toolbox Software
Find Asymptotes
To mathematically find the horizontal asymptote of f, 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.
2-46
Find Asymptotes, Critical and Inflection Points
To find the vertical asymptotes of f, set the denominator equal to 0 and solve by entering
the following command:
roots = solve(denom)
roots =
- 13^(1/2)/2 - 1/2
13^(1/2)/2 - 1/2
-1 + 13
x= ,
2
and
-1 - 13
x= .
2
f1 = diff(f)
f1 =
(6*x + 6)/(x^2 + x - 3) - ((2*x + 1)*(3*x^2 + 6*x - 1))/(x^2 + x - 3)^2
f1 = simplify(f1)
f1 =
-(3*x^2 + 16*x + 17)/(x^2 + x - 3)^2
2-47
2 Using Symbolic Math Toolbox Software
pretty(f1)
which returns
2
3 x + 16 x + 17
- ----------------
2 2
(x + x - 3)
Next, set the derivative equal to 0 and solve for the critical points:
crit_pts = solve(f1)
crit_pts =
- 13^(1/2)/3 - 8/3
13^(1/2)/3 - 8/3
-8 - 13
x1 = ,
3
-8 + 13
x2 = .
3
Note MATLAB does not always return the roots to an equation in the same order.
You can plot the maximum and minimum of f with the following commands:
fplot(f)
hold on
plot(double(crit_pts), double(subs(f,crit_pts)),'ro')
2-48
Find Asymptotes, Critical and Inflection Points
f2 = diff(f1);
inflec_pt = solve(f2,'MaxDegree',3);
double(inflec_pt)
2-49
2 Using Symbolic Math Toolbox Software
This returns
ans =
-5.2635 + 0.0000i
-1.3682 - 0.8511i
-1.3682 + 0.8511i
In this example, only the first entry is a real number, so this is the only inflection point.
(Note that in other examples, the real solutions might not be the first entries of the
answer.) Since you are only interested in the real solutions, you can discard the last two
entries, which are complex numbers.
inflec_pt = inflec_pt(1);
pretty(simplify(inflec_pt))
Plot the inflection point. The extra argument, [-9 6], in fplot extends the range of
x values in the plot so that you see the inflection point more clearly, as shown in the
following figure.
2-50
Find Asymptotes, Critical and Inflection Points
2-51
2 Using Symbolic Math Toolbox Software
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 2-60.
ans =
x + 1
ans =
x^12 - 1
2-52
Simplify Symbolic Expressions
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))
ans =
exp(x + y)
ans =
0
ans =
exp(x/2) - 1
ans =
0
ans =
(2*besselj(1, x))/x
f(x, y) =
exp(x)*exp(y)
2-53
2 Using Symbolic Math Toolbox Software
f(x, y) =
exp(x + y)
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 withIgnoreAnalyticConstraints, you get the result with combined
logarithms.
simplify(log(x^2) + log(x),'IgnoreAnalyticConstraints',true)
ans =
3*log(x)
ans =
log(x^3)
2-54
Simplify Symbolic Expressions
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 want to simplify it further.
The more efficient approach is to simplify the result instead of simplifying the original
expression.
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));
y = simplify(y)
y =
(sin(4*x)*(exp(x) - 1))/(2*cos(4*x)*(exp(x) + 1))
y = simplify(y,'Steps',25)
y =
(tan(4*x)*(exp(x) - 1))/(2*(exp(x) + 1))
y = simplify(y,'Steps',50)
2-55
2 Using Symbolic Math Toolbox Software
y =
(tan(4*x)*tanh(x/2))/2
syms n
simplify(sin(2*n*pi))
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
syms n clear
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
2-56
Simplify Symbolic Expressions
ans =
(x^2 - 2*x*y + y^2)/(x^2 - x*y + y^2)
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)
2-57
2 Using Symbolic Math Toolbox Software
syms x
s = solve(sqrt(x) + 1/x == 1, x)
s =
(1/(18*(25/54 - (23^(1/2)*108^(1/2))/108)^(1/3)) -...
(3^(1/2)*(1/(9*(25/54 - (23^(1/2)*108^(1/2))/108)^(1/3)) -...
(25/54 - (23^(1/2)*108^(1/2))/108)^(1/3))*1i)/2 +...
(25/54 - (23^(1/2)*108^(1/2))/108)^(1/3)/2 + 1/3)^2
...
((3^(1/2)*(1/(9*(25/54 - (23^(1/2)*108^(1/2))/108)^(1/3)) -...
(25/54 - (23^(1/2)*108^(1/2))/108)^(1/3))*1i)/2 + 1/(18*(25/54 -...
(23^(1/2)*108^(1/2))/108)^(1/3)) +...
(25/54 - (23^(1/2)*108^(1/2))/108)^(1/3)/2 + 1/3)^2
The returned result is a long expression that might be difficult to parse. To represent
it in a more familiar typeset form, use pretty. When displaying results, the pretty
function can use abbreviations to shorten long expressions.
pretty(s)
/ / 1 #2 1 \2 \
| | ----- - #1 + -- + - | |
| \ 18 #2 2 3 / |
| |
| / 1 #2 1 \2 |
| | #1 + ----- + -- + - | |
\ \ 18 #2 2 3 / /
where
/ 1 \
sqrt(3) | ---- - #2 | 1i
\ 9 #2 /
#1 == ------------------------
2
2-58
Abbreviate Common Terms in Long Expressions
#2 == | -- - ------------------ |
\ 54 108 /
subexpr is another function that you can use to shorten long expressions. This function
abbreviates only one common subexpression and, unlike pretty, it does not support
nested abbreviations. It 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 s by
variable t.
[s1,t] = subexpr(s,'t')
s1 =
(1/(18*t^(1/3)) - (3^(1/2)*(1/(9*t^(1/3)) -...
t^(1/3))*1i)/2 + t^(1/3)/2 + 1/3)^2
...
((3^(1/2)*(1/(9*t^(1/3)) - t^(1/3))*1i)/2 +...
1/(18*t^(1/3)) + t^(1/3)/2 + 1/3)^2
t =
25/54 - (23^(1/2)*108^(1/2))/108
For the syntax with one input argument, subexpr uses variable sigma to abbreviate
the common subexpression. Output arguments do not affect the choice of abbreviation
variable.
[s2,sigma] = subexpr(s)
s2 =
(1/(18*sigma^(1/3)) - (3^(1/2)*(1/(9*sigma^(1/3)) -...
sigma^(1/3))*1i)/2 + sigma^(1/3)/2 + 1/3)^2
...
((3^(1/2)*(1/(9*sigma^(1/3)) - sigma^(1/3))*1i)/2 +...
1/(18*sigma^(1/3)) + sigma^(1/3)/2 + 1/3)^2
sigma =
25/54 - (23^(1/2)*108^(1/2))/108
2-59
2 Using Symbolic Math Toolbox Software
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:
abac = ab + c
2-60
Choose Function to Rearrange Expression
acbc = (ab)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 these square roots because the identity is not valid for
negative values of variables.
combine(sqrt(x)*sqrt(y))
ans =
x^(1/2)*y^(1/2)
combine(sqrt(x)*sqrt(y),'IgnoreanalyticConstraints',true)
ans =
(x*y)^(1/2)
assume([x,y],'positive')
combine(sqrt(x)*sqrt(y))
ans =
(x*y)^(1/2)
syms x y clear
As target functions, combine accepts atan, exp, gamma, int, log, sincos, and
sinhcosh.
2-61
2 Using Symbolic Math Toolbox Software
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
this expression containing exponentials.
expand(exp(x + y)*(x + exp(x - y)))
ans =
exp(2*x) + x*exp(x)*exp(y)
Expand this 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)
ans =
log(a) + log(b) + log(c)
expand also works on trigonometric expressions. For example, expand this expression.
2-62
Choose Function to Rearrange 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
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)
2-63
2 Using Symbolic Math Toolbox Software
ans =
[ x - 3, x - 1, x - 2]
ans =
x^3 - 6*x^2 + 11*x - 5
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.
factor((log(x)^2 - 1)/(cos(x)^2 - sin(x)^2))
ans =
[ log(x) - 1, log(x) + 1, 1/(cos(x) - sin(x)), 1/(cos(x) + sin(x))]
2-64
Choose Function to Rearrange Expression
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]
syms x y
f = exp(3*x)*y^3 + exp(2*x)*y^2 + exp(x)*y;
expr = children(f)
expr =
[ y^2*exp(2*x), y^3*exp(3*x), y*exp(x)]
Extract the subexpressions of expr(1) by calling children repeatedly. When the input
to children is a vector, the output is a cell array.
expr1 = children(expr(1))
expr2 = children(expr1)
expr1 =
[ y^2, exp(2*x)]
expr2 =
2-65
2 Using Symbolic Math Toolbox Software
12 cell array
[12 sym] [11 sym]
expr2{1}
expr2{2}
ans =
[ y, 2]
ans =
2*x
syms x y z
collect(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, 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.
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.
ans =
(3*x^3*y^4 + y)*z^2 + (x + 5*x*y + x^2*y)*z + 2*x^3 + x*y^4
2-66
Choose Function to Rearrange Expression
If you do not specify variables that collect must consider as unknowns, the function
uses symvar to determine the default variable.
collect(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)
ans =
(3*y^4*z^2 + 2)*x^3 + (y*z)*x^2 + (y^4 + 5*z*y + z)*x + y*z^2
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)
2-67
2 Using Symbolic Math Toolbox Software
ans =
(exp(-x*1i)*1i)/2 - (exp(x*1i)*1i)/2
rewrite(cos(x),'exp')
ans =
exp(-x*1i)/2 + exp(x*1i)/2
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
2-68
Choose Function to Rearrange Expression
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]
syms x y
simplifyFraction((x^3 + 3*y^2)/(x^2 - y^2) + 3)
ans =
(x^3 + 3*x^2)/(x^2 - y^2)
ans =
x - y
ans =
exp(x) + exp(y)
2-69
2 Using Symbolic Math Toolbox Software
syms x
horner(x^3 - 6*x^2 + 11*x - 6)
ans =
x*(x*(x - 6) + 11) - 6
ans =
x*((33*x)/10 + 11/5) + 11/10
vpa(ans)
ans =
x*(3.3*x + 2.2) + 1.1
2-70
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) =
2-71
2 Using Symbolic Math Toolbox Software
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,d] = numden(x/y + y/x)
n =
x^2 + y^2
d =
x*y
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]
2-72
Substitute Variables in Symbolic Expressions
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')
2-73
2 Using Symbolic Math Toolbox Software
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.
subs(solx, params, 2)
ans =
(5*pi)/2
(23*pi)/6
(31*pi)/6
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
2-74
Substitute Elements in Symbolic Matrices
M =
[ a, b, c]
[ b, c, a]
[ c, a, b]
Replace variable b in this matrix 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)
M =
[ a, a + 1, c]
[ a + 1, c, a]
[ c, a, a + 1]
You also can specify the value to replace by indexing into matrix. That is, to replace all
elements whose value is c, you can specify the value to replace as c, M(1,3) or M(3,1).
M =
[ a, a + 1, a + 2]
[ a + 1, a + 2, a]
[ a + 2, a, a + 1]
Tip 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 =
2-75
2 Using Symbolic Math Toolbox Software
E =
[ 3*a + 3, 0, 0]
[ 0, 3^(1/2), 0]
[ 0, 0, -3^(1/2)]
subs(E, a, 1)
ans =
[ 6, 0, 0]
[ 0, 3^(1/2), 0]
[ 0, 0, -3^(1/2)]
2-76
Substitute Scalars with Matrices
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)
2-77
2 Using Symbolic Math Toolbox Software
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])
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)]
2-78
Use subs to Evaluate Expressions and Functions
Evaluate Expressions
Evaluation is one of the most common mathematical operations. Therefore, it is
important to understand how and when Symbolic Math Toolbox performs evaluations.
For example, create a symbolic variable, x, and then assign the expression x^2 to
another variable, y.
syms x
y = x^2;
x = 2;
This second assignment does not change the value of y, which is still x^2. If later you
change the value of x to some other number, variable, expression, or matrix, the toolbox
remembers that the value of y is defined as x^2. When displaying results, Symbolic Math
Toolbox does not automatically evaluate the value of x^2 according to the new value of x.
y =
x^2
To enforce evaluation of y according to the new value of x, use the subs function.
subs(y)
ans =
4
The displayed value (assigned to ans) is now 4. However, the value of y does not change.
To replace the value of y, assign the result returned by subs to y.
y = subs(y)
2-79
2 Using Symbolic Math Toolbox Software
y =
4
x = 5;
subs(y)
ans =
4
Evaluate Functions
Create a symbolic function and assign an expression to it.
syms f(x)
f(x) = x^2;
x = 2;
The function itself does not change: the body of the function is still the symbolic
expression x^2.
f(x) =
x^2
fnew = subs(f)
fnew(x) =
4
The function call, f(x), returns the value of f for the current value of x. For example,
if you assigned the value 2 to the variable x, then calling f(x) is equivalent to calling
f(2).
2-80
Use subs to Evaluate Expressions and Functions
f2 = f(x)
f2 =
4
f2 = f(2)
f2 =
4
f
[f(1),f(2),f(3)]
f(x) =
x^2
ans =
[ 1, 4, 9]
2-81
2 Using Symbolic Math Toolbox Software
a = b = ans =
pi 3.1415926535897932384626433832795
3.1416
ans = ans = ans =
0 -3.2101083013100396069547145883568e-40
1.2246e-16
Functions Used sym vpa double
digits
Round-Off Errors No, finds exact Yes, magnitude Yes, has 16 digits of
results depends on precision precision
used
Speed Slowest Faster, depends on Faster
precision used
Memory Usage Greatest Adjustable, depends Least
on precision used
Symbolic Arithmetic
By default, Symbolic Math Toolbox uses exact numbers, such as 1/3, sqrt(2), or pi, to
perform exact symbolic computations on page 1-12.
Variable-Precision Arithmetic
Variable-precision arithmetic using vpa is the recommended approach for numeric
calculations in Symbolic Math Toolbox. For greater precision, increase the number of
significant digits on page 2-84. For faster computations and decreased memory usage,
decrease the number of significant digits on page 2-91.
2-82
Choose Symbolic or Numeric Arithmetic
Double-Precision Arithmetic
Double-precision, floating-point arithmetic uses the same precision as most numeric
computations in MATLAB. 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 numbers and variable-precision arithmetic are recommended.
To approximate a value with double precision, use the double function.
2-83
2 Using Symbolic Math Toolbox Software
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
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 = 32
2-84
Increase Precision of Numeric Calculations
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
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 2-91.
2-85
2 Using Symbolic Math Toolbox Software
In this section...
Use Symbolic Computations When Possible on page 2-86
Perform Calculations with Increased Precision on page 2-87
Compare Symbolic and Numeric Results on page 2-89
Plot the Function or Expression on page 2-89
pi
sym(pi)
ans =
3.1416
ans =
pi
heaviside(sin(sym(pi)))
heaviside(sin(pi))
ans =
1/2
2-86
Recognize and Avoid Round-Off Errors
ans =
1
syms y
fplot(abs(zeta(1/2 + i*y)), [0 30])
2-87
2 Using Symbolic Math Toolbox Software
Use the numeric solver vpasolve to approximate the first three zeros of this Zeta
function:
ans =
14.134725141734693790457251983562
ans =
21.022039638771554992628479593897
ans =
25.010857580145688763213790992563
Now, consider the same function, but slightly increase the real part,
1000000001
z + iy . According to the Riemann hypothesis, this function does not have a
2000000000
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
Increasing the number of digits shows that the result is incorrect. The Zeta function
1000000001
z + 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)
2-88
Recognize and Avoid Round-Off Errors
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
B = besselj(53/2, sym(pi));
2-89
2 Using Symbolic Math Toolbox Software
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])
2-90
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;
tic
zeta(C);
toc
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));
2-91
2 Using Symbolic Math Toolbox Software
C = X + Y*i;
digits(10)
vpaC = vpa(C);
tic
zeta(vpaC);
toc
tic
zeta(C);
toc
Note: If you want to increase precision, see Increase Precision of Numeric Calculations
on page 2-84.
2-92
Numeric to Symbolic Conversion
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
sym determines that the double-precision value 0.1 approximates the exact symbolic
value 1/10. In general, sym tries to correct the round-off error in floating-point inputs
to return the exact symbolic form. Specifically, sym corrects round-off error in 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.
For these forms, demonstrate that sym converts floating-point inputs to the exact
symbolic form. First, numerically approximate 1/7, pi, and 1 / 2 .
N1 = 1/7
N2 = pi
N3 = 1/sqrt(2)
N1 =
0.1429
N2 =
3.1416
N3 =
0.7071
Convert the numeric approximations to exact symbolic form. sym corrects the round-off
error.
S1 = sym(N1)
S2 = sym(N2)
S3 = sym(N3)
S1 =
2-93
2 Using Symbolic Math Toolbox Software
1/7
S2 =
pi
S3 =
2^(1/2)/2
To return the error between the input and the estimated exact form, use the syntax
sym(num,'e'). See Conversion to Rational Symbolic Form with Error Term on page
2-95.
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)
sym('1333333333333333333')
ans =
1333333333333333248
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.
In this section...
Conversion to Rational Symbolic Form on page 2-95
Conversion by Using Floating-Point Expansion on page 2-95
Conversion to Rational Symbolic Form with Error Term on page 2-95
Conversion to Decimal Form on page 2-95
2-94
Numeric to Symbolic Conversion
ans =
1/10
ans =
3602879701896397/36028797018963968
Convert t to symbolic form. Return the error between its estimated symbolic form and its
floating-point value.
sym(t, 'e')
ans =
eps/40 + 1/10
The error term eps/40 is the difference between sym('0.1') and sym(0.1).
2-95
2 Using Symbolic Math Toolbox Software
sym(t,'d')
ans =
0.10000000000000000555111512312578
digitsOld = digits(7);
sym(t,'d')
ans =
0.1
digits(digitsOld)
2-96
Basic Algebraic Operations
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)]
2-97
2 Using Symbolic Math Toolbox Software
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)
I =
[ 1, 0]
[ 0, 1]
2-98
Linear Algebraic Operations
2-99
2 Using Symbolic Math Toolbox Software
The command
H = hilb(3)
generates the 3-by-3 Hilbert matrix. With format short, MATLAB prints
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. Indeed, H is a MATLAB array of class double. Converting H to a symbolic
matrix
H = sym(H)
gives
H =
[ 1, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
inv(H)
produces
ans =
[ 9, -36, 30]
[ -36, 192, -180]
[ 30, -180, 180]
and
det(H)
yields
ans =
1/2160
2-100
Linear Algebraic Operations
You can use the backslash operator to solve a system of simultaneous linear equations.
For example, the commands
% Solve Hx = b
b = [1; 1; 1];
x = H\b
All three of these results, the inverse, the determinant, and the solution to the linear
system, are the exact results corresponding to the infinitely precise, rational, Hilbert
matrix. On the other hand, using digits(16), the command
digits(16)
V = vpa(hilb(3))
returns
V =
[ 1.0, 0.5, 0.3333333333333333]
[ 0.5, 0.3333333333333333, 0.25]
[ 0.3333333333333333, 0.25, 0.2]
The decimal points in the representation of the individual elements are the signal to use
variable-precision arithmetic. The result of each arithmetic operation is rounded to 16
significant decimal digits. When inverting the matrix, these errors are magnified by the
matrix condition number, which for hilb(3) is about 500. Consequently,
inv(V)
which returns
ans =
[ 9.0, -36.0, 30.0]
[ -36.0, 192.0, -180.0]
[ 30.0, -180.0, 180.0]
2-101
2 Using Symbolic Math Toolbox Software
which gives
ans =
2160.000000000018
and
V\b
which is
ans =
3.0
-24.0
30.0
null(H)
ans =
Empty sym: 1-by-0
colspace(H)
ans =
[ 1, 0, 0]
[ 0, 1, 0]
[ 0, 0, 1]
A more interesting example, which the following code shows, is to find a value s for
H(1,1) that makes H singular. The commands
syms s
H(1,1) = s
Z = det(H)
sol = solve(Z)
produce
2-102
Linear Algebraic Operations
H =
[ 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
Then
H = subs(H, s, sol)
returns
ans =
0
and
inv(H)
because H is singular. For this matrix, null space and column space are nontrivial:
Z = null(H)
C = colspace(H)
Z =
2-103
2 Using Symbolic Math Toolbox Software
3/10
-6/5
1
C =
[ 1, 0]
[ 0, 1]
[ -3/10, 6/5]
It should be pointed out that even though H is singular, vpa(H) is not. For any integer
value d, setting digits(d), and then computing inv(vpa(H)) results in an inverse
with elements on the order of 10^d.
2-104
Eigenvalues
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 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]
Td = double(T)
Ed = double(E)
return
2-105
2 Using Symbolic Math Toolbox Software
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
64 253
eigenvalues are the result of applying the quadratic formula to x2 - x+ which is
45 2160
the quadratic factor in factor(charpoly(H, x)):
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]
2-106
Eigenvalues
The commands
p = charpoly(R, x);
pretty(factor(p))
produce
( 2 2 )
x, x - 1020, x - 1040500, x - 1020 x + 100, x - 1000, x - 1000
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
S = R;
S(1,8) = 30;
S(8,1) = 30;
you find
p =
x^8 - 4040*x^7 + 5079941*x^6 + 82706090*x^5...
- 5327831918568*x^4 + 4287832912719760*x^3...
2-107
2 Using Symbolic Math Toolbox Software
- 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,
2-108
Eigenvalues
exp(-t*1i)/2 + exp(t*1i)/2]
G = simplify(G)
G =
[ cos(t), sin(t)]
[ -sin(t), cos(t)]
produces
g =
cos(t) - sin(t)*1i
cos(t) + sin(t)*1i
g = rewrite(g, 'exp')
g =
exp(-t*1i)
exp(t*1i)
2-109
2 Using Symbolic Math Toolbox Software
[V,J] = jordan(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 =
[ 12, 32, 66, 116]
[ -25, -76, -164, -294]
[ 21, 66, 143, 256]
[ -6, -19, -41, -73]
Then
[V,J] = jordan(A)
produces
2-110
Jordan Canonical Form
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.
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 - l1 I ) v2 = v1
( A - l2 I ) v4 = v3 .
2-111
2 Using Symbolic Math Toolbox Software
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)
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-112
Singular Value Decomposition
[ 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
[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]
2-113
2 Using Symbolic Math Toolbox Software
In this section...
Solve an Equation on page 2-114
Return the Full Solution to an Equation on page 2-115
Work with the Full Solution, Parameters, and Conditions Returned by solve on page
2-115
Visualize and Plot Solutions Returned by solve on page 2-116
Simplify Complicated Results and Improve Performance on page 2-118
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 =
2-114
Solve Algebraic Equation
-(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 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.
2-115
2 Using Symbolic Math Toolbox Software
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
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
fplot(cos(x))
hold on
2-116
Solve Algebraic Equation
grid on
fplot(-sin(x))
title('Both sides of equation cos(x) = -sin(x)')
legend('cos(x)','-sin(x)','Location','Best')
Calculate the values of the functions at the values of x, and superimpose the solutions as
points using scatter.
yvalues = cos(xvalues)
scatter(xvalues, yvalues)
yvalues =
2-117
2 Using Symbolic Math Toolbox Software
-0.70710678118654752440084436210485
0.70710678118654752440084436210485
-0.70710678118654752440084436210485
0.70710678118654752440084436210485
2-118
Select Numeric or Symbolic Solver
Solve Equations Symbolically Using solve Solve Equations Numerically Using vpasolve
Returns exact solutions. Solutions can then Returns approximate solutions. Precision
be approximated using vpa. can be 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 Numeric solutions provide less insight.
solution.
Runs slower. Runs faster.
Search ranges can be specified using Search ranges and starting points can be
inequalities. specified.
solve solves equations and inequalities vpasolve does not solve inequalities,
that contain parameters. nor does it 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-84.
See Also
solve | vpasolve
Related Examples
Solve Algebraic Equation on page 2-114
2-119
2 Using Symbolic Math Toolbox Software
2-120
Solve System of Algebraic Equations
In this section...
Handle the Output of solve on page 2-121
Solve a Linear System of Equations on page 2-123
Return the Full Solution of a System of Equations on page 2-124
Solve a System of Equations Under Conditions on page 2-126
Work with Solutions, Parameters, and Conditions Returned by solve on page 2-127
Convert Symbolic Results to Numeric Values on page 2-130
Simplify Complicated Results and Improve Performance on page 2-131
x2 y2 = 0
y
x - = a,
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.
[solx,soly] = solve(x^2*y^2 == 0, x-y/2 == a)
2-121
2 Using Symbolic Math Toolbox Software
-2*a
0
Modify the first equation to x2y2=1. The new system has more solutions.
[solx,soly] = solve(x^2*y^2 == 1, x-y/2 == a)
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.
syms u v a
S = solve(u^2 - v^2 == a^2, u + v == 1, a^2 - 2*a == 3)
a: [21 sym]
u: [21 sym]
v: [21 sym]
2-122
Solve System of Algebraic Equations
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]
[A,b] = equationsToMatrix(eqns,x,y);
z = A\b
sol =
(2*v)/3 - (5*u)/3
2-123
2 Using Symbolic Math Toolbox Software
(4*u)/3 - v/3
z =
(2*v)/3 - (5*u)/3
(4*u)/3 - v/3
Thus,sol and z produce the same solution, although the results are assigned to different
variables.
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;
2-124
Solve System of Algebraic Equations
a.YTickLabel = M;
title('Plot of System of Equations')
legend('sin(x)+cos(y) == 4/5','sin(x)*cos(y) == 1/10', 'Location', 'best')
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 =
struct with fields:
x: [21 sym]
2-125
2 Using Symbolic Math Toolbox Software
y: [21 sym]
parameters: [12 sym]
conditions: [21 sym]
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.
ans =
z1
z1
ans =
z
z
ans =
[ z, z1]
ans =
(in((z - acos(6^(1/2)/10 + 2/5))/(2*pi), 'integer') |...
in((z + acos(6^(1/2)/10 + 2/5))/(2*pi), 'integer')) &...
(in(-(pi - z1 + asin(6^(1/2)/10 - 2/5))/(2*pi), 'integer') |...
in((z1 + asin(6^(1/2)/10 - 2/5))/(2*pi), 'integer'))
(in((z1 - asin(6^(1/2)/10 + 2/5))/(2*pi), 'integer') |...
in((z1 - pi + asin(6^(1/2)/10 + 2/5))/(2*pi), 'integer')) &...
(in((z - acos(2/5 - 6^(1/2)/10))/(2*pi), 'integer') |...
in((z + acos(2/5 - 6^(1/2)/10))/(2*pi), 'integer'))
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);
2-126
Solve System of Algebraic Equations
scatter(Srange.x, Srange.y,'k')
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.
2-127
2 Using Symbolic Math Toolbox Software
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 =
z1
paramy =
z
solparamx =
[ pi + asin(6^(1/2)/10 - 2/5), asin(6^(1/2)/10 - 2/5) - pi,
-asin(6^(1/2)/10 - 2/5), - 2*pi - asin(6^(1/2)/10 - 2/5)]
solparamy =
[ acos(6^(1/2)/10 + 2/5), acos(6^(1/2)/10 + 2/5) - 2*pi,
-acos(6^(1/2)/10 + 2/5), 2*pi - acos(6^(1/2)/10 + 2/5)]
ans =
Empty sym: 1-by-0
Solve the second solution to x and y for the parameters paramx and paramy.
2-128
Solve System of Algebraic Equations
solparamx =
[ pi + asin(6^(1/2)/10 - 2/5), asin(6^(1/2)/10 - 2/5) - pi,
-asin(6^(1/2)/10 - 2/5), - 2*pi - asin(6^(1/2)/10 - 2/5)]
[ asin(6^(1/2)/10 + 2/5), pi - asin(6^(1/2)/10 + 2/5),
asin(6^(1/2)/10 + 2/5) - 2*pi, - pi - asin(6^(1/2)/10 + 2/5)]
solparamy =
[ acos(6^(1/2)/10 + 2/5), acos(6^(1/2)/10 + 2/5) - 2*pi,
-acos(6^(1/2)/10 + 2/5), 2*pi - acos(6^(1/2)/10 + 2/5)]
[ acos(2/5 - 6^(1/2)/10), acos(2/5 - 6^(1/2)/10) - 2*pi,
-acos(2/5 - 6^(1/2)/10), 2*pi - acos(2/5 - 6^(1/2)/10)]
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 =
[ pi + asin(6^(1/2)/10 - 2/5), asin(6^(1/2)/10 - 2/5) - pi,
-asin(6^(1/2)/10 - 2/5), - 2*pi - asin(6^(1/2)/10 - 2/5)]
[ asin(6^(1/2)/10 + 2/5), pi - asin(6^(1/2)/10 + 2/5),
asin(6^(1/2)/10 + 2/5) - 2*pi, - pi - asin(6^(1/2)/10 + 2/5)]
soly =
[ acos(6^(1/2)/10 + 2/5), acos(6^(1/2)/10 + 2/5) - 2*pi,
-acos(6^(1/2)/10 + 2/5), 2*pi - acos(6^(1/2)/10 + 2/5)]
[ acos(2/5 - 6^(1/2)/10), acos(2/5 - 6^(1/2)/10) - 2*pi,
-acos(2/5 - 6^(1/2)/10), 2*pi - acos(2/5 - 6^(1/2)/10)]
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,:))
2-129
2 Using Symbolic Math Toolbox Software
for j = 1:length(soly(1,:))
scatter(solx(1,i), soly(1,j), 'k')
scatter(solx(2,i), soly(2,j), 'k')
end
end
2-130
Solve System of Algebraic Equations
Use vpa to convert the symbolic solutions solx and soly to numeric form.
vpa(solx)
vpa(soly)
ans =
[ 2.9859135500977407388300518406219,...
-3.2972717570818457380952349259371,...
0.15567910349205249963259154265761,...
-6.1275062036875339772926952239014]
...
[ 0.70095651347102524787213653614929,...
2.4406361401187679905905068471302,...
-5.5822287937085612290531502304097,...
-3.8425491670608184863347799194288]
ans =
[ 0.86983981332387137135918515549046,...
-5.4133454938557151055661016110685,...
-0.86983981332387137135918515549046,...
5.4133454938557151055661016110685]
...
[ 1.4151172233028441195987301489821,...
-4.8680680838767423573265566175769,...
-1.4151172233028441195987301489821,...
4.8680680838767423573265566175769]
2-131
2 Using Symbolic Math Toolbox Software
In this section...
Return Only Real Solutions on page 2-132
Apply Simplification Rules on page 2-132
Use Assumptions to Narrow Results on page 2-133
Simplify Solutions on page 2-135
Tips on page 2-135
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
2-132
Troubleshoot Equation Solutions from solve Function
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)
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)
2-133
2 Using Symbolic Math Toolbox Software
ans =
1
17^(1/2)/2 - 1/2
5*2^(1/2)
5^(1/2) - 1
ans =
1
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);
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.
2-134
Troubleshoot Equation Solutions from solve Function
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
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.
simplify(S, 'Steps', 50)
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.
sym(13)/5
sym(133333333333333333333)/5
sym('133333333333333333333')/5
ans =
13/5
2-135
2 Using Symbolic Math Toolbox Software
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.
2-136
Solve System of Linear Equations
In this section...
Solve System of Linear Equations Using linsolve on page 2-137
Solve System of Linear Equations Using solve on page 2-138
a11 a1n
A= M O M
a
m1 L amn
b
r 1
b= M
b
m
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.
2-137
2 Using Symbolic Math Toolbox Software
2x + y + z = 2
-x + y - z = 3
x + 2 y + 3 z = -10
syms x y z
eqn1 = 2*x + y + z == 2;
eqn2 = -x + y - z == 3;
eqn3 = x + 2*y + 3*z == -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 =
[ 2, 1, 1]
[ -1, 1, -1]
[ 1, 2, 3]
B =
2
3
-10
X = linsolve(A,B)
X =
3
1
-5
2-138
Solve System of Linear Equations
2x + y + z = 2
-x + y - z = 3
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.
sol = solve([eqn1, eqn2, eqn3], [x, y, z]);
xSol = sol.x
ySol = sol.y
zSol = sol.z
xSol =
3
ySol =
1
zSol =
-5
solve returns the solutions in a structure array. To access the solutions, index into the
array.
2-139
2 Using Symbolic Math Toolbox Software
In this section...
Find All Roots of a Polynomial Function on page 2-140
Find Zeros of a Nonpolynomial Function Using Search Ranges and Starting Points on
page 2-141
Obtain Solutions to Arbitrary Precision on page 2-145
Solve Multivariate Equations Using Search Ranges on page 2-146
syms f(x)
f(x) = 6*x^7-2*x^6+3*x^3-8;
sol = vpasolve(f)
sol =
1.0240240759053702941448316563337
- 0.88080620051762149639205672298326 + 0.50434058840127584376331806592405i
- 0.88080620051762149639205672298326 - 0.50434058840127584376331806592405i
- 0.22974795226118163963098570610724 + 0.96774615576744031073999010695171i
- 0.22974795226118163963098570610724 - 0.96774615576744031073999010695171i
0.7652087814927846556172932675903 + 0.83187331431049713218367239317121i
0.7652087814927846556172932675903 - 0.83187331431049713218367239317121i
vpasolve returns seven roots of the function, as expected, because the function is a
polynomial of degree seven.
2-140
Solve Equations Numerically
syms x
h = fplot(exp(x/7)*cos(2*x),[-2 25]);
grid on
2-141
2 Using Symbolic Math Toolbox Software
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, even if multiple zeros exist.
f = exp(-x/20)*cos(2*x);
for i = 1:3
vpasolve(f,x)
end
ans =
19.634954084936207740391521145497
ans =
19.634954084936207740391521145497
ans =
19.634954084936207740391521145497
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 4-1487 on the vpasolve page.
for i = 1:3
vpasolve(f,x,'random',true)
end
ans =
-226.98006922186256147892598444194
ans =
98.174770424681038701957605727484
ans =
58.904862254808623221174563436491
To find a zero close to x=10 and to x=1000, set the starting point to 10, and then to
1000.
vpasolve(f,x,10)
vpasolve(f,x,1000)
ans =
10.210176124166828025003590995658
ans =
999.8118620049516981407362567287
To find a zero in the range 15 x 25 , set the search range to [15 25].
2-142
Solve Equations Numerically
vpasolve(f,x,[15 25])
ans =
21.205750411731104359622842837137
To find multiple zeros in the range [15 25], you cannot call vpasolve repeatedly as it
returns the same result on each call, as previously shown. Instead, set random to true in
conjunction with the search range.
for i = 1:3
vpasolve(f,x,[15 25],'random',true)
end
ans =
21.205750411731104359622842837137
ans =
16.493361431346414501928877762217
ans =
16.493361431346414501928877762217
If you specify the random option while also specifying a starting point, vpasolve warns
you that the two options are incompatible.
vpasolve(f,x,15,'random',true)
Create the function findzeros below to systematically find all zeros for f in a given
search range, within the error tolerance. It starts with the input search range and calls
vpasolve to find a zero. Then, it splits the search range into two around the zeros
value, and recursively calls itself with the new search ranges as inputs to find more
zeros. 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.
Declare the function with the two inputs and one output.
2-143
2 Using Symbolic Math Toolbox Software
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);
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.
2-144
Solve Equations Numerically
Call findzeros with search range [10 20] to find all zeros in that range for f(x) =
exp(-x/20)*cos(2*x), within the default error tolerance.
syms f(x)
f(x) = exp(-x/20)*cos(2*x);
findzeros(f,[10 20])
ans =
[ 10.210176124166828025003590995658, 11.780972450961724644234912687298,...
13.351768777756621263466234378938, 14.922565104551517882697556070578,...
16.493361431346414501928877762217, 18.064157758141311121160199453857,...
19.634954084936207740391521145497]
f = exp(x/7)*cos(2*x);
2-145
2 Using Symbolic Math Toolbox Software
vpasolve(f)
digitsOld = digits;
digits(64)
vpasolve(f)
digits(digitsOld)
ans =
-7.0685834705770347865409476123789
ans =
-7.068583470577034786540947612378881489443631148593988097193625333
z = 10 ( cos ( x) + cos ( y) )
z = x + y2 - 0 .1 x2 y
x + y - 2.7 = 0
A plot of the equations for 0x2.5 and 0x2.5 shows that the three surfaces
intersect in two points. To better visualize the plot, use view. To scale the colormap
values, use caxis.
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)
caxis([-15 10])
2-146
Solve Equations Numerically
Use vpasolve to find a point where the surfaces intersect. The function vpasolve
returns a structure. To access the solution, index into the structure.
sol = vpasolve(equations);
[sol.x sol.y sol.z]
ans =
2-147
2 Using Symbolic Math Toolbox Software
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 in the picture.
Use vpasolve to find a solution for this search range 0 x 1 .5 and 1 .5 y 2.5 . To
omit a search range for z, set the 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]
2-148
Solve Equations Numerically
ans =
To find multiple solutions, you can 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 i = 1:5
temp = vpasolve(equations, vars, range, 'random', true);
sol(i,1) = temp.x;
sol(i,2) = temp.y;
sol(i,3) = temp.z;
end
sol
sol =
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. Scale the colormap to the plot values using caxis, and change
the perspective 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;
2-149
2 Using Symbolic Math Toolbox Software
2-150
Solve a Single Differential Equation
Before using dsolve, create the symbolic function for which you want to solve an
ordinary differential equation. Use sym or syms to create a symbolic function. For
example, create a function y(x):
syms y(x)
To specify initial or boundary conditions, use additional equations. If you do not specify
initial or boundary conditions, the solutions will contain integration constants, such as
C1, C2, and so on.
Call dsolve with the number of output variables equal to the number of dependent
variables.
Place the output in a structure whose fields contain the solutions of the differential
equations.
y(t) =
C2*exp(t^2/2)
Solve the same ordinary differential equation, but now specify the initial condition y(0)
= 2:
2-151
2 Using Symbolic Math Toolbox Software
syms y(t)
y(t) = dsolve(diff(y,t) == t*y, y(0) == 2)
y(t) =
2*exp(t^2/2)
Nonlinear ODE
Nonlinear equations can have multiple solutions, even if you specify initial conditions.
For example, solve this equation:
syms x(t)
x(t) = dsolve((diff(x,t) + x)^2 == 1, x(0) == 0)
results in
x(t) =
exp(-t) - 1
1 - exp(-t)
syms y(x)
Dy = diff(y);
y(x) = dsolve(diff(y, x, x) == cos(2*x) - y, y(0) == 1, Dy(0) == 0);
y(x) = simplify(y)
y(x) =
1 - (8*sin(x/2)^4)/3
Third-Order ODE
Solve this third-order ordinary differential equation:
d3u
=u
dx3
2-152
Solve a Single Differential Equation
Because the initial conditions contain the first- and the second-order derivatives, create
two additional symbolic functions, Dy and D2y to specify these initial conditions:
syms u(x)
Du = diff(u, x);
D2u = diff(u, x, 2);
u(x) = dsolve(diff(u, x, 3) == u, u(0) == 1, Du(0) == -1, D2u(0) == pi)
u(x) =
1
y(0) = 0, y(3) = K1/ 3 ( 2 3)
p
2-153
2 Using Symbolic Math Toolbox Software
See Also
Solve a System of Differential Equations on page 2-155
2-154
Solve a System of Differential Equations
In this section...
Solve System of Differential Equations on page 2-155
Solve Differential Equations in Matrix Form on page 2-157
df
= 3 f + 4 g,
dt
dg
= -4 f + 3 g.
dt
First, create the symbolic functions f(t) and g(t), and then declare the equations.
Solve the system by using dsolve. The dsolve function returns the solutions as
elements of the structure S.
S = dsolve(eqn1, eqn2)
S =
struct with fields:
g: [11 sym]
f: [11 sym]
fSol(t) = S.f
2-155
2 Using Symbolic Math Toolbox Software
gSol(t) = S.g
fSol(t) =
C2*cos(4*t)*exp(3*t) + C1*sin(4*t)*exp(3*t)
gSol(t) =
C1*cos(4*t)*exp(3*t) - C2*sin(4*t)*exp(3*t)
Alternatively, store f(t) and g(t) directly by providing the output arguments as a
vector.
fSol(t) =
C2*cos(4*t)*exp(3*t) + C1*sin(4*t)*exp(3*t)
gSol(t) =
C1*cos(4*t)*exp(3*t) - C2*sin(4*t)*exp(3*t)
Specify initial conditions f(0) == 0 and g(0) == 1, and solve the equations. dsolve
replaces the constants with their values.
c1 = f(0) == 0;
c2 = g(0) == 1;
[fSol(t), gSol(t)] = dsolve(eqn1, eqn2, c1, c2)
fSol(t) =
sin(4*t)*exp(3*t)
gSol(t) =
cos(4*t)*exp(3*t)
fplot(fSol)
hold on
fplot(gSol)
grid on
legend('fSol','gSol','Location','best')
2-156
Solve a System of Differential Equations
dx
= x + 2 y + 1,
dt
dy
= - x + y + t.
dt
2-157
2 Using Symbolic Math Toolbox Software
x 1 2 x 1
= + .
y -1 1 y t
Let
x 1 2 1
Y = ,A = , B = .
y -1 1 t
eqn(t) =
diff(x(t), t) == x(t) + 2*y(t) + 1
diff(y(t), t) == t - x(t) + y(t)
xSol(t) =
2^(1/2)*exp(t)*cos(2^(1/2)*t)*(C2 + (exp(-t)*(4*sin(2^(1/2)*t) +...
2^(1/2)*cos(2^(1/2)*t) + 6*t*sin(2^(1/2)*t) + 6*2^(1/2)*t*cos(2^(1/2)*t)))/18) +...
2^(1/2)*exp(t)*sin(2^(1/2)*t)*(C1 - (exp(-t)*(4*cos(2^(1/2)*t) -...
2^(1/2)*sin(2^(1/2)*t) + 6*t*cos(2^(1/2)*t) - 6*2^(1/2)*t*sin(2^(1/2)*t)))/18)
ySol(t) =
exp(t)*cos(2^(1/2)*t)*(C1 - (exp(-t)*(4*cos(2^(1/2)*t) -...
2^(1/2)*sin(2^(1/2)*t) + 6*t*cos(2^(1/2)*t) -...
6*2^(1/2)*t*sin(2^(1/2)*t)))/18) - exp(t)*sin(2^(1/2)*t)*(C2 +...
(exp(-t)*(4*sin(2^(1/2)*t) + 2^(1/2)*cos(2^(1/2)*t) +...
6*t*sin(2^(1/2)*t) + 6*2^(1/2)*t*cos(2^(1/2)*t)))/18)
xSol(t) = simplify(xSol(t))
2-158
Solve a System of Differential Equations
ySol(t) = simplify(ySol(t))
xSol(t) =
(2*t)/3 + 2^(1/2)*C2*exp(t)*cos(2^(1/2)*t) + 2^(1/2)*C1*exp(t)*sin(2^(1/2)*t) + 1/9
ySol(t) =
C1*exp(t)*cos(2^(1/2)*t) - t/3 - C2*exp(t)*sin(2^(1/2)*t) - 2/9
To find the value of constants, specify initial conditions. When specifying equations in
matrix form, you must specify initial conditions in matrix form too. Otherwise, dsolve
throws an error.
Specify initial conditions f(0) == 2 and g(0) == -1 in matrix form, and solve the
equations. dsolve replaces the constants with their values.
xSol(t) =
(2*t)/3 + (17*exp(t)*cos(2^(1/2)*t))/9 - (7*2^(1/2)*exp(t)*sin(2^(1/2)*t))/9 + 1/9
ySol(t) =
- t/3 - (7*exp(t)*cos(2^(1/2)*t))/9 - (17*2^(1/2)*exp(t)*sin(2^(1/2)*t))/18 - 2/9
clf
fplot(ySol)
hold on
fplot(xSol)
grid on
legend('ySol','xSol','Location','best')
2-159
2 Using Symbolic Math Toolbox Software
See Also
Solve a Single Differential Equation on page 2-151
2-160
Differential Algebraic Equations
F ( x& ( t ) , x ( t ) , t ) = 0
The differential order of a DAE system is the highest differential order of its equations.
The differential order of a differential algebraic equation is the highest derivative of its
state variables.
The differential index of a DAE system is the number of differentiations needed to reduce
the system to a system of ordinary differential equations (ODEs).
2-161
2 Using Symbolic Math Toolbox Software
These preliminary steps help you set up the DAE system using the functions available
in Symbolic Math Toolbox, and then convert the system to numeric function handles
acceptable by MATLAB. After completing these steps, call ode15i, ode15s, or ode23t
while specifying the system by the MATLAB function handles and providing initial
conditions.
2-162
Set Up Your DAE Problem
2-163
2 Using Symbolic Math Toolbox Software
For example, specify the system of equations that describes a two-dimensional pendulum.
The functions x(t) and y(t) are the state variables of the system that describe the
horizontal and vertical positions of the pendulum mass. The function T(t) is the state
variable describing the force that keeps the mass from flying away. The variables
m, r, and g are the mass, length of the rod, and standard surface gravity on Earth,
respectively.
syms x(t) y(t) T(t) m r g;
eqs= [m*diff(x(t), 2) == T(t)/r*x(t), ...
m*diff(y(t), 2) == T(t)/r*y(t) - m*g, ...
x(t)^2 + y(t)^2 == r^2];
2-164
Set Up Your DAE Problem
MATLAB function handle. If you want to use the ode15s or ode23t solver, then use
massMatrixForm to extract the mass matrix and the right sides of the system of
equations. Then, convert the resulting matrix and vector to MATLAB function handles by
using matlabFunction. See Convert DAE Systems to MATLAB Function Handles on
page 2-173.
2-165
2 Using Symbolic Math Toolbox Software
2-166
Reduce Differential Order of DAE Systems
Note: This is the second step in solving a DAE problem. For the sequence of steps for
solving DAE problems, see Set Up Your DAE Problem on page 2-162.
At this step, your DAE system must be specified as a collection of equations and state
variables. For example, this system of equations describes a two-dimensional pendulum.
The functions x(t) and y(t) are the state variables of the system that describe the
horizontal and vertical positions of the pendulum mass. The function T(t) is the state
variable describing the force that keeps the mass from flying away. The variables
m, r, and g are the mass, length of the rod, and standard surface gravity on Earth,
respectively.
The first and second equations have second-order derivatives of the coordinates x and
y. The third equation is an algebraic equation. Thus, the differential order of this DAE
system is 2. To visualize where the terms with the state variables and their derivatives
appear in this DAE system, display the incidence matrix of the system. The system
contains three equations and three state variables, so incidenceMatrix returns a 3-
by-3 matrix of 1s and 0s. Here, 1s correspond to the terms containing state variables or
their derivatives.
M = incidenceMatrix(eqs, vars)
M =
1 0 1
0 1 1
1 1 0
Before checking the differential index of the system or solving this DAE
system, you must convert it to a first-order DAE system. For this, use the
reduceDifferentialOrder function that substitutes the derivatives with new
variables, such as Dxt(t) and Dyt(t). You can call reduceDifferentialOrder with
2-167
2 Using Symbolic Math Toolbox Software
two or three output arguments. The syntax with three output arguments shows which
derivatives correspond to new variables.
[eqs, vars, R] = reduceDifferentialOrder(eqs, vars)
eqs =
m*diff(Dxt(t), t) - (T(t)*x(t))/r
g*m + m*diff(Dyt(t), t) - (T(t)*y(t))/r
x(t)^2 + y(t)^2 - r^2
Dxt(t) - diff(x(t), t)
Dyt(t) - diff(y(t), t)
vars =
x(t)
y(t)
T(t)
Dxt(t)
Dyt(t)
R =
[ Dxt(t), diff(x(t), t)]
[ Dyt(t), diff(y(t), t)]
Display the incidence matrix of the new system. The index reduction process introduced
two new variables and two new equations. As a result, incidenceMatrix now returns a
5-by-5 matrix of 1s and 0s.
M = incidenceMatrix(eqs, vars)
M =
1 0 1 1 0
0 1 1 0 1
1 1 0 0 0
1 0 0 1 0
0 1 0 0 1
For the next step in solving your DAE problem, see Check and Reduce Differential
Index on page 2-169.
2-168
Check and Reduce Differential Index
Note: This is the third step in solving a DAE problem. For the sequence of steps for
solving DAE problems, see Set Up Your DAE Problem on page 2-162.
At this step, your DAE system must be a first-order system. The MATLAB solvers
ode15i, ode15s, and ode23t can solve systems of ordinary differential equations or
systems of differential algebraic equations of differential index 0 or 1. Therefore, before
you can solve a system of DAEs, you must check the differential index of the system.
If the index is higher than 1, the next step is to rewrite the system so that the index
reduces to 0 or 1.
In this section...
Reduce Differential Index to 1 on page 2-169
Reduce Differential Index to 0 on page 2-171
isLowIndexDAE(eqs,vars)
ans =
logical
0
There are two index reduction functions available in Symbolic Math Toolbox. The
reduceDAEIndex function tries to reduce the differential index by differentiating
the original equations (Pantelides algorithm) and replacing the derivatives by new
variables. The result contains the original equations (with the derivatives replaced
by new variables) followed by the new equations. The vector of variables contains the
original variables followed by variables generated by reduceDAEIndex.
[DAEs,DAEvars] = reduceDAEIndex(eqs,vars)
2-169
2 Using Symbolic Math Toolbox Software
DAEs =
m*Dxtt(t) - (T(t)*x(t))/r
g*m + m*Dytt(t) - (T(t)*y(t))/r
x(t)^2 + y(t)^2 - r^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)
DAEvars =
x(t)
y(t)
T(t)
Dxt(t)
Dyt(t)
Dytt(t)
Dxtt(t)
Dxt1(t)
Dyt1(t)
Dxt1t(t)
DAEs =
-(T(t)*x(t) - m*r*Dxtt(t))/r
(g*m*r - T(t)*y(t) + m*r*Dytt(t))/r
x(t)^2 + y(t)^2 - r^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)
DAEvars =
x(t)
y(t)
T(t)
Dxt(t)
Dyt(t)
Dytt(t)
2-170
Check and Reduce Differential Index
Dxtt(t)
Check the differential index of the new system. Now isLowIndexDAE returns 1, which
means that the differential index of the system is 0 or 1.
isLowIndexDAE(DAEs,DAEvars)
ans =
logical
1
For the next step in solving your DAE problem, see Convert DAE Systems to MATLAB
Function Handles on page 2-173.
isLowIndexDAE(eqs,vars)
ans =
logical
0
2-171
2 Using Symbolic Math Toolbox Software
Use reduceDAEToODE to reduce the differential index of small semilinear DAE systems
or semilinear DAE systems for which reduceDAEIndex fails to reduce the index to 1.
For example, the system of equations for a two-dimensional pendulum is relatively small
(five first-order equations in five variables). The reduceDAEToODE function reduces this
system to a system of implicit ordinary differential equations as follows.
[ODEs,constraints] = reduceDAEToODE(eqs,vars)
ODEs =
Dxt(t) - diff(x(t), t)
Dyt(t) - diff(y(t), t)
m*diff(Dxt(t), t) - (T(t)*x(t))/r
m*diff(Dyt(t), t) - (T(t)*y(t) - g*m*r)/r
-(4*T(t)*y(t) - 2*g*m*r)*diff(y(t), t) -...
diff(T(t), t)*(2*x(t)^2 + 2*y(t)^2) -...
4*T(t)*x(t)*diff(x(t), t) -...
4*m*r*Dxt(t)*diff(Dxt(t), t) -...
4*m*r*Dyt(t)*diff(Dyt(t), t)
constraints =
2*g*m*r*y(t) - 2*T(t)*y(t)^2 - 2*m*r*Dxt(t)^2 -...
2*m*r*Dyt(t)^2 - 2*T(t)*x(t)^2
r^2 - y(t)^2 - x(t)^2
2*Dxt(t)*x(t) + 2*Dyt(t)*y(t)
For the next step in solving your DAE problem, see Convert DAE Systems to MATLAB
Function Handles on page 2-173.
2-172
Convert DAE Systems to MATLAB Function Handles
Note: This is the fourth step in solving a DAE problem. For the sequence of steps for
solving DAE problems, see Set Up Your DAE Problem on page 2-162.
At this step, your DAE system must be a first-order system of differential index 0 or 1.
The system is still a system of symbolic expressions and variables. Before you can use the
MATLAB differential equation solvers, you must convert your DAE or ODE system to a
suitable input for these solvers, that is, a MATLAB function handle.
There are two ways to convert a DAE or ODE system to a MATLAB function handle:
To use the ode15i solver, convert a DAE or ODE system to a function handle by
using daeFunction.
To use the ode15s or ode23t solver, find the mass matrix and vector containing
the right sides of equations by using massMatrixForm. Then convert the result to
function handles by using matlabFunction. You can use this approach only with
semilinear systems.
These topics show how to convert your DAE or ODE system to function handles
acceptable by different MATLAB solvers.
In this section...
DAEs to Function Handles for ode15i on page 2-173
ODEs to Function Handles for ode15i on page 2-175
DAEs to Function Handles for ode15s and ode23t on page 2-176
ODEs to Function Handles for ode15s and ode23t on page 2-177
When you have a first-order low-index DAE system consisting of a vector of equations
and a vector of variables that is ready for conversion to a MATLAB function handle, use
daeFunction to convert the system. If a DAE system contains symbolic parameters
2-173
2 Using Symbolic Math Toolbox Software
(symbolic variables other than those specified in the vector of state variables, DAEvars),
then specify these symbolic parameters as additional input arguments of daeFunction.
For example, the two-dimensional pendulum model contains the variables m, r, and g.
Call daeFunction and provide these variables as additional arguments.
f = daeFunction(DAEs, DAEvars, m, r, g);
The function handle f still contains symbolic parameters. Create a purely numeric
function handle F that you can pass to ode15i.
F = @(t, Y, YP) f(t, Y, YP, m, r, g);
If your DAE system does not contain any symbolic parameters, then daeFunction
creates a function handle suitable for ode15i. For example, substitute the parameters
m = 1.0, r = 1.0, and g = 9.81 into the equations DAEs. Now the system does not
contain symbolic variables other than specified in the vector of state variables DAEvars.
DAEs = subs(DAEs)
DAEs =
Dxtt(t) - T(t)*x(t)
Dytt(t) - T(t)*y(t) + 981/100
x(t)^2 + y(t)^2 - 1
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)
Use daeFunction to create a function handle. The result is a function handle suitable
for ode15i.
F = daeFunction(DAEs, DAEvars);
For the next step in solving your DAE problem, see Find Consistent Initial Conditions
on page 2-180.
2-174
Convert DAE Systems to MATLAB Function Handles
When you have a first-order ODE system consisting of a vector of equations and a
vector of variables that is ready for conversion to a MATLAB function handle, use
daeFunction to convert the system. If an ODE system contains symbolic parameters
(symbolic variables other than those specified in the vector of state variables, vars), then
specify these symbolic parameters as additional input arguments of daeFunction. For
example, the two-dimensional pendulum model contains the variables m, r, and g. Call
daeFunction and provide these variables as additional arguments.
f = daeFunction(ODEs, vars, m, r, g);
Although daeFunction lets you create a function handle that contains symbolic
parameters without numeric values assigned to them, you cannot use these function
handles as input arguments for the ode15i solver. Before you call the solvers, you must
assign numeric values to all symbolic parameters.
m = 1.0;
r = 1.0;
g = 9.81;
The function handle f still contains symbolic parameters. Create a purely numeric
function handle F that you can pass to ode15i.
F = @(t, Y, YP) f(t, Y, YP, m, r, g);
If your ODE system does not contain any symbolic parameters, then daeFunction
creates a function handle suitable for ode15i. For example, substitute the parameters
m = 1.0, r = 1.0, and g = 9.81 into the equations ODEs and constraint equations
constraints. Now the system does not contain symbolic variables other than those
specified in the vector of state variables vars.
ODEs = subs(ODEs)
ODEs =
Dxt(t) - diff(x(t), t)
Dyt(t) - diff(y(t), t)
diff(Dxt(t), t) - T(t)*x(t)
diff(Dyt(t), t) - T(t)*y(t) + 981/100
- (4*T(t)*y(t) - 981/50)*diff(y(t), t) -...
2-175
2 Using Symbolic Math Toolbox Software
4*Dxt(t)*diff(Dxt(t), t) -...
4*Dyt(t)*diff(Dyt(t), t) -...
diff(T(t), t)*(2*x(t)^2 + 2*y(t)^2) -...
4*T(t)*x(t)*diff(x(t), t)
constraints = subs(constraints)
constraints =
(981*y(t))/50 - 2*Dxt(t)^2 - 2*Dyt(t)^2 - 2*T(t)*x(t)^2 - 2*T(t)*y(t)^2
1 - y(t)^2 - x(t)^2
2*Dxt(t)*x(t) + 2*Dyt(t)*y(t)
For the next step in solving your DAE problem, see Find Consistent Initial Conditions
on page 2-180.
When you have a first-order low-index semilinear DAE system consisting of a vector of
equations and a vector of variables, use massMatrixForm to find the mass matrix M and
vector F of the right side of the equations.
[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
2-176
Convert DAE Systems to MATLAB Function Handles
To convert M and F to MATLAB function handles, use two separate odeFunction calls.
For inputs that do not contain any symbolic parameters, odeFunction creates function
handles suitable for the MATLAB ODE solvers. In the previous code sample, the mass
matrix M does not contain symbolic variables other than specified in the vector of state
variables (DAEvars). Use odaeFunction to create a function handle. The result is a
function handle suitable for ode15s and ode23t.
M = odeFunction(M, DAEvars);
The function handle f still contains symbolic parameters. Create a purely numeric
function handle F that you can pass to ode15s or ode23t.
F = @(t, Y) F(t, Y, m, r, g);
For the next step in solving your DAE problem, see Find Consistent Initial Conditions
on page 2-180.
2-177
2 Using Symbolic Math Toolbox Software
side of the equations. If M is a mass matrix form and F is a vector containing the right
side of equations, then M(t,y(t))*y'(t) = F(t,y(t)).
When you have a first-order ODE system consisting of a vector of equations and a vector
of variables, use massMatrixForm to find the mass matrix M and vector F of the right
side of the equations.
[M,F] = massMatrixForm(ODEs,vars)
M =
[ -1, 0, 0, 0, 0]
[ 0, -1, 0, 0, 0]
[ 0, 0, 0, m, 0]
[ 0, 0, 0, 0, m]
[ -4*T(t)*x(t), 2*g*m*r - 4*T(t)*y(t), - 2*x(t)^2 - 2*y(t)^2, -4*m*r*Dxt(t), -4*m*r*Dyt(t)]
F =
-Dxt(t)
-Dyt(t)
(T(t)*x(t))/r
(T(t)*y(t) - g*m*r)/r
0
To convert M and F to MATLAB function handles, use two separate odeFunction calls.
Although odeFunction lets you create function handles containing symbolic parameters
without numeric values assigned to them, you cannot use these function handles as input
arguments for the MATLAB ODE solvers. Before calling the solvers, you must assign
numeric values to all symbolic parameters.
m = 1.0;
r = 1.0;
g = 9.81;
The function handles M and F still contain symbolic parameters. Create purely numeric
function handles that you can pass to ode15s or ode23t.
2-178
Convert DAE Systems to MATLAB Function Handles
For the next step in solving your DAE problem, see Find Consistent Initial Conditions
on page 2-180.
2-179
2 Using Symbolic Math Toolbox Software
Note: This is the fifth step in solving a DAE problem. For the sequence of steps for
solving DAE problems, see Set Up Your DAE Problem on page 2-162.
At this step, you search for initial conditions that satisfy all equations of your new low-
index DAE or ODE system. There are two functions that let you find consistent initial
conditions:
If you used reduceDAEIndex to reduce the differential index of the system to 1, then
use the MATLAB decic function to find consistent initial conditions for the new DAE
system.
If you used reduceDAEToODE to rewrite the system as a system of implicit ODEs,
then use the decic function available in Symbolic Math Toolbox. As one of its input
arguments, this function accepts algebraic constraints of the original system returned
by reduceDAEToODE and returns consistent initial conditions that satisfy those
constraints.
These topics show how to find consistent initial conditions for your DAE or ODE system
when you use different solvers.
In this section...
DAEs: Initial Conditions for ode15i on page 2-180
ODEs: Initial Conditions for ode15i on page 2-182
DAEs: Initial Conditions for ode15s and ode23t on page 2-183
ODEs: Initial Conditions for ode15s and ode23t on page 2-184
DAEvars
DAEvars =
2-180
Find Consistent Initial Conditions
x(t)
y(t)
T(t)
Dxt(t)
Dyt(t)
Dytt(t)
Dxtt(t)
Suppose that the initial angular displacement of the pendulum is 30, and the origin
of the coordinates is at the suspension point of the pendulum. Since cos(30) = 0.5 and
sin(30) 0.8, you can specify the starting points for the search for consistent values of
the variables and their derivatives at the time t0 = 0 as two 7-by-1 vectors.
y0est = [0.5*r; -0.8*r; 0; 0; 0; 0; 0];
yp0est = zeros(7,1);
Create an option set that specifies numerical tolerances for the numerical search.
opt = odeset('RelTol', 10.0^(-7), 'AbsTol' , 10.0^(-7));
Find consistent initial values for the variables and their derivatives by using the
MATLAB decic function.
[y0, yp0] = decic(F, 0, y0est, [], yp0est, [], opt)
y0 =
0.4828
-0.8757
-8.5909
0
0.0000
-2.2866
-4.1477
yp0 =
0
0.0000
0
0
-2.2866
0
0
For the next step in solving your DAE problem, see Solve DAE Systems Using MATLAB
ODE Solvers on page 2-186.
2-181
2 Using Symbolic Math Toolbox Software
vars =
x(t)
y(t)
T(t)
Dxt(t)
Dyt(t)
Suppose that the initial angular displacement of the pendulum is 30, and the origin
of the coordinates is at the suspension point of the pendulum. Since cos(30) = 0.5 and
sin(30) 0.8, you can specify the starting points for the search for consistent values of
the variables and their derivatives at the time t0 = 0 as two 5-by-1 vectors.
y0est = [0.5*r; -0.8*r; 0; 0; 0];
yp0est = zeros(5,1);
Create an option set that specifies numerical tolerances for the numerical search.
opt = odeset('RelTol', 10.0^(-7), 'AbsTol' , 10.0^(-7));
Find initial values consistent with the system of ODEs and with the algebraic constraints
by using the decic function available in Symbolic Math Toolbox. 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. The zero elements in
[1,0,0,0,1] correspond to those values in y0est for which decic solves the constraint
equations.
[y0, yp0] = decic(ODEs, vars, constraints, 0, y0est, [1,0,0,0,1], yp0est, opt)
y0 =
0.5000
-0.8660
-8.4957
0
0
yp0 =
2-182
Find Consistent Initial Conditions
0
0
0
-4.2479
-2.4525
For the next step in solving your DAE problem, see Solve DAE Systems Using MATLAB
ODE Solvers on page 2-186.
Create an option set that contains the mass matrix M of the system, a vector yp0est of
initial guesses for the derivatives, 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 f
describing the DAE by 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, yp0] = decic(@(t,y,yp) M(t,y)*yp - F(t,y), 0, y0est, [], yp0est, [], opt)
y0 =
0.4828
-0.8757
-8.5909
0
0.0000
-2.2866
-4.1477
yp0 =
2-183
2 Using Symbolic Math Toolbox Software
0
0.0000
0
0
-2.2866
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.
opt = odeset(opt, 'InitialSlope', yp0);
For the next step in solving your DAE problem, see Solve DAE Systems Using MATLAB
ODE Solvers on page 2-186.
Before you proceed, substitute numeric values for m, r, and g into ODEs, constraints,
and y0est.
m = 1.0;
r = 1.0;
g = 9.81;
ODEs = subs(ODEs);
constraints = subs(constraints);
y0est = subs(y0est);
Create an option set that contains the mass matrix M of the system and specifies
numerical tolerances for the numerical search.
opt = odeset('Mass', M, 'RelTol', 10.0^(-7), 'AbsTol' , 10.0^(-7));
Find initial values consistent with the system of ODEs and with the algebraic constraints
by using the decic function available in Symbolic Math Toolbox. The parameter
2-184
Find Consistent Initial Conditions
[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. The zero elements in
[1,0,0,0,1] correspond to those values in y0est for which decic solves the constraint
equations.
[y0, yp0] = decic(ODEs, vars, constraints, 0, y0est, [1,0,0,0,1], yp0est, opt)
y0 =
0.5000
-0.8660
-8.4957
0
0
yp0 =
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.
opt = odeset(opt, 'InitialSlope', yp0);
For the next step in solving your DAE problem, see Solve DAE Systems Using MATLAB
ODE Solvers on page 2-186.
2-185
2 Using Symbolic Math Toolbox Software
Note: This is the final step in solving a DAE problem. For the sequence of steps for
solving DAE problems, see Set Up Your DAE Problem on page 2-162.
At this step, you must have a MATLAB function handle representing your ODE or
DAE system (of differential index 0 or 1, respectively). You also must have two vectors
specifying initial conditions for the variables of the system and their first derivatives.
ode15i, ode15s, and ode23t are the MATLAB differential equation solvers
recommended for this workflow.
If you have one function handle representing your DAE system (typically obtained via
daeFunction), then use ode15i.
If your DAE is semilinear, and you have function handles for the mass matrix and
the right sides of equations of the DAE system, use ode15s or ode23t. These two
functions use the same syntax. The example shows how to use ode15s, but you can
replace it with ode23t.
The following examples show how to solve DAE and ODE systems using different
MATLAB solvers.
In this section...
Solve a DAE System with ode15i on page 2-186
Solve an ODE System with ode15i on page 2-187
Solve a DAE System with ode15s on page 2-188
Solve an ODE System with ode15s on page 2-189
for k = 1:numel(DAEvars)
S{k} = char(DAEvars(k));
2-186
Solve DAE Systems Using MATLAB ODE Solvers
end
for k = 1:numel(vars)
2-187
2 Using Symbolic Math Toolbox Software
S{k} = char(vars(k));
end
2-188
Solve DAE Systems Using MATLAB ODE Solvers
for k = 1:numel(DAEvars)
S{k} = char(DAEvars(k));
end
2-189
2 Using Symbolic Math Toolbox Software
for k = 1:numel(vars)
S{k} = char(vars(k));
end
2-190
Fourier Transforms and Inverse
F [ f ] (w) = f ( x) e-iwx dx,
-
1
F -1 [ f ] ( x ) = f (w)e
iwx
dw.
2p
-
This documentation refers to this formulation as the Fourier transform of f with respect
to x as a function of w. Or, more concisely, the Fourier transform of f with respect to x
at w. Mathematicians often use the notation F[f] to indicate the Fourier transform of
f. In this setting, the transform is taken with respect to the independent variable of f
(if f = f(t), then t is the independent variable; f = f(x) implies that x is the independent
variable, etc.) at the default variable w. This documentation refers to F[f] as the Fourier
transform of f at w and F1[f] is the IFT of f at x. See fourier and ifourier in the
reference pages for tables that show the Symbolic Math Toolbox commands equivalent to
various mathematical representations of the Fourier and inverse Fourier transforms.
For example, consider the Fourier transform of the Cauchy density function, ((1+x2))1:
syms x
cauchy = 1/(pi*(1+x^2));
fcauchy = fourier(cauchy)
fcauchy =
exp(-abs(w))
fplot(fcauchy)
2-191
2 Using Symbolic Math Toolbox Software
The Fourier transform is symmetric, since the original Cauchy density function is
symmetric.
To recover the Cauchy density function from the Fourier transform, call ifourier:
finvfcauchy = ifourier(fcauchy)
finvfcauchy =
1/(pi*(x^2 + 1))
An application of the Fourier transform is the solution of ordinary and partial differential
equations over the real line. Consider the deformation of an infinitely long beam resting
on an elastic foundation with a shock applied to it at a point. A real world analogy to
this phenomenon is a set of railroad tracks atop a road bed.
2-192
Fourier Transforms and Inverse
d4 y k 1
+ y= d( x), - < x < .
4 EI EI
dx
Here, E represents elasticity of the beam (railroad track), I is the beam constant, and
k is the spring (road bed) stiffness. The shock force on the right side of the differential
equation is modeled by the Dirac Delta function (x). The Dirac Delta function has the
following important property:
f ( x - y) d( y) dy = f ( x).
-
where
2-193
2 Using Symbolic Math Toolbox Software
1 1
1 for - <x<
c( -1 / 2n, 1/ 2n ) ( x) = 2n 2n
0 otherwise.
d4 y 4
F (w) = w Y ( w).
dx4
syms w y(x)
fourier(diff(y(x), x, 4), x, w)
ans =
w^4*fourier(y(x), x, w)
Note that you can call the fourier command with one, two, or three inputs (see the
reference pages for fourier). With a single input argument, fourier(f) returns a
function of the default variable w. If the input argument is a function of w, fourier(f)
returns a function of t. All inputs to fourier must be symbolic objects.
Applying the Fourier transform to the differential equation above yields the algebraic
equation
4 k
w + Y ( w) = D(w),
EI
or Y ( w ) = D(w) G( w),
where
1
G (w) = = F[ g( x)] (w)
4 k
w +
EI
for some function g(x). That is, g is the inverse Fourier transform of G:
2-194
Fourier Transforms and Inverse
g ( x) = F-1[ G ( w ) ]( x )
The Symbolic Math Toolbox counterpart to the IFT is ifourier. This behavior of
ifourier parallels fourier with one, two, or three input arguments (see the reference
pages for ifourier).
Continuing with the solution of the differential equation, observe that the ratio
K
EI
is a relatively large number since the road bed has a high stiffness constant k and
a railroad track has a low elasticity E and beam constant I. Make the simplifying
assumption that
K
= 1024.
EI
G = 1/(w^4 + 1024);
g = ifourier(G, w, x);
g = simplify(g)
g =
(pi*exp(x*(- 4 - 4i))*(sign(x) + 1)*(1/1024 + 1i/1024) +...
pi*exp(x*(- 4 + 4i))*(sign(x) + 1)*(1/1024 - 1i/1024) -...
pi*exp(x*(4 - 4i))*(sign(x) - 1)*(1/1024 - 1i/1024) -...
pi*exp(x*(4 + 4i))*(sign(x) - 1)*(1/1024 + 1i/1024))/(2*pi)
y( x) = (d * g)( x) = g( x - y)d ( y) dy = g( x).
-
by the special property of the Dirac Delta function. To plot this function, substitute the
domain of x into y(x), using the subs command. The resulting graph shows that the
impact of a blow on a beam is highly localized; the greatest deflection occurs at the point
of impact and falls off sharply from there.
2-195
2 Using Symbolic Math Toolbox Software
XX = -3:0.05:3;
YY = double(subs(g, x, XX));
plot(XX, YY)
title('Beam Deflection for a Point Shock')
xlabel('x')
ylabel('y(x)')
2-196
Laplace Transform and Inverse
L [ f ] (s ) = f (t)e
- ts
dt,
0
c+i
1
L-1 [ f ] ( t) = f (s) est ds,
2p i
c-i
where c is a real number selected so that all singularities of f(s) are to the left of the line
s= c. The notation L[f] indicates the Laplace transform of f at s. Similarly, L1[f] is the
ILT of f at t.
The Laplace transform has many applications including the solution of ordinary
differential equations/initial value problems. Consider the resistance-inductor-capacitor
(RLC) circuit below.
2-197
2 Using Symbolic Math Toolbox Software
By applying Kirchhoff's voltage and current laws, Ohm's Law, and Faraday's Law, you
can arrive at the following system of simultaneous ordinary differential equations.
dI1 R2 dQ R2 - R1
+ = I1 , I1 (0) = I0 .
dt L dt L
dQ 1 1 R2
= E(t) - Q( t) + I1 , Q (0) = Q0 .
dt R3 + R2 C R3 + R2
Solve this system of differential equations using laplace. First treat the Rj, L, and C as
(unknown) real constants and then supply values later on in the computation.
clear E
syms R1 R2 R3 L C real
syms I1(t) Q(t) s
2-198
Laplace Transform and Inverse
At this point, you have constructed the equations in the MATLAB workspace. An
approach to solving the differential equations is to apply the Laplace transform, which
you will apply to eq1(t) and eq2(t). Transforming eq1(t) and eq2(t)
L1(t) = laplace(eq1,t,s)
L2(t) = laplace(eq2,t,s)
returns
L1(t) =
s*laplace(I1(t), t, s) - I1(0)
+ ((R1 - R2)*laplace(I1(t), t, s))/L
- (R2*(Q(0) - s*laplace(Q(t), t, s)))/L
L2(t) =
s*laplace(Q(t), t, s) - Q(0)
- (R2*laplace(I1(t), t, s))/(R2 + R3) - (C/(s^2 + 1)
- laplace(Q(t), t, s))/(C*(R2 + R3))
returns
NI1 =
s*laplace(I1(t), t, s) + (5*s*laplace(Q(t), t, s))/4
+ (5*laplace(I1(t), t, s))/4 - 35/2
The substitution
NQ = subs(L2,{R1,R2,R3,L,C,I1(0),Q(0)},{4,2,3,1.6,1/4,15,2})
2-199
2 Using Symbolic Math Toolbox Software
returns
NQ(t) =
s*laplace(Q(t), t, s) - 1/(5*(s^2 + 1)) -...
(2*laplace(I1(t), t, s))/5 + (4*laplace(Q(t), t, s))/5 - 2
to obtain
NI1 =
(5*LI1)/4 + LI1*s + (5*LQ*s)/4 - 35/2
Collecting terms
NI1 = collect(NI1,LI1)
gives
NI1 =
(s + 5/4)*LI1 + (5*LQ*s)/4 - 35/2
A similar substitution
NQ = ...
subs(NQ,{laplace(I1(t),t,s), laplace(Q(t),t,s)}, {LI1,LQ})
yields
NQ(t) =
(4*LQ)/5 - (2*LI1)/5 + LQ*s - 1/(5*(s^2 + 1)) - 2
gives
NQ(t) =
(s + 4/5)*LQ - (2*LI1)/5 - 1/(5*(s^2 + 1)) - 2
2-200
Laplace Transform and Inverse
you obtain
LI1 =
(5*(60*s^3 + 56*s^2 + 59*s + 56))/((s^2 + 1)*(20*s^2 + 51*s + 20))
LQ =
(40*s^3 + 190*s^2 + 44*s + 195)/((s^2 + 1)*(20*s^2 + 51*s + 20))
To recover I1 and Q, compute the inverse Laplace transform of LI1 and LQ. Inverting
LI1
I1 = ilaplace(LI1, s, t)
produces
I1 =
15*exp(-(51*t)/40)*(cosh((1001^(1/2)*t)/40) -...
(293*1001^(1/2)*sinh((1001^(1/2)*t)/40))/21879) - (5*sin(t))/51
Inverting LQ
Q = ilaplace(LQ, s, t)
yields
Q =
(4*sin(t))/51 - (5*cos(t))/51 +...
(107*exp(-(51*t)/40)*(cosh((1001^(1/2)*t)/40) +...
(2039*1001^(1/2)*sinh((1001^(1/2)*t)/40))/15301))/51
Now plot the current I1(t) and charge Q(t) in two different time domains, 0 t 10
and 5 t 25. The following statements generate the desired plots.
subplot(2,2,1)
fplot(I1,[0,10])
title('Current')
ylabel('I1(t)')
xlabel('t')
grid
subplot(2,2,2)
fplot(Q,[0,10])
title('Charge')
ylabel('Q(t)')
xlabel('t')
grid
subplot(2,2,3)
fplot(I1,[5,25])
2-201
2 Using Symbolic Math Toolbox Software
title('Current')
ylabel('I1(t)')
xlabel('t')
grid
text(7,0.25,'Transient')
text(16,0.125,'Steady State')
subplot(2,2,4)
fplot(Q,[5,25])
title('Charge')
ylabel('Q(t)')
xlabel('t')
grid
text(7,0.25,'Transient')
text(15,0.16,'Steady State')
2-202
Laplace Transform and Inverse
Note that the circuit's behavior, which appears to be exponential decay in the short term,
turns out to be oscillatory in the long term. The apparent discrepancy arises because the
circuit's behavior actually has two components: an exponential part that decays rapidly
(the transient component) and an oscillatory part that persists (the steady-state
component).
2-203
2 Using Symbolic Math Toolbox Software
Z [ f ]( z ) = f (n)z -n .
n =0
1
Z -1 [ g ] ( n) = g( z) zn -1 dz, n = 1, 2,...
2p i
z =R
The notation Z1[f] means the IZT of f at n. The Symbolic Math Toolbox commands
ztrans and iztrans apply the z-transform and IZT to symbolic expressions,
respectively. See ztrans and iztrans for tables showing various mathematical
representations of the z-transform and inverse z-transform and their Symbolic Math
Toolbox counterparts.
The z-transform is often used to solve difference equations. In particular, consider the
famous Rabbit Problem. That is, suppose that rabbits reproduce only on odd birthdays
(1, 3, 5, 7, ...). If p(n) is the rabbit population at year n, then p obeys the difference
equation
You can use ztrans to find the population each year p(n). First, apply ztrans to the
equations
syms p(n) z
eq = p(n + 2) - p(n + 1) - p(n);
Zeq = ztrans(eq, n, z)
to obtain
Zeq =
z*p(0) - z*ztrans(p(n), n, z) - z*p(1) + z^2*ztrans(p(n), n, z)
- z^2*p(0) - ztrans(p(n), n, z)
2-204
Z-Transform and Inverse
Next, replace ztrans(p(n), n, z) with Pz and insert the initial conditions for p(0)
and p(1).
syms Pz
Zeq = subs(Zeq,{ztrans(p(n), n, z), p(0), p(1)}, {Pz, 1, 2})
to obtain
Zeq =
Pz*z^2 - z - Pz*z - Pz - z^2
Collecting terms
eq = collect(Zeq, Pz)
yields
eq =
(z^2 - z - 1)*Pz - z^2 - z
to obtain
P =
-(z^2 + z)/(- z^2 + z + 1)
2-205
2 Using Symbolic Math Toolbox Software
title('Rabbit Population')
xlabel('years')
ylabel('p')
grid on
References
[1] Andrews, L.C., Shivamoggi, B.K., Integral Transforms for Engineers and Applied
Mathematicians, Macmillan Publishing Company, New York, 1986
2-206
Z-Transform and Inverse
2-207
2 Using Symbolic Math Toolbox Software
Create Plots
In this section...
Plot with Symbolic Plotting Functions on page 2-208
Plot Functions Numerically on page 2-210
Plot Multiple Symbolic Functions in One Graph on page 2-211
Plot Multiple Symbolic Functions in One Figure on page 2-213
Combine Symbolic Function Plots and Numeric Data Plots on page 2-215
Combine Numeric and Symbolic Plots in 3-D on page 2-217
Plot the symbolic expression by using fplot. By default, fplot uses the range
.
syms x
fplot(sin(6*x))
2-208
Create Plots
Plot a symbolic expression or function in polar coordinates (radius) and (polar angle)
by using ezpolar. By default, ezpolar plots a symbolic expression or function over the
interval .
syms t
ezpolar(sin(6*t))
2-209
2 Using Symbolic Math Toolbox Software
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);
2-210
Create Plots
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)
2-211
2 Using Symbolic Math Toolbox Software
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.
syms x y
f = exp(x)*sin(20*x)
obj = fplot(f,[0 3]);
hold on
fplot(exp(x), [0 3], '--r')
fplot(-exp(x), [0 3], '--r')
title(obj.DisplayName)
hold off
f =
sin(20*x)*exp(x)
2-212
Create Plots
syms x y a
2-213
2 Using Symbolic Math Toolbox Software
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)
fsurf(subs(f, a, 100))
title('a = 100')
2-214
Create Plots
x = linspace(-5,5);
y = sin(x) + (-1).^randi(10, 1, 100).*rand(1, 100)./2;
scatter(x, y)
2-215
2 Using Symbolic Math Toolbox Software
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
2-216
Create Plots
2-217
2 Using Symbolic Math Toolbox Software
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')
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.
2-218
Create Plots
hold on
[X,Y,Z] = sphere;
mesh(X, Y, Z)
colormap(gray)
title('Symbolic Parametric Plot and a Sphere')
hold off
2-219
2 Using Symbolic Math Toolbox Software
For example:
syms x y
z = 30*x^4/(x*y^2 + 10) - x^3*(y^2 + 1)^2;
fortran(z)
ans =
159 char array
t0 = (x**4*3.0D1)/(x*y**2+1.0D1)-x**3*(y**2+1.0D0)**2
ccode(z)
ans =
166 char array
t0 = ((x*x*x*x)*3.0E1)/(x*(y*y)+1.0E1)-(x*x*x)*pow(y*y+1.0,2.0);
generates a file named fortrantest in the current folder. fortrantest consists of the
following:
t12 = x**2
t13 = y**2
t14 = t13+1
t0 = (t12**2*30)/(t13*x+10)-t12*t14**2*x
2-220
Generate C or Fortran Code from Symbolic Expressions
t17 = y*y;
t18 = t17+1.0;
t0 = ((t16*t16)*3.0E1)/(t17*x+1.0E1)-t16*(t18*t18)*x;
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, for example t32. Intermediate variables can make
the resulting code more efficient by reusing intermediate expressions (such as t12 in
fortrantest, and t16 in ccodetest). They can also make the code easier to read by
keeping expressions short.
2-221
2 Using Symbolic Math Toolbox Software
If you work in the MuPAD Notebook app, see Create MATLAB Functions from MuPAD
Expressions on page 3-70.
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
2-222
Generate MATLAB Functions from Symbolic Expressions
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:
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
2-223
2 Using Symbolic Math Toolbox Software
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];
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)
2-224
Generate MATLAB Functions from Symbolic Expressions
...
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:
function out1 = testMatrix(x,y,t)
...
To customize the names of output variables, use the output option:
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'})
2-225
2 Using Symbolic Math Toolbox Software
If you work in the MuPAD Notebook app, see Create MATLAB Function Blocks from
MuPAD Expressions on page 3-74.
new_system('my_system')
open_system('my_system')
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
r = sqrt(x.^2+y.^2);
2-226
Generate MATLAB Function Blocks from Symbolic Expressions
syms x y
mu = sym('mu');
dydt = -x - mu*y*(x^2 - 1);
matlabFunctionBlock('my_system/vdp', dydt,'vars', [y mu x])
2-227
2 Using Symbolic Math Toolbox Software
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.
If you work in the MuPAD Notebook app, see Create Simscape Equations from MuPAD
Expressions on page 3-76.
syms a y(t)
Dy = diff(y);
s = dsolve(diff(y, 2) == -a^2*y, y(0) == 1, Dy(pi/a) == 0);
s = simplify(s)
s =
cos(a*t)
Then, use the simscapeEquation function to rewrite the solution in the Simscape
language:
simscapeEquation(s)
2-228
Generate Simscape Equations from Symbolic Expressions
ans =
117 char array
s == cos(a*time);
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.
syms a x(t)
simscapeEquation(diff(x), -a^2*x)
ans =
116 char array
x.der == -a^2*x;
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 =
195 char array
if (x ~= 0.0)
s == -atan(1.0/x^2*(u-1.0))+atan(1.0/x^2*(u+1.0));
2-229
2 Using Symbolic Math Toolbox Software
else
s == NaN;
end
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. If
a symbolic expression contains functions that are not supported by Simscape, then
simscapeEquation cannot represent the symbolic expression as a Simscape equation,
but instead issues a warning. Always verify the conversion result. The following types of
expressions are prone to invalid conversion:
2-230
3
Note: MuPAD notebooks are not recommended. Use MATLAB live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some. For
more information, see Convert MuPAD Notebooks to MATLAB Live Scripts on page
3-19.
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-66.
3-2
Create MuPAD Notebooks
Note: MuPAD notebooks are not recommended. Use MATLAB live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some. For
more information, see Convert MuPAD Notebooks to MATLAB Live Scripts on page
3-19.
Before creating a MuPAD notebook, it is best to decide which interface you intend to use
primarily for your task. The two approaches are:
Perform your computations in the MATLAB Live Editor while using MuPAD
notebooks as an auxiliary tool. This approach is recommended and implies that you
create a MuPAD notebook, and then execute it, transfer data and results, or close it
from the MATLAB Live Editor.
Perform your computations and obtain the results in the MuPAD Notebook app. This
approach is not recommended and implies that you use the MATLAB Live Editor only
to access MuPAD, but do not intend to copy data and results between MATLAB and
MuPAD.
If you created a MuPAD notebook without creating a handle, and then realized
that you need to transfer data and results between MATLAB and MuPAD, use
allMuPADNotebooks to create a handle to this notebook:
mupad
nb = allMuPADNotebooks
nb =
Notebook1
This approach does not require saving the notebook. Alternatively, you can save the
notebook and then open it again, creating a handle.
3-3
3 MuPAD in Symbolic Math Toolbox
To create a blank MuPAD notebook from the MATLAB Command Window, type
nb = mupad
The variable nb is a handle to the notebook. You can use any variable name instead of
nb.
To create several notebooks, use this syntax repeatedly, assigning a notebook handle to
different variables. For example, use the variables nb1, nb2, and so on.
To create several MuPAD notebooks, click the MuPAD Notebook button repeatedly.
To create a new blank notebook, type mupad in the MATLAB Command Window.
The Welcome to MuPAD dialog box lets you create a new notebook or program file, open
an existing notebook or program file, and access documentation. To open this dialog box,
type mupadwelcome in the MATLAB Command Window.
3-4
Create MuPAD Notebooks
If you already opened a notebook, you can create new notebooks and program files
without switching to the MATLAB Live Editor:
To create a new notebook, select File>New Notebook from the main menu or use
the toolbar.
To open a new Editor window, where you can create a program file, select File>New
Editor from the main menu or use the toolbar.
3-5
3 MuPAD in Symbolic Math Toolbox
Note: MuPAD notebooks are not recommended. Use MATLAB live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some. For
more information, see Convert MuPAD Notebooks to MATLAB Live Scripts on page
3-19.
Before opening a MuPAD notebook, it is best to decide which interface you intend to use
primarily for your task. The two approaches are:
Perform your computations in the MATLAB Live Editor using MuPAD notebooks as
an auxiliary tool. This approach is recommended and implies that you open a MuPAD
notebook, and then execute it, transfer data and results, or close it from the MATLAB
Live Editor. If you perform computations in both interfaces, use handles to notebooks.
The toolbox uses these handles for communication between the MATLAB workspace
and the MuPAD notebook.
Perform your computations and obtain the results in MuPAD. This approach is not
recommended. It implies that you use the MATLAB Live Editor only to access the
MuPAD Notebook app, but do not intend to copy data and results between MATLAB
and MuPAD. If you use the MATLAB Live Editor only to open a notebook, and then
perform all your computations in that notebook, you can skip using a handle.
Tip MuPAD notebook files open in an unevaluated state. In other words, the notebook
is not synchronized with its engine when it opens. To synchronize a notebook with
its engine, select Notebook > Evaluate All or use evaluateMuPADNotebook. For
details, see Evaluate MuPAD Notebooks from MATLAB on page 3-13.
If you opened a MuPAD notebook without creating a handle, and then realized
that you need to transfer data and results between MATLAB and MuPAD, use
allMuPADNotebooks to create a handle to this notebook:
mupad
nb = allMuPADNotebooks
nb =
Notebook1
3-6
Open MuPAD Notebooks
This approach does not require saving changes in the notebook. Alternatively, you can
save the notebook and open it again, this time creating a handle.
nb1 = openmn('file_name')
nb = openmn('file_name#linktarget_name')
3-7
3 MuPAD in Symbolic Math Toolbox
Open an existing MuPAD notebook file by using the mupad or openmn function in the
MATLAB Command Window:
mupad('file_name')
openmn('file_name')
mupad('file_name#linktarget_name')
openmn('file_name#linktarget_name')
Open an existing MuPAD notebook file by using open in the MATLAB Command
Window:
open('file_name')
The Welcome to MuPAD dialog box lets you create a new notebook or program file, open
an existing notebook or program file, and access documentation. To open this dialog box,
type mupadwelcome in the MATLAB Command Window.
3-8
Open MuPAD Notebooks
If you already opened a notebook, you can start new notebooks and open existing ones
without switching to the MATLAB Live Editor. To open an existing notebook, select
File>Open from the main menu or use the toolbar. Also, you can open the list of
notebooks you recently worked with.
Do not use a handle when opening program files and graphic files because there is no
communication between these files and the MATLAB Live Editor.
You can open an existing MuPAD notebook, program file, or graphic file by double-
clicking the file name. The system opens the file in the appropriate interface.
3-9
3 MuPAD in Symbolic Math Toolbox
Symbolic Math Toolbox provides these functions for opening MuPAD files in the
interfaces with which these files are associated:
openmu opens a program file with the extension .mu in the MATLAB Editor.
openxvc opens an XVC graphic file in the MuPAD Graphics window.
openxvz opens an XVZ graphic file in the MuPAD Graphics window.
For example, open an existing MuPAD program file by using the openmu function in the
MATLAB Command Window:
openmu('H:\Documents\Notes\myProcedure.mu')
You must specify a full path unless the file is in the current folder.
Open an existing MuPAD file by using open in the MATLAB Command Window:
open('file_name')
The Welcome to MuPAD dialog box lets you create a new notebook or program file, open
an existing notebook or program file, and access documentation. To open this dialog box,
type mupadwelcome in the MATLAB Command Window.
3-10
Open MuPAD Notebooks
If you already opened a notebook, you can create new notebooks and program files and
open existing ones without switching to the MATLAB Command Window. To open an
existing file, select File>Open from the main menu or use the toolbar.
You also can open the Debugger window from within a MuPAD notebook. For details, see
Open the Debugger.
Note: You cannot access the MuPAD Debugger from the MATLAB Command Window.
3-11
3 MuPAD in Symbolic Math Toolbox
Note: MuPAD notebooks are not recommended. Use MATLAB live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some. For
more information, see Convert MuPAD Notebooks to MATLAB Live Scripts on page
3-19.
1 Switch to the notebook. (You cannot save changes in a MuPAD notebook from the
MATLAB Command Window.)
2 Select File>Save or File>Save As from the main menu or use the toolbar.
If you want to save and close a notebook, you can use the close function in the MATLAB
Command Window. If the notebook has been modified, then MuPAD brings up the dialog
box asking if you want to save changes. Click Yes to save the modified notebook.
Note: You can lose data when saving a MuPAD notebook. A notebook saves its inputs
and outputs, but not the state of its engine. In particular, MuPAD does not save variables
copied into a notebook using setVar(nb,...).
3-12
Evaluate MuPAD Notebooks from MATLAB
Note: MuPAD notebooks are not recommended. Use MATLAB live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some. For
more information, see Convert MuPAD Notebooks to MATLAB Live Scripts on page
3-19.
When you open a saved MuPAD notebook file, the notebook displays the results
(outputs), but the engine does not remember them. For example, suppose that you
saved the notebook myFile1.mn in your current folder and then opened it:
nb = mupad('myFile1.mn');
Open that file and try to use the value w without synchronizing the notebook with its
engine. The variable w currently has no assigned value.
3-13
3 MuPAD in Symbolic Math Toolbox
To synchronize a MuPAD notebook with its engine, you must evaluate the notebook as
follows:
1 Open the notebooks that you want to evaluate. Symbolic Math Toolbox cannot
evaluate MuPAD notebooks without opening them.
2 Use evaluateMuPADNotebook. Alternatively, you can evaluate the notebook by
selecting Notebook>Evaluate All from the main menu of the MuPAD notebook.
3 Perform your computations using data and results obtained from MuPAD notebooks.
4 Close the notebooks. This step is optional.
For example, evaluate the notebook myFile1.mn located in your current folder:
evaluateMuPADNotebook(nb)
3-14
Evaluate MuPAD Notebooks from MATLAB
Now, you can use the data and results from that notebook in your computations. For
example, copy the variables y and w to the MATLAB workspace:
y = getVar(nb,'y')
w = getVar(nb,'w')
y =
sin(x)/(sin(x)^2 + 1)
w =
sin(x)/(sin(x)^2 - sin(x) + 1)
You can evaluate several notebooks in a single call by passing a vector of notebook
handles to evaluateMuPADNotebook:
nb1 = mupad('myFile1.mn');
nb2 = mupad('myFile2.mn');
evaluateMuPADNotebook([nb1,nb2])
Also, you can use allMuPADNotebooks that returns handles to all currently open
notebooks. For example, if you want to evaluate the notebooks with the handles nb1 and
nb2, and no other notebooks are currently open, then enter:
evaluateMuPADNotebook(allMuPADNotebooks)
3-15
3 MuPAD in Symbolic Math Toolbox
evaluateMuPADNotebook(allMuPADNotebooks,'IgnoreErrors',true)
3-16
Close MuPAD Notebooks from MATLAB
Note: MuPAD notebooks are not recommended. Use MATLAB live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some. For
more information, see Convert MuPAD Notebooks to MATLAB Live Scripts on page
3-19.
To close notebooks from the MATLAB Command Window, use the close function and
specify the handle to that notebook. For example, create the notebook with the handle
nb:
nb = mupad;
close(nb)
If you do not have a handle to the notebook (for example, if you created it without
specifying a handle or accidentally deleted the handle later), use allMuPADNotebooks
to return handles to all currently open notebooks. This function returns a vector of
handles. For example, create three notebooks without handles:
mupad
mupad
mupad
nbhandles = allMuPADNotebooks
nbhandles =
Notebook1
Notebook2
Notebook3
close(nbhandles(1))
3-17
3 MuPAD in Symbolic Math Toolbox
close(allMuPADNotebooks)
If you modify a notebook and then try to close it, MuPAD brings up the dialog box asking
if you want to save changes. To suppress this dialog box, call close with the 'force'
flag. You might want to use this flag if your task requires opening many notebooks,
evaluating them, and then closing them. For example, suppose that you want to evaluate
the notebooks myFile1.mn, myFile2.mn, ..., myFile10.mn located in your current
folder. First, open the notebooks. If you do not have any other notebooks open, you can
skip specifying the handles and later use allMuPADNotebooks. Otherwise, do not forget
to specify the handles.
mupad('myFile1.mn')
mupad('myFile2.mn')
...
mupad('myFile10.mn')
When you evaluate MuPAD notebooks, you also modify them. Therefore, when you try to
close them, the dialog box asking you to save changes will appear for each notebook. To
suppress the dialog box and discard changes, use the 'force' flag:
close(allMuPADNotebooks,'force')
3-18
Convert MuPAD Notebooks to MATLAB Live Scripts
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 3-25. If you
cannot fix your error, and the Known Issues on page 3-20 do not help, please
contact 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
3-19
3 MuPAD in Symbolic Math Toolbox
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 3-34.
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 3-20 listed below.
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
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.
Procedures or function definitions, except trivial functions created by using the arrow
operator, such as f := x->x^2.
3-20
Convert MuPAD Notebooks to MATLAB Live Scripts
In MATLAB, when symbolic variables are assigned values, then expressions containing
those values are not automatically updated.
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.
3-21
3 MuPAD in Symbolic Math Toolbox
Instead of using ans, assign the result to a variable and use that variable.
There is no general solution. Further, non-finite solution sets are not translatable.
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.
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.
3-22
Convert MuPAD Notebooks to MATLAB Live Scripts
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];
When performing operations on matrices, search for the matrix operation and use it
instead. For example, in MATLAB:
3-23
3 MuPAD in Symbolic Math Toolbox
indets is translated to MATLAB symvar. However, symvar does not find bound
variables or constant identifiers like PI.
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 3-48.
3-24
Troubleshoot MuPAD to MATLAB Translation Errors
3-25
3 MuPAD in Symbolic Math Toolbox
3-26
Troubleshoot MuPAD to MATLAB Translation Errors
Domains, function
environments, and their
slots are not available in
MATLAB.
Unable to translate MuPAD lets you use special Adjust the code so that it
explicitly given coefficient coefficient rings that does not use polynomials
ring. cannot be represented by over special rings.
arithmetical expressions.
Specifying coefficient
rings of polynomials is not
available in MATLAB.
Unable to translate MuPAD uses the value Adjust the code so
complexInfinity. complexInfinity. This that it does not use
value is not available in complexInfinity.
MATLAB.
Unable to translate MuPAD MuPAD syntax has changed Update code to use
code because it uses an and the code uses obsolete current MuPAD syntax
obsolete calling syntax. syntax that is no longer by checking MuPAD
supported. documentation and then run
convertMuPADNotebook
again.
Unable to translate MuPAD Domains represent data Adjust the code so that it
domains, or commands to types in MuPAD. They are does not create or explicitly
create domains or their not available in MATLAB. use domains and their
elements. elements.
3-27
3 MuPAD in Symbolic Math Toolbox
convertMuPADNotebook
cannot translate MuPAD
environment variables
because they are not
available in MATLAB.
Unable to translate function In MuPAD, a function call Adjust the code so that it
calls with expression f(x), where x is a sequence does not contain function
sequences as input of n operands, resolves to a calls with expression
arguments. call with n arguments. sequences as input
arguments.
MATLAB cannot resolve
function calls with
expression sequences
to calls with multiple
arguments.
Unable to translate ''{0}'' to Every call to a function Adjust the code so that every
a symbolic function because must have the same number call to the function has the
the number of arguments of arguments. same number of arguments.
varies.
3-28
Troubleshoot MuPAD to MATLAB Translation Errors
3-29
3 MuPAD in Symbolic Math Toolbox
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.
More complicated
procedures cannot be
translated to MATLAB
code.
3-30
Troubleshoot MuPAD to MATLAB Translation Errors
3-31
3 MuPAD in Symbolic Math Toolbox
The MATLAB
rewrite function
supports fewer targets:
exp,log,sincos,sin,cos,tan,
cot,sqrt, heaviside,
asin, acos, atan, acot,
sinh, cosh, tanh, coth,
sinhcosh, asinh, acosh,
atanh, acoth, piecewise.
Syntax error in MuPAD MuPAD code contains a Check and correct the
code. syntax error, for example, a MuPAD code that you are
missing bracket. translating.
Test environment of The MuPAD test Adjust the code so that it
MuPAD not available in environment is not available does not use the MuPAD test
MATLAB. in MATLAB. environment.
Unable to translate physical Units of measurement, Adjust the code so that
units. such as m, cm, kg, oz, and it does not use units of
so on are not available in measurement.
MATLAB.
3-32
Troubleshoot MuPAD to MATLAB Translation Errors
3-33
3 MuPAD in Symbolic Math Toolbox
3-34
Troubleshoot MuPAD to MATLAB Translation Warnings
convertMuPADNotebook
corrected it.
Invalid assignment to When translating Verify the corrected code.
remember table. Replacing a notebook file, Then delete this warning.
it by procedure definition. convertMuPADNotebook
considered an assignment
to a remember table in
a MuPAD notebook as
unintentional, and replaced
it by a procedure definition.
For example, an assignment
such as f(x):=x^2 gets
replaced by f:= x->x^2.
3-35
3 MuPAD in Symbolic Math Toolbox
3-36
Troubleshoot MuPAD to MATLAB Translation Warnings
3-37
3 MuPAD in Symbolic Math Toolbox
3-38
Troubleshoot MuPAD to MATLAB Translation Warnings
3-39
3 MuPAD in Symbolic Math Toolbox
Protecting procedures
and functions from
overwriting is not available
in MATLAB. When
translating a notebook file,
convertMuPADNotebook
ignores the corresponding
MuPAD code.
3-40
Troubleshoot MuPAD to MATLAB Translation Warnings
3-41
3 MuPAD in Symbolic Math Toolbox
Note: MuPAD notebooks are not recommended. Use MATLAB live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some. For
more information, see Convert MuPAD Notebooks to MATLAB Live Scripts on page
3-19.
The default interface for editing MuPAD code is the MATLAB Editor. Alternatively,
you can create and edit your code in any text editor. The MATLAB Editor automatically
formats the code and, therefore, helps you avoid errors, or at least reduce their number.
To open an existing MuPAD file with the extension .mu in the MATLAB Editor, double-
click the file name or select Open and navigate to the file.
3-42
Edit MuPAD Code in MATLAB Editor
After editing the code, save the file. Note that the extension .mu allows the Editor to
recognize and open MuPAD program files. Thus, if you intend to open the files in the
MATLAB Editor, save them with the extension .mu. Otherwise, you can specify other
extensions suitable for text files, for example, .txt or .tst.
3-43
3 MuPAD in Symbolic Math Toolbox
3-44
Notebook Files and Program Files
Note: MuPAD notebooks are not recommended. Use MATLAB live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some. For
more information, see Convert MuPAD Notebooks to MATLAB Live Scripts on page
3-19.
A notebook file has the extension .mn and lets you store the result of the work performed
in the MuPAD Notebook app. A notebook file can contain text, graphics, and any MuPAD
commands and their outputs. A notebook file can also contain procedures and functions.
By default, a notebook file opens in the MuPAD Notebook app. Creating a new notebook
or opening an existing one does not automatically start the MuPAD engine. This means
that although you can see the results of computations as they were saved, MuPAD does
not remember evaluating them. (The MuPAD Workspace is empty.) You can evaluate
any or all commands after opening a notebook.
A program file is a text file that contains any code snippet that you want to store
separately from other computations. Saving a code snippet as a program file can be very
helpful when you want to use the code in several notebooks. Typically, a program file
contains a single procedure, but it also can contain one or more procedures or functions,
assignments, statements, tests, or any other valid MuPAD code.
Tip If you use a program file to store a procedure, MuPAD does not require the name of
that program file to match the name of a procedure.
The most common approach is to write a procedure and save it as a program file with the
extension .mu. This extension allows the MATLAB Editor to recognize and open the file
later. Nevertheless, a program file is just a text file. You can save a program file with any
extension that you use for regular text files.
3-45
3 MuPAD in Symbolic Math Toolbox
To evaluate the commands from a program file, you must execute a program file in a
notebook. For details about executing program files, see Read MuPAD Procedures on
page 3-62.
3-46
Source Code of the MuPAD Library Functions
Note: MuPAD notebooks are not recommended. Use MATLAB live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some. For
more information, see Convert MuPAD Notebooks to MATLAB Live Scripts on page
3-19.
You can display the source code of the MuPAD built-in library functions. If you work in
the MuPAD Notebook app, enter expose(name), where name is the library function
name. The MuPAD Notebook app displays the code as plain text with the original line
breaks and indentations.
You can also display the code of a MuPAD library function in the MATLAB Command
Window. To do this, use the evalin or feval function to call the MuPAD expose
function:
sprintf(char(feval(symengine, 'expose', 'numlib::tau')))
ans =
1375 char array
proc(a)
name numlib::tau;
begin
if args(0) <> 1 then
error(message("symbolic:numlib:IncorrectNumberOfArguments"))
else
if (~testtype(a, Type::Numeric)) then
return(procname(args()))
else
if domtype(a) <> DOM_INT then
error(message("symbolic:numlib:ArgumentInteger"))
end_if
end_if
end_if;
numlib::numdivisors(a)
end_proc
MuPAD also includes kernel functions written in C++. You cannot access the source code
of these functions.
3-47
3 MuPAD in Symbolic Math Toolbox
Note: MuPAD notebooks are not recommended. Use MATLAB live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some. For
more information, see Convert MuPAD Notebooks to MATLAB Live Scripts on page
3-19.
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 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.
3-48
Differences Between MATLAB and MuPAD Syntax
The next table lists differences between MATLAB expressions and MuPAD expressions.
3-49
3 MuPAD in Symbolic Math Toolbox
The MuPAD definition of exponential integral differs from the Symbolic Math Toolbox
counterpart.
3-50
Copy Variables and Expressions Between MATLAB and MuPAD
Note: MuPAD notebooks are not recommended. Use MATLAB live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some. For
more information, see Convert MuPAD Notebooks to MATLAB Live Scripts on page
3-19.
You can copy a variable from a MuPAD notebook to a variable in the MATLAB
workspace using a MATLAB command. Similarly, you can copy a variable or symbolic
expression in the MATLAB workspace to a variable in a MuPAD notebook using a
MATLAB command. To do either assignment, you need to know the handle to the
MuPAD notebook you want to address.
The only way to assign variables between a MuPAD notebook and the MATLAB
workspace is to open the notebook using the following syntax:
nb = mupad;
You can use any variable name for the handle nb. To open an existing notebook file, use
the following syntax:
nb = mupad('file_name');
Here file_name must be a full path unless the notebook is in the current folder. The
handle nb is used only for communication between the MATLAB workspace and the
MuPAD notebook.
setVar(notebook_handle,'MuPADvar',MATLABvar)
For example, if nb is the handle to the notebook and z is the variable, enter:
setVar(nb,'z',z)
There is no indication in the MuPAD notebook that variable z exists. To check that it
exists, enter the command anames(All, User) in the notebook.
3-51
3 MuPAD in Symbolic Math Toolbox
setVar(notebook_handle,'variable',expression)
at the MATLAB command line. For example, if nb is the handle to the notebook,
exp(x) - sin(x) is the expression, and z is the variable, enter:
syms x
setVar(nb,'z',exp(x) - sin(x))
Again, there is no indication in the MuPAD notebook that variable z exists. Check
that it exists by entering this command in the notebook:
anames(All, User)
To copy a symbolic variable in a MuPAD notebook to a variable in the MATLAB
workspace, enter in the MATLAB Command Window:
MATLABvar = getVar(notebook_handle,'variable');
For example, if nb is the handle to the notebook, z is the variable in the MuPAD
notebook, and u is the variable in the MATLAB workspace, enter:
u = getVar(nb,'z')
Communication between the MATLAB workspace and the MuPAD notebook occurs in
the notebook's engine. Therefore, variable z must be synchronized into the notebook's
MuPAD engine before using getVar, and not merely displayed in the notebook. If you
try to use getVar to copy an undefined variable z in the MuPAD engine, the resulting
MATLAB variable u is empty. For details, see Evaluate MuPAD Notebooks from
MATLAB on page 3-13.
Tip Do all copying and assignments from the MATLAB workspace, not from a MuPAD
notebook.
3-52
Copy Variables and Expressions Between MATLAB and MuPAD
setvar(nb, z, z)
Select the output with the mouse and copy it to the clipboard:
exp(x)/(x^2 + 1)
3-53
3 MuPAD in Symbolic Math Toolbox
If you paste it into Microsoft WordPad on a Windows system, the result is a picture.
3-54
Reserved Variable and Function Names
Note: MuPAD notebooks are not recommended. Use MATLAB live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some. For
more information, see Convert MuPAD Notebooks to MATLAB Live Scripts on page
3-19.
Both MATLAB and MuPAD have their own reserved keywords, such as function names,
special values, and names of mathematical constants. Using reserved keywords as
variable or function names can result in errors. If a variable name or a function name is a
reserved keyword in one or both interfaces, you can get errors or incorrect results. If you
work in one interface and a name is a reserved keyword in another interface, the error
and warning messages are produced by the interface you work in. These messages can
specify the cause of the problem incorrectly.
Tip The best approach is to avoid using reserved keywords as variable or function names,
especially if you use both interfaces.
In MuPAD, function names are protected. Normally, the system does not let you redefine
a standard function or use its name as a variable. (To be able to modify a standard
MuPAD function you must first remove its protection.) Even when you work in the
MATLAB Command Window, the MuPAD engine handles symbolic computations.
Therefore, MuPAD function names are reserved keywords in this case. Using a MuPAD
function name while performing symbolic computations in the MATLAB Command
Window can lead to an error:
solve('D - 10')
The message does not indicate the real cause of the problem:
To fix this issue, use the syms function to declare D as a symbolic variable. Then call the
symbolic solver without using quotes:
syms D
3-55
3 MuPAD in Symbolic Math Toolbox
solve(D - 10)
In this case, the toolbox replaces D with some other variable name before passing the
expression to the MuPAD engine:
ans =
10
To list all MuPAD function names, enter this command in the MATLAB Command
Window:
evalin(symengine, 'anames()')
3-56
Call Built-In MuPAD Functions from MATLAB
Note: MuPAD notebooks are not recommended. Use MATLAB live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some. For
more information, see Convert MuPAD Notebooks to MATLAB Live Scripts on page
3-19.
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);
3-57
3 MuPAD in Symbolic Math Toolbox
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)
ans =
0
feval(symengine, 'numeric::fsolve',f,'x=3')
ans =
x == 3.0699801238394654654386548746678
As you might expect, the answer is the numerical value of 3p . 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)
3-58
Call Built-In MuPAD Functions from MATLAB
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)
ans =
0.028005841168289
ans =
0.028005841168289177028337498391181
For further computations, set the format for displaying outputs back to short:
3-59
3 MuPAD in Symbolic Math Toolbox
format short
3-60
Use Your Own MuPAD Procedures
Note: MuPAD notebooks are not recommended. Use MATLAB live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some. For
more information, see Convert MuPAD Notebooks to MATLAB Live Scripts on page
3-19.
To define a procedure, use the proc function. Enclose the code in the begin and
end_proc functions:
myProc:= proc(n)
begin
if n = 1 or n = 0 then
1
else
n * myProc(n - 1)
end_if;
end_proc:
By default, a MuPAD procedure returns the result of the last executed command.
You can force a procedure to return another result by using return. In both cases, a
procedure returns only one result. To get multiple results from a procedure, combine
them into a list or other data structure, or use the print function.
If you just want to display the results, and do not need to use them in further
computations, use the print function. With print, your procedure still returns one
result, but prints intermediate results on screen. For example, this procedure prints
the value of its argument in each call:
myProcPrint:= proc(n)
begin
print(n);
if n = 0 or n = 1 then
return(1);
3-61
3 MuPAD in Symbolic Math Toolbox
end_if;
n * myProcPrint(n - 1);
end_proc:
If you want to use multiple results of a procedure, use ordered data structures, such
as lists or matrices as return values. In this case, the result of the last executed
command is technically one object, but it can contain more than one value. For
example, this procedure returns the list of two entries:
myProcSort:= proc(a, b)
begin
if a < b then
[a, b]
else
[b, a]
end_if;
end_proc:
Avoid using unordered data structures, such as sequences and sets, to return multiple
results of a procedure. The order of the entries in these structures can change
unpredictably.
When you save the procedure, it is recommended to use the extension .mu. For details,
see Notebook Files and Program Files on page 3-45. The name of the file can differ from
the name of the procedure. Also, you can save multiple procedures in one file.
If you work in the MuPAD Notebook app and create a separate program file that contains
a procedure, use one of the following methods to execute the procedure in a notebook. The
first approach is to select Notebook > Read Commands from the main menu.
Alternatively, you can use the read function. The function call read(filename)
searches for the program file in this order:
3-62
Use Your Own MuPAD Procedures
If you want to call the procedure from the MATLAB Live Editor, you still need to execute
that procedure before calling it. See Call Your Own MuPAD Procedures on page
3-63.
Suppose you wrote the myProc procedure that computes the factorial of a nonnegative
integer.
3-63
3 MuPAD in Symbolic Math Toolbox
Save the procedure as a file with the extension .mu. For example, save the procedure as
myProcedure.mu in the folder C:/MuPAD.
Return to the MATLAB Command Window. Before calling the procedure at the MATLAB
command line, enter:
read(symengine, 'C:/MuPAD/myProcedure.mu')
The read command reads and executes the myProcedure.mu file in MuPAD. After that,
you can call the myProc procedure with any valid parameter. For example, compute the
factorial of 15:
ans =
1307674368000
If your MuPAD procedure accepts character vector arguments, enclose these arguments
in two sets of quotes: double quotes inside single quotes. Single quotes suppress
evaluation of the argument before passing it to the MuPAD procedure, and double quotes
3-64
Use Your Own MuPAD Procedures
let MuPAD recognize that the argument is a character vector. For example, this MuPAD
procedure converts a character vector to lowercase and checks if reverting that character
vector changes it.
In the MATLAB Command Window, use the read command to read and execute
reverted.mu.
read(symengine, 'C:/MuPAD/reverted.mu')
Now, use feval to call the procedure reverted. To pass a character vector argument to
the procedure, use double quotes inside single quotes.
feval(symengine, 'reverted', '"Abccba"')
ans =
1
3-65
3 MuPAD in Symbolic Math Toolbox
Note: MuPAD notebooks are not recommended. Use MATLAB live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some. For
more information, see Convert MuPAD Notebooks to MATLAB Live Scripts on page
3-19.
The symbolic engine workspace associated with the MATLAB workspace is usually
empty. The MATLAB workspace tracks the values of symbolic variables, and passes
them to the symbolic engine for evaluation as necessary. However, the symbolic engine
workspace contains all assumptions you make about symbolic variables, such as whether
a variable is real, positive, integer, greater or less than some value, and so on. These
assumptions can affect solutions to equations, simplifications, and transformations, as
explained in Effects of Assumptions on Computations on page 3-68.
syms x
x = sym('x');
clear x
clear any existing value of x in the MATLAB workspace, but do not clear assumptions
about x in the symbolic engine workspace.
If you make an assumption about the nature of a variable, for example, using the
commands
syms x
assume(x,'real')
or
syms x
assume(x > 0)
then clearing the variable x from the MATLAB workspace does not clear the assumption
from the symbolic engine workspace. To clear the assumption, enter the command
assume(x,'clear')
3-66
Clear Assumptions and Reset the Symbolic Engine
For details, see Check Assumptions Set On Variables on page 3-67 and Effects of
Assumptions on Computations on page 3-68.
MATLAB no longer recognizes any symbolic variables that exist in the MATLAB
workspace. Clear the variables with the clear command, or renew them with the syms
or sym command.
This example shows how the MATLAB workspace and the symbolic engine workspace
respond to a sequence of commands.
If the function returns an empty symbolic object, there are no additional assumptions on
the variable. (The default assumption is that x can be any complex number.) Otherwise,
there are additional assumptions on the value of that variable.
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)
3-67
3 MuPAD in Symbolic Math Toolbox
ans =
in(x, 'real')
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]
assumptions
ans =
Empty sym: 1-by-0
ans =
-1
1
-1i
1i
3-68
Clear Assumptions and Reset the Symbolic Engine
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
syms x
assumptions(x)
solve(x^4 == 1, x)
ans =
[ 0 < x, in(x, 'real')]
ans =
1
assume(x,'clear')
assumptions(x)
ans =
Empty sym: 1-by-0
3-69
3 MuPAD in Symbolic Math Toolbox
Note: MuPAD notebooks are not recommended. Use MATLAB live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some. For
more information, see Convert MuPAD Notebooks to MATLAB Live Scripts on page
3-19.
Symbolic Math Toolbox lets you create a MATLAB function from a symbolic expression.
A MATLAB function created from a symbolic expression accepts numeric arguments and
evaluates the expression applied to the arguments. You can generate a function handle
or a file that contains a MATLAB function. The generated file is available for use in any
MATLAB calculation, independent of a license for Symbolic Math Toolbox functions.
If you work in the MATLAB Live Editor, see Generate MATLAB Functions from
Symbolic Expressions on page 2-222.
When you use the MuPAD Notebook app, all your symbolic expressions are written in
the MuPAD language. To be able to create a MATLAB function from such expressions,
you must convert it to the MATLAB language. There are two approaches for converting a
MuPAD expression to the MATLAB language:
Assign the MuPAD expression to a variable, and copy that variable from a notebook to
the MATLAB workspace. This approach lets you create a function handle or a file that
contains a MATLAB function. It also requires using a handle to the notebook.
Generate MATLAB code from the MuPAD expression in a notebook. This approach
limits your options to creating a file. You can skip creating a handle to the notebook.
The generated MATLAB function can depend on the approach that you chose. For
example, code can be optimized differently or not optimized at all.
Suppose you want to create a MATLAB function from a symbolic matrix that converts
spherical coordinates of any point to its Cartesian coordinates. First, open a MuPAD
notebook with the handle notebook_handle:
notebook_handle = mupad;
In this notebook, create the symbolic matrix S that converts spherical coordinates to
Cartesian coordinates:
3-70
Create MATLAB Functions from MuPAD Expressions
x := r*sin(a)*cos(b):
y := r*sin(a)*sin(b):
z := r*cos(b):
S := matrix([x, y, z]):
Now convert matrix S to the MATLAB language. Choose the best approach for your task.
S = getVar(notebook_handle,'S')
Variable S and its value (the symbolic matrix) appear in the MATLAB workspace
and in the MATLAB Live Editor:
S =
r*cos(b)*sin(a)
r*sin(a)*sin(b)
r*cos(b)
2 Use matlabFunction to create a MATLAB function from the symbolic matrix. To
generate a MATLAB function handle, use matlabFunction without additional
parameters:
h = matlabFunction(S)
h =
@(a,b,r)[r.*cos(b).*sin(a);r.*sin(a).*sin(b);r.*cos(b)]
To generate a file containing the MATLAB function, use the parameter file and
specify the path to the file and its name. For example, save the MATLAB function to
the file cartesian.m in the current folder:
S = matlabFunction(S,'file', 'cartesian.m');
3-71
3 MuPAD in Symbolic Math Toolbox
Note: If the file with this name already exists, fprint replaces the contents of this
file with the converted expression.
2 Open cartesian.m. It contains a MATLAB formatted character vector representing
matrix S:
S = zeros(3,1);
S(1,1) = r*cos(b)*sin(a);
S(2,1) = r*sin(a)*sin(b);
S(3,1) = r*cos(b);
3 To convert this file to a valid MATLAB function, add the keywords function and
end, the function name (must match the file name), input and output arguments,
and comments:
3-72
Create MATLAB Functions from MuPAD Expressions
3-73
3 MuPAD in Symbolic Math Toolbox
Note: MuPAD notebooks are not recommended. Use MATLAB live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some. For
more information, see Convert MuPAD Notebooks to MATLAB Live Scripts on page
3-19.
Symbolic Math Toolbox lets you create a MATLAB function block from a symbolic
expression. The generated block is available for use in Simulink models, whether or not
the computer that runs the simulations has a license for Symbolic Math Toolbox.
If you work in the MATLAB Live Editor, see Generate MATLAB Function Blocks
from Symbolic Expressions on page 2-226. Working in the MATLAB Live Editor is
recommended.
The MuPAD Notebook app does not provide a function for generating a block. Therefore,
to be able to create a block from the MuPAD expression:
For details about these steps, see Copy MuPAD Variables to the MATLAB Workspace
on page 3-71.
When the expression that you want to use for creating a MATLAB function block appears
in the MATLAB workspace, use the matlabFunctionBlock function to create a block
from that expression.
3-74
Create MATLAB Function Blocks from MuPAD Expressions
Variable r and its value appear in the MATLAB workspace and in the MATLAB Live
Editor:
r =
(x^2 + y^2)^(1/2)
Before generating a MATLAB Function block from the expression, create an empty model
or open an existing one. For example, create and open the new model my_system:
new_system('my_system')
open_system('my_system')
Since the variable and its value are in the MATLAB workspace, you can use
matlabFunctionBlock to generate the block my_block:
matlabFunctionBlock('my_system/my_block', r)
You can open and edit the block in the MATLAB Editor. To open the block, double-click
it:
function r = my_block(x,y)
%#codegen
r = sqrt(x.^2+y.^2);
3-75
3 MuPAD in Symbolic Math Toolbox
Note: MuPAD notebooks are not recommended. Use MATLAB live scripts instead.
MATLAB live scripts support most MuPAD functionality, though there are some. For
more information, see Convert MuPAD Notebooks to MATLAB Live Scripts on page
3-19.
Symbolic Math Toolbox lets you integrate symbolic computations into the Simscape
modeling workflow by using the results of these computations in the Simscape equation
section.
If you work in the MATLAB Live Editor, see Generate Simscape Equations from
Symbolic Expressions on page 2-228. Working in the MATLAB Live Editor is
recommended.
Assign the MuPAD expression to a variable, copy that variable from a notebook to the
MATLAB workspace, and use simscapeEquation to generate the Simscape equation
in the MATLAB Command Window.
Generate the Simscape equation from the MuPAD expression in a notebook.
In both cases, to use the generated equation, you must manually copy the equation and
paste it to the equation section of the Simscape component file.
For example, follow these steps to generate a Simscape equation from the solution of the
ordinary differential equation computed in the MuPAD Notebook app:
notebook_handle = mupad;
2 In this notebook, define the following equation:
3-76
Create Simscape Equations from MuPAD Expressions
print(Unquoted, generate::Simscape(s))
This command returns the Simscape equation that you can copy and paste to the
Simscape equation section:
-y^2+y.der == 0.0;
s = getVar(notebook_handle, 's')
Variable s and its value appear in the MATLAB workspace and in the MATLAB
Command Window:
s =
ode(diff(y(t), t) - y(t)^2, y(t))
2 Use simscapeEquation to generate the Simscape equation from s:
simscapeEquation(s)
You can copy and paste the generated equation to the Simscape equation section. Do not
copy the automatically generated variable ans and the equal sign that follows it.
ans =
s == (-y^2+y.der == 0.0);
3-77
4
abs
Absolute value of real or complex value
Syntax
abs(z)
abs(A)
Description
abs(z) returns the absolute value of z. If z is complex, abs(z) returns the complex
modulus (magnitude) of z.
abs(A) returns the absolute value of each element of A. If A is complex, abs(A) returns
the complex modulus (magnitude) of each element of A.
Input Arguments
z
Examples
Compute absolute values of these symbolic real numbers:
ans =
[ 1/2, 0, 4 - pi]
4-2
abs
ans =
[ 5^(1/2)/2, 25]
[ 2^(1/2), (pi*5^(1/2)*18^(1/2))/18]
Compute the absolute value of this expression assuming that the value x is negative:
syms x
assume(x < 0)
abs(5*x^3)
ans =
-5*x^3
More About
Complex Modulus
Tips
Calling abs for a number that is not a symbolic object invokes the MATLAB abs
function.
See Also
angle | imag | real | sign | signIm
4-3
4 Functions Alphabetical List
acos
Symbolic inverse cosine function
Syntax
acos(X)
Description
acos(X) returns the inverse cosine function (arccosine function) of X.
Examples
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]
4-4
acos
vpa(symA)
ans =
[ 3.1415926535897932384626433832795,...
1.9106332362490185563277142050315,...
2.0943951023931954923084289221863,...
1.318116071652817965745664254646,...
1.0471975511965977461542144610932,...
0.52359877559829887307710723054658,...
0]
syms x
fplot(acos(x), [-1, 1])
grid on
4-5
4 Functions Alphabetical List
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)
4-6
acos
ans =
-x/(1 - x^2)^(3/2)
ans =
x*acos(x) - (1 - x^2)^(1/2)
taylor(acos(x), x)
ans =
- (3*x^5)/40 - x^3/6 - x + pi/2
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
See Also
acot | acsc | asec | asin | atan | cos | cot | csc | sec | sin | tan
4-7
4 Functions Alphabetical List
acosh
Symbolic inverse hyperbolic cosine function
Syntax
acosh(X)
Description
acosh(X) returns the inverse hyperbolic cosine function of X.
Examples
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)]
4-8
acosh
vpa(symA)
ans =
[ 3.1415926535897932384626433832795i,...
1.5707963267948966192313216916398i,...
1.4033482475752072886780470855961i,...
1.0471975511965977461542144610932i,...
0,...
1.316957896924816708625046347308]
syms x
fplot(acosh(x), [1, 10])
grid on
4-9
4 Functions Alphabetical List
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 =
4-10
acosh
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)
ans =
x*acosh(x) - (x - 1)^(1/2)*(x + 1)^(1/2)
ans =
(x^5*3i)/40 + (x^3*1i)/6 + x*1i - (pi*1i)/2
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
See Also
acoth | acsch | asech | asinh | atanh | cosh | coth | csch | sech | sinh | tanh
4-11
4 Functions Alphabetical List
4-12
acot
acot
Symbolic inverse cotangent function
Syntax
acot(X)
Description
acot(X) returns the inverse cotangent function (arccotangent function) of X.
Examples
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]
4-13
4 Functions Alphabetical List
vpa(symA)
ans =
[ -0.78539816339744830961566084581988,...
-1.2490457723982544258299170772811,...
-1.0471975511965977461542144610932,...
1.1071487177940905030170654601785,...
0.78539816339744830961566084581988,...
0.52359877559829887307710723054658]
syms x
fplot(acot(x), [-10, 10])
grid on
4-14
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)
4-15
4 Functions Alphabetical List
ans =
(2*x)/(x^2 + 1)^2
ans =
log(x^2 + 1)/2 + x*acot(x)
ans =
- x^5/5 + x^3/3 - x + pi/2
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
See Also
acos | acsc | asec | asin | atan | cos | cot | csc | sec | sin | tan
4-16
acoth
acoth
Symbolic inverse hyperbolic cotangent function
Syntax
acoth(X)
Description
acoth(X) returns the inverse hyperbolic cotangent function of X.
Examples
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 =
4-17
4 Functions Alphabetical List
vpa(symA)
ans =
[ -0.75246926714192715916204347800251,...
Inf,...
-1.5707963267948966192313216916398i,...
0.54930614433405484569762261846126...
- 1.5707963267948966192313216916398i,...
Inf,...
0.75246926714192715916204347800251]
syms x
fplot(acoth(x), [-10, 10])
grid on
4-18
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)
4-19
4 Functions Alphabetical List
ans =
(2*x)/(x^2 - 1)^2
ans =
log(x^2 - 1)/2 + x*acoth(x)
ans =
x^5/5 + x^3/3 + x - (pi*1i)/2
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
See Also
acosh | acsch | asech | asinh | atanh | cosh | coth | csch | sech | sinh | tanh
4-20
acsc
acsc
Symbolic inverse cosecant function
Syntax
acsc(X)
Description
acsc(X) returns the inverse cosecant function (arccosecant function) of X.
Examples
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)]
4-21
4 Functions Alphabetical List
vpa(symA)
ans =
[ -0.52359877559829887307710723054658,...
Inf,...
1.0471975511965977461542144610932,...
1.5707963267948966192313216916398...
- 1.3169578969248165734029498707969i,...
1.5707963267948966192313216916398,...
0.20135792079033079660099758712022]
syms x
fplot(acsc(x), [-10, 10])
grid on
4-22
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))
4-23
4 Functions Alphabetical List
ans =
2/(x^3*(1 - 1/x^2)^(1/2)) + 1/(x^5*(1 - 1/x^2)^(3/2))
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)
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
See Also
acos | acot | asec | asin | atan | cos | cot | csc | sec | sin | tan
4-24
acsch
acsch
Symbolic inverse hyperbolic cosecant function
Syntax
acsch(X)
Description
acsch(X) returns the inverse hyperbolic cosecant function of X.
Examples
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)]
4-25
4 Functions Alphabetical List
vpa(symA)
ans =
[ 0.52359877559829887307710723054658i,...
Inf,...
-1.0471975511965977461542144610932i,...
1.4436354751788103424932767402731,...
-1.5707963267948966192313216916398i,...
0.32745015023725844332253525998826]
syms x
fplot(acsch(x), [-10, 10])
grid on
4-26
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))
4-27
4 Functions Alphabetical List
ans =
2/(x^3*(1/x^2 + 1)^(1/2)) - 1/(x^5*(1/x^2 + 1)^(3/2))
ans =
x*asinh(1/x) + asinh(x)*sign(x)
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
See Also
acosh | acoth | asech | asinh | atanh | cosh | coth | csch | sech | sinh | tanh
4-28
adjoint
adjoint
Adjoint of symbolic square matrix
Syntax
X = adjoint(A)
Description
X = adjoint(A) returns the adjoint matrix X of A. The adjoint of a matrix A is the
matrix X, such that A*X = det(A)*eye(n) = X*A, where n is the number of rows in A
and eye(n) is the n-by-n identity matrix.
Input Arguments
A
Output Arguments
X
Examples
Compute the adjoint of this symbolic matrix:
syms x y z
A = sym([x y z; 2 1 0; 1 0 2]);
4-29
4 Functions Alphabetical List
X = adjoint(A)
X =
[ 2, -2*y, -z]
[ -4, 2*x - z, 2*z]
[ -1, y, x - 2*y]
Verify that A*X = det(A)*eye(3), where eye(3) is the 3-by-3 identity matrix:
isAlways(A*X == det(A)*eye(3))
ans =
33 logical array
1 1 1
1 1 1
1 1 1
isAlways(det(A)*eye(3) == X*A)
ans =
33 logical array
1 1 1
1 1 1
1 1 1
Compute the inverse of this matrix by computing its 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)]
isAlways(invA == inv(A))
ans =
22 logical array
1 1
1 1
4-30
adjoint
More About
Adjoint of Square Matrix
The adjoint 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.
Cofactor of Matrix
i+ j
a ji = ( -1 ) det ( Aij )
Aij is the submatrix of A obtained from A by removing the i-th row and j-th column.
See Also
det | inv | rank
Introduced in R2013a
4-31
4 Functions Alphabetical List
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 of the first kind, Ai(x), for each element of 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 4-40 following the syntax
for the MATLAB airy function.
4-32
airy
Examples
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.
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)
4-33
4 Functions Alphabetical List
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 4-33.
Plot the Airy Functions, and , 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
4-34
airy
syms y
z = x + 1i*y;
figure(2)
fsurf(abs(airy(z)))
title('|Ai(z)|')
a = gca;
a.ZLim = [0 10];
caxis([0 10])
4-35
4 Functions Alphabetical List
dAi =
-(3^(1/6)*gamma(2/3))/(2*pi)
dAi_vpa =
-0.2588194037928067984051835601892
4-36
airy
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
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)
4-37
4 Functions Alphabetical List
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))
syms x
aiFourier = fourier(airy(x))
aiFourier =
exp((w^3*1i)/3)
syms x
vpasolve(airy(x) == 0, x)
ans =
-226.99630507523600716771890962744
ans =
-4.0879494441309706166369887014574
4-38
airy
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 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.
4-39
4 Functions Alphabetical List
2 (3 / 2)
x
e 3 Ai ( x ) .
2
- Re( x (3 / 2) )
e 3 Bi ( x) .
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.
See Also
besseli | besselj | besselk | bessely
Introduced in R2012a
4-40
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.
Input Arguments
A
dim
Integer. For example, if A is a matrix, all(A,1) tests elements of each column and
returns a row vector of logical 1s and 0s. all(A,2) tests elements of each row and
returns a column vector of logical 1s and 0s.
Default: The first dimension that is not equal to 1 (non-singleton dimension). For
example, if A is a matrix, all(A) treats the columns of A as vectors.
4-41
4 Functions Alphabetical List
Examples
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
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]
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 =
12 logical array
1 0
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]
4-42
all
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 =
12 logical array
1 0
To test all elements of each row, use the value 2 as the second argument:
all(M, 2)
ans =
21 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
More About
Tips
4-43
4 Functions Alphabetical List
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.
See Also
and | any | isAlways | not | or | xor
Introduced in R2012a
4-44
allMuPADNotebooks
allMuPADNotebooks
All open notebooks
Syntax
L = allMuPADNotebooks
Description
L = allMuPADNotebooks returns a vector with handles (pointers) to all currently open
MuPAD notebooks.
Examples
Identify All Open Notebooks
Suppose that your current folder contains MuPAD notebooks named myFile1.mn and
myFile2.mn. Open them keeping their handles in variables nb1 and nb2, respectively.
Also create a new notebook with the handle nb3:
nb1 = mupad('myFile1.mn')
nb2 = mupad('myFile2.mn')
nb3 = mupad
nb1 =
myFile1
nb2 =
myFile2
nb3 =
Notebook1
4-45
4 Functions Alphabetical List
Suppose that there are no other open notebooks. Use allMuPADNotebooks to get a
vector of handles to these notebooks:
allNBs = allMuPADNotebooks
allNBs =
myFile1
myFile2
Notebook1
If you already created a MuPAD notebook without a handle or if you lost the handle to a
notebook, use allMuPADNotebooks to create a new handle. Alternatively, you can save
the notebook, close it, and then open it again using a handle.
Suppose that you already performed some computations in that notebook, and now want
to transfer a few variables to the MATLAB workspace. To be able to do it, you need to
create a handle to this notebook:
nb = allMuPADNotebooks
nb =
Notebook1
Now, you can use nb when transferring data and results between the notebook
Notebook1 and the MATLAB workspace. This approach does not require you to save
Notebook1.
getVar(nb,'x')
ans =
x
4-46
allMuPADNotebooks
Output Arguments
L All open MuPAD notebooks
vector of handles to notebooks
See Also
close | evaluateMuPADNotebook | getVar | mupad | mupadNotebookTitle |
openmn | setVar
Introduced in R2013b
4-47
4 Functions Alphabetical List
and
Logical AND for symbolic expressions
Syntax
A & B
and(A,B)
Description
A & B represents the logical conjunction. A & B is true only when both A and B are true.
Input Arguments
A
Examples
Combine these symbolic inequalities into the logical expression using &:
syms x y
xy = x >= 0 & y >= 0;
4-48
and
assume(xy)
ans =
[ 0 <= x, 0 <= y]
Combine two symbolic inequalities into the logical expression using &:
syms x
range = 0 < x & x < 1;
Replace variable x with these numeric values. If you replace x with 1/2, then both
inequalities are valid. If you replace x with 10, both inequalities are invalid. Note that
subs does not evaluate these inequalities to logical 1 or 0.
x1 = subs(range, x, 1/2)
x2 = subs(range, x, 10)
x1 =
0 < 1/2 & 1/2 < 1
x2 =
0 < 10 & 10 < 1
ans =
logical
1
ans =
logical
0
Note that simplify does not simplify these logical expressions to logical 1 or 0. Instead,
they return symbolic values TRUE or FALSE.
s1 = simplify(x1)
s2 = simplify(x2)
s1 =
TRUE
4-49
4 Functions Alphabetical List
s2 =
FALSE
isAlways(s1)
isAlways(s2)
ans =
logical
1
ans =
logical
0
The recommended approach to define a range of values is using &. Nevertheless, you can
define a range of values of a variable as follows:
syms x
range = 0 < x < 1;
Now if you want to replace variable x with numeric values, use symbolic numbers
instead of MATLAB double-precision numbers. To create a symbolic number, use sym
x1 = subs(range, x, sym(1/2))
x2 = subs(range, x, sym(10))
x1 =
(0 < 1/2) < 1
x2 =
(0 < 10) < 1
isAlways(x1)
isAlways(x2)
ans =
logical
1
ans =
logical
0
4-50
and
More About
Tips
If you call simplify for a logical expression containing symbolic subexpressions, you
can get symbolic values TRUE or FALSE. These values are not the same as logical 1
(true) and logical 0 (false). To convert symbolic TRUE or FALSE to logical values, use
isAlways.
See Also
all | any | isAlways | not | or | piecewise | xor
Introduced in R2012a
4-51
4 Functions Alphabetical List
angle
Symbolic polar angle
Syntax
angle(Z)
Description
angle(Z) computes the polar angle of the complex value Z.
Input Arguments
Z
Symbolic number, variable, expression, function. The function also accepts a vector or
matrix of symbolic numbers, variables, expressions, functions.
Examples
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]
4-52
angle
ans =
-(3*pi)/4
ans =
pi/4
ans =
[ pi/3, pi/6]
[ pi/4, pi/2]
Alternatives
For real X and Y such that Z = X + Y*i, the call angle(Z) is equivalent to
atan2(Y,X).
More About
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.
See Also
atan2 | conj | imag | real | sign | signIm
Introduced in R2013a
4-53
4 Functions Alphabetical List
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.
Input Arguments
A
dim
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.
Default: The first dimension that is not equal to 1 (non-singleton dimension). For
example, if A is a matrix, any(A) treats the columns of A as vectors.
4-54
any
Examples
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)
ans =
12 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]
4-55
4 Functions Alphabetical List
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 =
12 logical array
1 0
To test elements of each row, use the value 2 as the second argument:
any(M, 2)
ans =
21 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
More About
Tips
4-56
any
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.
See Also
all | and | isAlways | not | or | xor
Introduced in R2012a
4-57
4 Functions Alphabetical List
argnames
Input variables of symbolic function
Syntax
argnames(f)
Description
argnames(f) returns input variables of f.
Input Arguments
f
Symbolic function.
Examples
Create this symbolic function:
syms f(x, y)
f(x, y) = x + y;
argnames(f)
ans =
[ x, y]
syms f(a, b, x, y)
f(x, b, y, a) = a*x + b*y;
4-58
argnames
Use argnames to find input variables of f. When returning variables, argnames uses the
same order as you used when you defined the function:
argnames(f)
ans =
[ x, b, y, a]
See Also
formula | sym | syms | symvar
Introduced in R2012a
4-59
4 Functions Alphabetical List
asec
Symbolic inverse secant function
Syntax
asec(X)
Description
asec(X) returns the inverse secant function (arcsecant function) of X.
Examples
Compute the inverse secant function for these numbers. Because these numbers are not
symbolic objects, asec returns floating-point results.
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 =
[ (2*pi)/3, Inf, pi/6, acos(2), 0, acos(1/5)]
4-60
asec
vpa(symA)
ans =
[ 2.0943951023931954923084289221863,...
Inf,...
0.52359877559829887307710723054658,...
1.3169578969248165734029498707969i,...
0,...
1.3694384060045659001758622252964]
syms x
fplot(asec(x), [-10, 10])
grid on
4-61
4 Functions Alphabetical List
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))
4-62
asec
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)
taylor(asec(x), x, Inf)
ans =
pi/2 - 1/x - 1/(6*x^3) - 3/(40*x^5)
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
See Also
acos | acot | acsc | asin | atan | cos | cot | csc | sec | sin | tan
4-63
4 Functions Alphabetical List
asech
Symbolic inverse hyperbolic secant function
Syntax
asech(X)
Description
asech(X) returns the inverse hyperbolic secant function of X.
Examples
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)]
4-64
asech
vpa(symA)
ans =
[ 2.0943951023931954923084289221863i,...
Inf,...
0.52359877559829887307710723054658i,...
1.316957896924816708625046347308,...
0,...
1.230959417340774682134929178248i]
syms x
fplot(asech(x), [0, 1])
grid on
4-65
4 Functions Alphabetical List
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 =
4-66
asech
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)
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
See Also
acosh | acoth | acsch | asinh | atanh | cosh | coth | csch | sech | sinh | tanh
4-67
4 Functions Alphabetical List
asin
Symbolic inverse sine function
Syntax
asin(X)
Description
asin(X) returns the inverse sine function (arcsine function) of X.
Examples
Compute the inverse sine function for these numbers. Because these numbers are not
symbolic objects, asin returns floating-point results.
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 =
[ -pi/2, -asin(1/3), -pi/6, asin(1/4), pi/6, pi/3, pi/2]
4-68
asin
vpa(symA)
ans =
[ -1.5707963267948966192313216916398,...
-0.33983690945412193709639251339176,...
-0.52359877559829887307710723054658,...
0.25268025514207865348565743699371,...
0.52359877559829887307710723054658,...
1.0471975511965977461542144610932,...
1.5707963267948966192313216916398]
syms x
fplot(asin(x), [-1, 1])
grid on
4-69
4 Functions Alphabetical List
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)
4-70
asin
ans =
x/(1 - x^2)^(3/2)
ans =
x*asin(x) + (1 - x^2)^(1/2)
taylor(asin(x), x)
ans =
(3*x^5)/40 + x^3/6 + x
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
See Also
acos | acot | acsc | asec | atan | cos | cot | csc | sec | sin | tan
4-71
4 Functions Alphabetical List
asinh
Symbolic inverse hyperbolic sine function
Syntax
asinh(X)
Description
asinh(X) returns the inverse hyperbolic sine function of X.
Examples
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)]
4-72
asinh
vpa(symA)
ans =
[ -1.5707963267948966192313216916398i,...
0,...
0.16590455026930117643502171631553,...
0.52359877559829887307710723054658i,...
1.5707963267948966192313216916398i,...
1.4436354751788103012444253181457]
syms x
fplot(asinh(x), [-10, 10])
grid on
4-73
4 Functions Alphabetical List
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)
4-74
asinh
ans =
-x/(x^2 + 1)^(3/2)
ans =
x*asinh(x) - (x^2 + 1)^(1/2)
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
See Also
acosh | acoth | acsch | asech | atanh | cosh | coth | csch | sech | sinh | tanh
4-75
4 Functions Alphabetical List
assume
Set assumption on symbolic object
Syntax
assume(condition)
assume(expr,set)
assume(expr,'clear')
Description
assume(condition) states that condition is valid for all symbolic variables in
condition. It also removes any assumptions previously made on these symbolic
variables.
assume(expr,set) states that expr belongs to set. This new assumption replaces
previously set assumptions on all variables in expr.
Examples
Common Assumptions
Set an assumption using the associated syntax.
Assume x is Syntax
real assume(x,real)
rational assume(x,rational)
positive assume(x > 0)
an integer between 2 and 10 assume(in(x,'integer') & x>2 &
x<10)
4-76
assume
Assume x is Syntax
less than -1 or greater than 1 assume(x<-1 | x>1)
not equal to 0 assume(x ~= 0)
even assume(x/2,'integer')
odd assume((x - 1)/2,'integer')
between 0 and 2 assume(x>0 & x<2*pi)
a multiple of assume(x/pi,integer)
Assume x is even.
syms x
assume(x/2,'integer')
ans =
2
4
6
8
Assume x is odd by setting the assumption that (x-1)/2 is an integer. Find all odd
numbers between 0 and 10 using solve.
assume((x-1)/2,'integer')
solve(x>0,x<10,x)
ans =
1
3
5
7
9
4-77
4 Functions Alphabetical List
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))
Calculate the time during which the object falls from a certain height by solving the
kinematic equation for free fall motion. Assume the gravitational acceleration g is
positive.
syms g h t
assume(g > 0)
solve(h == g*t^2/2, t)
ans =
4-78
assume
(2^(1/2)*h^(1/2))/g^(1/2)
-(2^(1/2)*h^(1/2))/g^(1/2)
Additionally, you can set assumptions on variables for which you solve an equation.
When you set assumptions on such variables, the solver compares obtained solutions
with the specified assumptions. This additional task can slow down the solver.
assume(t > 0)
solve(h == g*t^2/2,t)
The solver returns a warning that h must be positive. This warning follows as the object
is above ground.
assume([g t],'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')
4-79
4 Functions Alphabetical List
simplify(sin(2*n*pi))
ans =
0
Assumptions on Expressions
Set assumption on the symbolic expression.
You can set assumptions not only on variables, but also on expressions. For example,
compute this integral.
syms x
int(1/abs(x^2 - 1),x)
ans =
-atanh(x)/sign(x^2 - 1)
ans =
-atanh(x)
ans =
4-80
assume
-5
-1
-1/3
1/2
100
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')
Create the 3-by-3 symbolic matrix A with auto-generated elements. Specify the 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]
4-81
4 Functions Alphabetical List
assumptions(A)
ans =
[ in(A3_1, 'rational'), in(A2_1, 'rational'), in(A1_1, 'rational'),...
in(A3_2, 'rational'), in(A2_2, 'rational'), in(A1_2, 'rational'),...
in(A3_3, 'rational'), in(A2_3, 'rational'), in(A1_3, 'rational')]
You can also use assume to set assumptions on all elements of a matrix. Assume all
elements of A are positive using assume.
assume(A,'positive')
assume(A,'clear')
Input Arguments
condition Assumption statement
symbolic expression | symbolic equation | symbolic relation | vector or matrix of
symbolic expressions, equations, or relations
4-82
assume
More About
Tips
assume removes any assumptions previously set on the symbolic variables. To retain
previous assumptions while adding a new 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 MuPAD 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. Make assumptions
on symbolic variables and expressions instead.
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','integer');
c = sym('c','positive');
d = sym('d','positive');
e = sym('e','rational');
or more efficiently
syms a real
syms b integer
syms c d positive
syms e rational
4-83
4 Functions Alphabetical List
See Also
and | assumeAlso | assumptions | clear all | in | isAlways | not | or |
piecewise | sym | syms
Introduced in R2012a
4-84
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.
Examples
syms x y
assume(x >= 0 & y >= 0)
s = solve(x^2 + y^2 == 1, y)
4-85
4 Functions Alphabetical List
(1 - x)^(1/2)*(x + 1)^(1/2)
-(1 - x)^(1/2)*(x + 1)^(1/2)
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 = solve(x^2 + y^2 == 1, y)
s =
(1 - x)^(1/2)*(x + 1)^(1/2)
assume([x y],'clear')
syms n positive
Using assumeAlso, add more assumptions on the same variable n. For example, assume
also that n is and integer.
assumeAlso(n,'integer')
assumptions(n)
ans =
[ in(n, 'integer'), 0 < n]
4-86
assumeAlso
assume(n,'clear')
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 =
[ 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'),...
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]
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.
4-87
4 Functions Alphabetical List
ans =
[ in(y, 'real'), y ~= 0, in(y*1i, 'real')]
Input Arguments
condition Assumption statement
symbolic expression | symbolic equation | relation | vector or matrix of symbolic
expressions, equations, or relations
4-88
assumeAlso
More About
Tips
assume(var,'clear')
To clear all objects in the MATLAB workspace and close the MuPAD 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.
4-89
4 Functions Alphabetical List
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.
See Also
and | assume | assumptions | clear all | in | isAlways | not | or | piecewise
| sym | syms
Introduced in R2012a
4-90
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
Assume that the variable n is an integer using assume. Return the assumption using
assumptions.
syms n
assume(n,'integer')
assumptions
ans =
in(n, 'integer')
Assume that n is less than x and that x < 42 using assume. 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)
4-91
4 Functions Alphabetical List
assumptions(n)
ans =
[ n < x, x < 42]
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])
ans =
[ 1 < m, m < 3, n < x, x < 42]
To see the assumptions that affect all variables, use assumptions without any
arguments.
assumptions
ans =
[ n < x, x < 42, 1 < m, m < 3]
ans =
4-92
assumptions
Set assumptions on variables in a symbolic expression. Find all assumptions that affect
all variables in the symbolic expression using assumptions.
syms a b c
expr = a*exp(b)*sin(c);
assume(a+b > 3 & in(a,'integer') & in(c,'real'))
assumptions(expr)
ans =
[ 3 < a + b, in(a, 'integer'), in(c, 'real')
Find all assumptions that affect all variables that are inputs to a symbolic function.
syms f(a,b,c)
assumptions(f)
ans =
[ 3 < a + b, in(a, 'integer'), in(c, 'real')]
Solve the equation for a spring using dsolve under the assumptions that the mass and
spring constant are positive.
syms m k positive
syms x(t)
4-93
4 Functions Alphabetical List
ans =
C8*sin((k^(1/2)*t)/m^(1/2))
ans =
C10*exp((t*(-k*m)^(1/2))/m) + C10*exp(-(t*(-k*m)^(1/2))/m)
Input Arguments
var Symbolic input to check for assumptions
symbolic variable | symbolic expression | symbolic function | symbolic vector | symbolic
matrix | symbolic multidimensional array
More About
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.
4-94
assumptions
To clear all assumptions set on a symbolic variable var use this command.
assume(var,'clear')
To close the MuPAD engine associated with the MATLAB workspace resetting all its
assumptions, use this command.
reset(symengine)
See Also
and | assume | assumeAlso | clear | clear all | in | isAlways | not | or |
piecewise | sym | syms
Introduced in R2012a
4-95
4 Functions Alphabetical List
atan
Symbolic inverse tangent function
Syntax
atan(X)
Description
atan(X) returns the inverse tangent function (arctangent function) of X.
Examples
Compute the inverse tangent function for these numbers. Because these numbers are not
symbolic objects, atan returns floating-point results.
A =
-0.7854 -0.3218 -0.5236 0.4636 0.7854 1.0472
Compute the inverse tangent function for the numbers converted to symbolic objects. For
many symbolic (exact) numbers, atan returns unresolved symbolic calls.
symA =
[ -pi/4, -atan(1/3), -pi/6, atan(1/2), pi/4, pi/3]
4-96
atan
vpa(symA)
ans =
[ -0.78539816339744830961566084581988,...
-0.32175055439664219340140461435866,...
-0.52359877559829887307710723054658,...
0.46364760900080611621425623146121,...
0.78539816339744830961566084581988,...
1.0471975511965977461542144610932]
syms x
fplot(atan(x), [-10, 10])
grid on
4-97
4 Functions Alphabetical List
Find the first and second derivatives of the inverse tangent function:
syms x
diff(atan(x), x)
diff(atan(x), x, x)
ans =
1/(x^2 + 1)
4-98
atan
ans =
-(2*x)/(x^2 + 1)^2
ans =
x*atan(x) - log(x^2 + 1)/2
taylor(atan(x), x)
ans =
x^5/5 - x^3/3 + x
ans =
(log(1 - x*1i)*1i)/2 - (log(1 + x*1i)*1i)/2
Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
See Also
acos | acot | acsc | asec | asin | atan2 | cos | cot | csc | sec | sin | tan
4-99
4 Functions Alphabetical List
atan2
Symbolic four-quadrant inverse tangent
Syntax
atan2(Y,X)
Description
atan2(Y,X) computes the four-quadrant inverse tangent (arctangent) of Y and X. If Y
and X are vectors or matrices, atan2 computes arctangents element by element.
Input Arguments
Y
Symbolic number, variable, expression, function. The function also accepts a vector or
matrix of symbolic numbers, variables, expressions, functions. If Y is a number, it must
be real. If Y is a vector or matrix, it must either be a scalar or have the same dimensions
as X. All numerical elements of Y must be real.
Symbolic number, variable, expression, function. The function also accepts a vector or
matrix of symbolic numbers, variables, expressions, functions. If X is a number, it must
be real. If X is a vector or matrix, it must either be a scalar or have the same dimensions
as Y. All numerical elements of X must be real.
Examples
Compute the arctangents of these parameters. Because these numbers are not symbolic
objects, you get floating-point results.
4-100
atan2
ans =
0.7854 0.6658 0.7854
Compute the arctangents of these parameters which are converted to symbolic objects:
ans =
[ pi/4, atan(pi/4), pi/4]
syms x
limit(atan2(x^2/(1 + x), x), x, -Inf)
limit(atan2(x^2/(1 + x), x), x, Inf)
ans =
-(3*pi)/4
ans =
pi/4
ans =
[ pi/3, pi/6]
[ pi/4, pi/2]
Alternatives
For complex Z = X + Y*i, the call atan2(Y,X) is equivalent to angle(Z).
More About
atan2 vs. atan
If X 0 and Y 0, then
4-101
4 Functions Alphabetical List
Y p
atan2 ( Y , X ) = atan( ) + sign ( Y ) (1 - sign ( X ) )
X 2
Results returned by atan2 belong to the closed interval [-pi,pi]. Results returned by
atan 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.
Symbolic arguments X and Y are assumed to be real.
If X = 0 and Y > 0, then atan2(Y,X) returns pi/2.
See Also
angle | atan | conj | imag | real
Introduced in R2013a
4-102
atanh
atanh
Symbolic inverse hyperbolic tangent function
Syntax
atanh(X)
Description
atanh(X) returns the inverse hyperbolic tangent function of X.
Examples
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)]
4-103
4 Functions Alphabetical List
vpa(symA)
ans =
[ -0.78539816339744830961566084581988i,...
0,...
0.1682361183106064652522967051085,...
0.46364760900080611621425623146121i,...
0.78539816339744830961566084581988i,...
0.54930614433405484569762261846126 - 1.5707963267948966192313216916398i]
syms x
fplot(atanh(x), [-1, 1])
grid on
4-104
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)
4-105
4 Functions Alphabetical List
ans =
(2*x)/(x^2 - 1)^2
ans =
log(x^2 - 1)/2 + x*atanh(x)
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
See Also
acosh | acoth | acsch | asech | asinh | cosh | coth | csch | sech | sinh | tanh
4-106
bernoulli
bernoulli
Bernoulli numbers and polynomials
Syntax
bernoulli(n)
bernoulli(n,x)
Description
bernoulli(n) returns the nth Bernoulli number.
Examples
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 =
4-107
4 Functions Alphabetical List
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)
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
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
4-108
bernoulli
syms x
fplot(bernoulli(0:5, x), [-0.8 1.8])
title('Bernoulli Polynomials')
grid on
4-109
4 Functions Alphabetical List
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)
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))
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
4-110
bernoulli
More About
Bernoulli Polynomials
te xt tn
et - 1
= bernoulli (n, x) n !
n =0
Bernoulli Numbers
bernoulli ( n ) = bernoulli ( n, 0 )
See Also
euler
Introduced in R2014a
4-111
4 Functions Alphabetical List
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 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 handles results to symbolic.
Examples
syms t
4-112
bernstein
fplot(sin(2*pi*t),[0,1])
hold on
fplot(b10,[0,1])
fplot(b100,[0,1])
4-113
4 Functions Alphabetical List
syms x t
bernstein(exp(x), 2, t)
ans =
(t - 1)^2 + t^2*exp(1) - 2*t*exp(1/2)*(t - 1)
syms x y t
symvar(y*exp(x*y), 1)
ans =
x
bernstein(y*exp(x*y), 2, t)
ans =
y*(t - 1)^2 + t^2*y*exp(y) - 2*t*y*exp(y/2)*(t - 1)
bernstein(y*exp(x*y), y, 2, t)
ans =
t^2*exp(x) - t*exp(x/2)*(t - 1)
syms f(t)
4-114
bernstein
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)
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
4-115
4 Functions Alphabetical List
Input Arguments
f Function to be approximated by a polynomial
function handle
4-116
bernstein
t Evaluation point
number | symbolic number | symbolic variable | symbolic expression | symbolic
function
More About
Bernstein Polynomials
n
B (t ) = b k bk,n (t ).
k= 0
Here,
n n -k
bk,n ( t ) = tk (1 - t) , k = 0, , n
k
4-117
4 Functions Alphabetical List
n
are the Bernstein basis polynomials, and is a binomial coefficient.
k
n
k
Bn ( f ) ( t ) = f n bk,n ( t)
k =0
lim Bn ( f )( t ) = f ( t )
n
Tips
See Also
bernsteinMatrix | formula | nchoosek | symsum | symvar
Introduced in R2013b
4-118
bernsteinMatrix
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.
Examples
P = [0 1; 4 3; 6 2; 3 0; 2 4];
4-119
4 Functions Alphabetical List
syms t
B = bernsteinMatrix(4, t)
B =
[ (t - 1)^4, -4*t*(t - 1)^3, 6*t^2*(t - 1)^2, -4*t^3*(t - 1), t^4]
bezierCurve = simplify(B*P)
bezierCurve =
[ -2*t*(- 5*t^3 + 6*t^2 + 6*t - 8), 5*t^4 + 8*t^3 - 18*t^2 + 8*t + 1]
4-120
bernsteinMatrix
P = [0 0 0; 2 2 2; 2 -1 1; 6 1 3];
syms t
B = bernsteinMatrix(3,t)
B =
4-121
4 Functions Alphabetical List
bezierCurve =
[ 6*t*(t^2 - t + 1), t*(10*t^2 - 15*t + 6), 3*t*(2*t^2 - 3*t + 2)]
4-122
bernsteinMatrix
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
4-123
4 Functions Alphabetical List
Input Arguments
n Approximation order
nonnegative integer
t Evaluation point
number | vector | symbolic number | symbolic variable | symbolic expression | symbolic
vector
4-124
bernsteinMatrix
Output Arguments
B Bernstein matrix
matrix
See Also
bernstein | nchoosek | symsum | symvar
Introduced in R2013b
4-125
4 Functions Alphabetical List
besseli
Modified Bessel function of the first kind
Syntax
besseli(nu,z)
Description
besseli(nu,z) returns the modified Bessel function of the first kind, I(z).
Input Arguments
nu
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
4-126
besseli
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.
[besseli(sym(0), 5), besseli(sym(-1), 2),...
besseli(1/3, sym(7/4)), besseli(sym(1), 3/2 + 2*i)]
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)]
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.
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
4-127
4 Functions Alphabetical List
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))
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))
4-128
besseli
syms x
A = [-1, pi; x, 0];
besseli(1/2, A)
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')
4-129
4 Functions Alphabetical List
More About
Modified Bessel Functions of the First Kind
d2w dw
z2
2
dz
+z
dz
( )
- z2 + n 2 w = 0
4-130
besseli
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) = C1 In ( z ) + C2 Kn ( z )
This formula is the integral representation of the modified Bessel functions of the first
kind:
( z 2 )n p z cos( t) ( )2n
In ( z ) = e sin t dt
p G (n + 1 2 ) 0
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.
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 | | besselj | besselk | bessely
Introduced in R2014a
4-131
4 Functions Alphabetical List
besselj
Bessel function of the first kind
Syntax
besselj(nu,z)
Description
besselj(nu,z) returns the Bessel function of the first kind, J(z).
Input Arguments
nu
Examples
4-132
besselj
Compute the Bessel functions of the first kind for the numbers converted to symbolic
objects. For most symbolic (exact) numbers, besselj returns unresolved symbolic calls.
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)]
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 first kind is a valid solution of the Bessel
differential equation:
syms nu z
isAlways(z^2*diff(besselj(nu, z), z, 2) + z*diff(besselj(nu, z), z)...
+ (z^2 - nu^2)*besselj(nu, z) == 0)
ans =
logical
1
4-133
4 Functions Alphabetical List
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))
ans =
besselj(0, x) - besselj(1, x)/x
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))
4-134
besselj
syms x
A = [-1, pi; x, 0];
besselj(1/2, A)
ans =
[ (2^(1/2)*sin(1)*1i)/pi^(1/2), 0]
[ (2^(1/2)*sin(x))/(x^(1/2)*pi^(1/2)), 0]
syms x y
fplot(besselj(0:3, x))
axis([0 10 -0.5 1.1])
grid on
ylabel('J_v(x)')
legend('J_0','J_1','J_2','J_3', 'Location','Best')
title('Bessel functions of the first kind')
4-135
4 Functions Alphabetical List
More About
Bessel Functions of the First Kind
d2w dw
z2
2
dz
+z
dz
( )
+ z2 - n 2 w = 0
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):
4-136
besselj
w ( z) = C1Jn ( z) + C2 Yn ( z )
This formula is the integral representation of the Bessel functions of the first kind:
n p
( z 2) 2n
Jn ( z ) = cos ( z cos ( t ) ) sin ( t ) dt
p G (n + 1 2 ) 0
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.
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 | besseli | besselk | bessely
Introduced in R2014a
4-137
4 Functions Alphabetical List
besselk
Modified Bessel function of the second kind
Syntax
besselk(nu,z)
Description
besselk(nu,z) returns the modified Bessel function of the second kind, K(z).
Input Arguments
nu
Examples
4-138
besselk
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)]
syms x
besselk(1/2, x)
ans =
(2^(1/2)*pi^(1/2)*exp(-x))/(2*x^(1/2))
besselk(-1/2, x)
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))
4-139
4 Functions Alphabetical List
besselk(5/2, x)
ans =
(2^(1/2)*pi^(1/2)*exp(-x)*(3/x + 3/x^2 + 1))/(2*x^(1/2))
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
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)
4-140
besselk
syms x
A = [-1, pi; x, 0];
besselk(1/2, A)
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')
4-141
4 Functions Alphabetical List
More About
Modified Bessel Functions of the Second Kind
d2w dw
z2
2
dz
+z
dz
( )
- z2 + n 2 w = 0
4-142
besselk
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) = C1 In ( z ) + C2 Kn ( z )
The modified Bessel functions of the second kind are defined via the modified Bessel
functions of the first kind:
p 2
Kn ( z ) =
sin (np )
( I-n ( z ) - In ( z ))
Here I(z) are the modified Bessel functions of the first kind:
( z 2 )n p z cos( t) ( )2n
In ( z ) = e sin t dt
p G (n + 1 2 ) 0
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.
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.
4-143
4 Functions Alphabetical List
See Also
airy | besseli | besselj | bessely
Introduced in R2014a
4-144
bessely
bessely
Bessel function of the second kind
Syntax
bessely(nu,z)
Description
bessely(nu,z) returns the Bessel function of the second kind, Y(z).
Input Arguments
nu
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 =
4-145
4 Functions Alphabetical List
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.
[bessely(sym(0), 5), bessely(sym(-1), 2),...
bessely(1/3, sym(7/4)), bessely(sym(1), 3/2 + 2*i)]
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)]
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:
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
4-146
bessely
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))
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))
syms x
4-147
4 Functions Alphabetical List
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]
syms x y
fplot(bessely(0:3, x))
axis([0 10 -1 0.6])
grid on
ylabel('Y_v(x)')
legend('Y_0','Y_1','Y_2','Y_3', 'Location','Best')
title('Bessel functions of the second kind')
4-148
bessely
More About
Bessel Function of the Second Kind
d2w dw
z2
2
dz
+z
dz
( )
+ z2 - n 2 w = 0
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):
4-149
4 Functions Alphabetical List
w ( z) = C1Jn ( z) + C2 Yn ( z )
The Bessel functions of the second kind are defined via the Bessel functions of the first
kind:
n p
( z 2) 2n
Jn ( z ) = cos ( z cos ( t ) ) sin ( t ) dt
p G (n + 1 2 ) 0
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.
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 | besseli | besselj | besselk
4-150
bessely
Introduced in R2014a
4-151
4 Functions Alphabetical List
beta
Beta function
Syntax
beta(x,y)
Description
beta(x,y) returns the beta function of x and y.
Input Arguments
x
Examples
Compute the beta function for these numbers. Because these numbers are not symbolic
objects, you get floating-point results:
ans =
0.2000 0.1716 0.0379 Inf
4-152
beta
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):
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 =
4-153
4 Functions Alphabetical List
-2.836889094
ans =
(gamma(x)*gamma(y))/gamma(x + y)
ans =
-(x*gamma(x)*gamma(y))/(gamma(x + y) - y*gamma(x + y))
More About
Beta Function
1
y -1 G ( x ) G ( y)
B ( x, y ) = t x -1 (1 - t )
dt =
G( x + y )
0
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
4-154
beta
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.
References
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
Introduced in R2014a
4-155
4 Functions Alphabetical List
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
Create vectors A and B.
A = sym('a%d',[1 4])
B = sym('b%d',[1 4])
A =
[ a1, a2, a3, a4]
B =
[ b1, b2, b3, b4]
ans =
[ a1, a2, a3, a4]
[ b1, b2, b3, b4]
4-156
cat
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]
A(:,:,1) =
[ a11, a12]
[ a21, a22]
A(:,:,2) =
[ -a11, -a12]
[ -a21, -a22]
B(:,:,1) =
[ b11, b12]
[ b21, b22]
B(:,:,2) =
[ -b11, -b12]
[ -b21, -b22]
4-157
4 Functions Alphabetical List
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
See Also
horzcat | reshape | vertcat
Introduced in R2010b
4-158
catalan
catalan
Catalan constant
Syntax
catalan
Description
catalan represents the Catalan constant. 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
ans =
0.9159655942
4-159
4 Functions Alphabetical List
More About
Catalan Constant
( - 1) i 1 1 1 1
catalan = 2
=
2
-
2
+
2
-
72
+
i =0 ( 2i + 1) 1 3 5
See Also
dilog | eulergamma
Introduced in R2014a
4-160
ccode
ccode
C code representation of symbolic expression
Syntax
ccode(s)
ccode(s,'file',fileName)
Description
ccode(s) returns a fragment of C that evaluates the symbolic expression s.
Examples
The statements
syms x
f = taylor(log(1+x));
ccode(f)
return
ans =
185 char array
t0 = x-(x*x)*(1.0/2.0)+(x*x*x)*(1.0/3.0)-(x*x*x*x)*(1.0/4.0)+...
(x*x*x*x*x)*(1.0/5.0);
The statements
H = sym(hilb(3));
ccode(H)
4-161
4 Functions Alphabetical List
return
ans =
1184 char array
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;
The statements
syms x
z = exp(-exp(-x));
ccode(diff(z,3),'file','ccodetest')
t2 = exp(-x);
t3 = exp(-t2);
t0 = t3*exp(x*(-2.0))*(-3.0)+t3*exp(x*(-3.0))+t2*t3;
See Also
fortran | latex | matlabFunction | pretty
4-162
ceil
ceil
Round symbolic matrix toward positive infinity
Syntax
Y = ceil(x)
Description
Y = ceil(x) is the matrix of the smallest integers greater than or equal to x.
Examples
x = sym(-5/2);
[fix(x) floor(x) round(x) ceil(x) frac(x)]
ans =
[ -2, -3, -3, -2, -1/2]
See Also
round | floor | fix | frac
4-163
4 Functions Alphabetical List
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.
Examples
Convert Cell Array of Scalars
Convert a cell array of only scalar elements to a symbolic array.
4-164
cell2sym
C = {'x','y','z'; 1 2 3}
C =
23 cell array
'x' 'y' 'z'
[1] [2] [3]
S = cell2sym(C)
S =
[ x, y, z]
[ 1, 2, 3]
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
Create a cell array, the elements of which are a scalar, a row vector, a column vector, and
a matrix.
C =
22 cell array
'x' [13 double]
[21 sym] [23 double]
S = cell2sym(C)
4-165
4 Functions Alphabetical List
S =
[ x, 2, 3, 4]
[ y, 6, 7, 8]
[ 9, 10, 11, 12]
Createa cell array pi with two elements: the double-precision value of the constant pi
and the exact value pi.
C = {pi, sym(pi)}
C =
12 cell array
[3.1416] [11 sym]
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)
S =
[ pi, pi]
S = cell2sym(C,'r')
S =
[ pi, pi]
Convert the same cell array to a symbolic array using the flags 'd', 'e', and 'f'.
See the Input Arguments on page 4-167 section for the details about conversion
techniques.
S = cell2sym(C,'d')
S =
[ 3.1415926535897931159979634685442, pi]
S = cell2sym(C,'e')
S =
4-166
cell2sym
[ pi - (198*eps)/359, pi]
S = cell2sym(C,'f')
S =
[ 884279719003555/281474976710656, pi]
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.
4-167
4 Functions Alphabetical List
Output Arguments
S Resulting symbolic array
symbolic array
See Also
cell2mat | mat2cell | num2cell | sym2cell
Introduced in R2016a
4-168
char
char
Convert symbolic objects to character vectors
Syntax
char(A)
Description
char(A) converts a symbolic scalar or a symbolic array to a character vector.
Input Arguments
A
Examples
Convert symbolic expressions to character vectors, and then concatenate the character
vectors:
syms x
y = char(x^3 + x^2 + 2*x - 1);
name = [y, ' represents a polynomial expression']
name =
154 char array
2*x + x^2 + x^3 - 1 represents a polynomial expression
Note that char changes the order of the terms in the resulting character vector.
A = sym(hilb(3))
4-169
4 Functions Alphabetical List
char(A)
A =
[ 1, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
ans =
157 char array
matrix([[1,1/2,1/3],[1/2,1/3,1/4],[1/3,1/4,1/5]])
More About
Tips
See Also
sym | double | pretty
4-170
charpoly
charpoly
Characteristic polynomial of matrix
Syntax
charpoly(A)
charpoly(A,var)
Description
charpoly(A) returns a vector of the coefficients of the characteristic polynomial of A.
If A is a symbolic matrix, charpoly returns a symbolic vector. Otherwise, it returns a
vector of double-precision values.
Input Arguments
A
Matrix.
var
Default: If you do not specify var, charpoly returns a vector of coefficients of the
characteristic polynomial instead of returning the polynomial itself.
Examples
Compute the characteristic polynomial of the matrix A in terms of the variable x:
syms x
A = sym([1 1 0; 0 1 0; 0 0 1]);
4-171
4 Functions Alphabetical List
charpoly(A, x)
ans =
x^3 - 3*x^2 + 3*x - 1
To find the coefficients of the characteristic polynomial of A, call charpoly with one
argument:
A = sym([1 1 0; 0 1 0; 0 0 1]);
charpoly(A)
ans =
[ 1, -3, 3, -1]
Find the coefficients of the characteristic polynomial of the symbolic matrix A. For this
matrix, charpoly returns the symbolic vector of coefficients:
A = sym([1 2; 3 4]);
P = charpoly(A)
P =
[ 1, -5, -2]
Now find the coefficients of the characteristic polynomial of the matrix B, all elements of
which are double-precision values. Note that in this case charpoly returns coefficients
as double-precision values:
B = ([1 2; 3 4]);
P = charpoly(B)
P =
1 -5 -2
More About
Characteristic Polynomial of Matrix
The characteristic polynomial of an n-by-n matrix A is the polynomial pA(x), such that
pA ( x) = det ( xI n - A )
4-172
charpoly
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
2132, Birkhauser, 1997.
See Also
det | eig | jordan | minpoly | poly2sym | sym2poly
Introduced in R2012b
4-173
4 Functions Alphabetical List
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 at
the point x.
Examples
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.
4-174
chebyshevT
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.
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
4-175
4 Functions Alphabetical List
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')
4-176
chebyshevT
Input Arguments
n Degree of polynomial
nonnegative integer | symbolic variable | symbolic expression | symbolic function |
vector | matrix
4-177
4 Functions Alphabetical List
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) = 2 xT ( n - 1, x ) - T ( n - 2, x )
Chebyshev polynomials of the first kind are orthogonal on the interval -1x1 with
respect to the weight function
1
w ( x) =
1 - x2
Chebyshev polynomials of the first kind are a special case of the Jacobi polynomials
2 2n ( n !)
2
1 1
T ( n, x) = P n, - , - , x
( 2 n) ! 2 2
n
T ( n, x) = G ( n, 0, x )
2
Tips
chebyshevT returns floating-point results for numeric arguments that are not
symbolic objects.
4-178
chebyshevT
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
chebyshevU | gegenbauerC | hermiteH | jacobiP | laguerreL | legendreP
Introduced in R2014b
4-179
4 Functions Alphabetical List
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
at the point x.
Examples
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.
4-180
chebyshevU
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.
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
4-181
4 Functions Alphabetical List
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')
4-182
chebyshevU
Input Arguments
n Degree of polynomial
nonnegative integer | symbolic variable | symbolic expression | symbolic function |
vector | matrix
4-183
4 Functions Alphabetical List
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 ) a cos ( x ) )
U ( n, x) =
sin ( a cos ( x) )
U ( 0, x) = 1, U ( 1, x ) = 2 x, U ( n, x) = 2 xU ( n - 1, x ) - U ( n - 2, x )
Chebyshev polynomials of the second kind are orthogonal on the interval -1x1 with
respect to the weight function
w ( x) = 1 - x2
Chebyshev polynomials of the second kind are a special case of the Jacobi polynomials
2 2n n ! ( n + 1 ) ! 1 1
U ( n, x) = P n, , , x
( 2n + 1 ) ! 2 2
U ( n, x) = G ( n,1, x )
4-184
chebyshevU
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.
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 | gegenbauerC | hermiteH | jacobiP | laguerreL | legendreP
Introduced in R2014b
4-185
4 Functions Alphabetical List
children
Subexpressions or terms of symbolic expression
Syntax
children(expr)
children(A)
Description
children(A) returns a cell array containing the child subexpressions of each expression
in A.
Input Arguments
expr
Examples
Find the child subexpressions of this expression. Child subexpressions of a sum are its
terms.
syms x y
children(x^2 + x*y + y^2)
4-186
children
ans =
[ x*y, x^2, y^2]
Find the child subexpressions of this expression. This expression is also a sum, only some
terms of that sum are negative.
ans =
[ -x*y, x^2, -y^2]
children(x)
ans =
x
Find the child subexpressions of this equation. The child subexpressions of an equation
are the left and right sides of that equation.
syms x y
children(x^2 + x*y == y^2 + 1)
ans =
[ x^2 + y*x, y^2 + 1]
ans =
[ sin(x), cos(x)]
Call the children function for this matrix. The result is the cell array containing the
child subexpressions of each element of the matrix.
syms x y
s = children([x + y, sin(x)*cos(y); x^3 - y^3, exp(x*y^2)])
s =
22 cell array
[12 sym] [12 sym]
[12 sym] [11 sym]
4-187
4 Functions Alphabetical List
ans =
[ x, y]
ans =
[ x^3, -y^3]
ans =
[ cos(y), sin(x)]
ans =
x*y^2
See Also
coeffs | numden | subs
Introduced in R2012a
4-188
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. Otherwise, this syntax throws an error.
[T,p] = chol(A) computes the Cholesky factorization 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).