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).
4-189
4 Functions Alphabetical List
Input Arguments
A
Symbolic matrix.
'lower'
Flag that prompts chol to return a lower triangular matrix instead of an upper
triangular matrix.
'vector'
Flag that prompts chol to return the permutation information in the form of a vector. To
use this flag, you must specify three output arguments.
'nocheck'
Flag that prompts chol to avoid checking whether matrix A is Hermitian positive
definite. Use this flag if A contains symbolic parameters, and you want to avoid
additional assumptions on these parameters.
'real'
Flag that prompts chol to use real arithmetic. Use this flag if A contains symbolic
parameters, and you want to avoid complex conjugates.
4-190
chol
Output Arguments
T
Upper triangular matrix, such that T'*T = A, or lower triangular matrix, such that
T*T' = A.
If chol does not identify A as a Hermitian positive definite matrix, then p is a positive
integer. R is an upper triangular matrix of order q = p - 1, such that R'*R =
A(1:q,1:q).
Permutation matrix.
Permutation vector.
Examples
Compute the Cholesky factorization of the 3-by-3 Hilbert matrix. Because these numbers
are not symbolic objects, you get floating-point results.
chol(hilb(3))
ans =
1.0000 0.5000 0.3333
0 0.2887 0.2887
0 0 0.0745
Now convert this matrix to a symbolic object, and compute the Cholesky factorization:
chol(sym(hilb(3)))
ans =
[ 1, 1/2, 1/3]
[ 0, 3^(1/2)/6, 3^(1/2)/6]
4-191
4 Functions Alphabetical List
[ 0, 0, 5^(1/2)/30]
Compute the Cholesky factorization of the 3-by-3 Pascal matrix returning a lower
triangular matrix as a result:
chol(sym(pascal(3)), 'lower')
ans =
[ 1, 0, 0]
[ 1, 1, 0]
[ 1, 2, 1]
Try to compute the Cholesky factorization of this matrix. Because this matrix is not
Hermitian positive definite, chol used without output arguments or with one output
argument throws an error:
A = sym([1 1 1; 1 2 3; 1 3 5]);
T = chol(A)
To suppress the error, use two output arguments, T and p. If the matrix is not recognized
as Hermitian positive definite, then this syntax assigns an empty symbolic object to T
and the value 1 to p:
[T,p] = chol(A)
T =
[ empty sym ]
p =
1
T =
[ 1, 1, 1]
[ 0, 1, 2]
[ 0, 0, 1]
p =
4-192
chol
Compute the Cholesky factorization of the 3-by-3 inverse Hilbert matrix returning the
permutation matrix:
A = sym(invhilb(3));
[T, p, S] = chol(A)
T =
[ 3, -12, 10]
[ 0, 4*3^(1/2), -5*3^(1/2)]
[ 0, 0, 5^(1/2)]
p =
0
S =
1 0 0
0 1 0
0 0 1
Compute the Cholesky factorization of the 3-by-3 inverse Hilbert matrix returning the
permutation information as a vector:
A = sym(invhilb(3));
[T, p, S] = chol(A, 'vector')
T =
[ 3, -12, 10]
[ 0, 4*3^(1/2), -5*3^(1/2)]
[ 0, 0, 5^(1/2)]
p =
0
S =
1 2 3
syms a
A = [a 0; 0 a];
isAlways(A == A','Unknown','false')
ans =
4-193
4 Functions Alphabetical List
22 logical array
0 1
1 0
ans =
[ a^(1/2), 0]
[ 0, a^(1/2)]
'nocheck' lets you skip checking whether A is a Hermitian positive definite matrix.
Thus, this flag lets you compute the Cholesky factorization of a symbolic matrix without
setting additional assumptions on its components:
A = [a 0; 0 a];
chol(A,'nocheck')
ans =
[ a^(1/2), 0]
[ 0, a^(1/2)]
If you use 'nocheck' for computing the Cholesky factorization of a matrix that is not
Hermitian positive definite, chol can return a matrix T for which the identity T'*T = A
does not hold. To make isAlways return logical 0 (false) for undecidable conditions, set
Unknown to false.
T = chol(sym([1 1; 2 1]), 'nocheck')
T =
[ 1, 2]
[ 0, 3^(1/2)*1i]
isAlways(A == T'*T,'Unknown','false')
ans =
22 logical array
0 0
0 0
4-194
chol
T =
[ a^(1/2), conj(b)/conj(a^(1/2))]
[ 0, (a*abs(a) - abs(b)^2)^(1/2)/abs(a)^(1/2)]
T =
[ a^(1/2), b/a^(1/2)]
[ 0, ((a^2 - b^2)/a)^(1/2)]
When you use this flag, chol computes a symmetric factorization A = T.'*T instead
of a Hermitian factorization A = T'*T. To make isAlways return logical 0 (false) for
undecidable conditions, set Unknown to false.
isAlways(A == T.'*T)
ans =
22 logical array
1 1
1 1
isAlways(A == T'*T,'Unknown','false')
ans =
22 logical array
0 0
0 0
More About
Hermitian Positive Definite Matrix
A square complex matrix A is Hermitian positive definite if v'*A*v is real and positive
for all nonzero complex vectors v, where v' is the conjugate transpose (Hermitian
transpose) of v.
4-195
4 Functions Alphabetical List
Tips
Calling chol for numeric arguments that are not symbolic objects invokes the
MATLAB chol function.
If you use 'nocheck', then the identities T'*T = A (for an upper triangular matrix
T) and T*T = A (for a lower triangular matrix T) are not guaranteed to hold.
If you use 'real', then the identities T'*T = A (for an upper triangular matrix T)
and T*T' = A (for a lower triangular matrix T) are only guaranteed to hold for a real
symmetric positive definite A.
To use 'vector', you must specify three output arguments. Other flags do not
require a particular number of output arguments.
If you use 'matrix' instead of 'vector', then chol returns permutation matrices,
as it does by default.
If you use 'upper' instead of 'lower', then chol returns an upper triangular
matrix, as it does by default.
If A is not a Hermitian positive definite matrix, then the syntaxes containing the
argument p typically return p = 1 and an empty symbolic object T.
To check whether a matrix is Hermitian, use the operator ' (or its functional form
ctranspose). Matrix A is Hermitian if and only if A'= A, where A' is the conjugate
transpose of A.
See Also
chol | ctranspose | eig | isAlways | lu | qr | svd | transpose | vpa
Introduced in R2013a
4-196
clear all
clear all
Remove items from MATLAB workspace and reset MuPAD engine
Syntax
clear all
Description
clear all clears all objects in the MATLAB workspace and closes the MuPAD engine
associated with the MATLAB workspace resetting all its assumptions.
See Also
reset
Introduced in R2008b
4-197
4 Functions Alphabetical List
close
Close MuPAD notebook
Syntax
close(nb)
close(nb,'force')
Description
close(nb) closes the MuPAD notebook with the handle nb. If you modified the
notebook, close(nb) brings up a dialog box asking if you want to save the changes.
This syntax can be helpful when you evaluate MuPAD notebooks by using
evaluateMuPADNotebook. When you evaluate a notebook, MuPAD inserts results in
the output regions or at least inserts the new input region at the bottom of the notebook,
thus modifying the notebook. If you want to close the notebook quickly without saving
such changes, use close(nb,'force').
Examples
Close One Notebook
Suppose that your current folder contains a MuPAD notebook named myFile1.mn. Open
this notebook keeping its handle in the variable nb1:
nb1 = mupad('myFile1.mn');
Suppose that you finished using this notebook and now want to close it. Enter this
command in the MATLAB Command Window. If you have unsaved changes in that
notebook, then this command will bring up a dialog box asking if you want to save the
changes.
4-198
close
close(nb1)
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
Close myFile1.mn and myFile2.mn. If you have unsaved changes in any of these two
notebooks, then this command will bring up a dialog box asking if you want to save the
changes.
close([nb1, nb2])
Close all notebooks. If you have unsaved changes in any notebook, then this command
will bring up a dialog box asking if you want to save the changes.
close(allNBs)
Identify and close all currently open MuPAD notebooks without saving changes.
4-199
4 Functions Alphabetical List
Close all notebooks using the force flag to suppress the dialog box that offers you to
save changes:
close(allNBs,'force')
Input Arguments
nb Pointer to MuPAD notebook
handle to notebook | vector of handles to notebooks
You can get the list of all open notebooks using the allMuPADNotebooks function.
close accepts a vector of handles returned by allMuPADNotebooks.
See Also
allMuPADNotebooks | evaluateMuPADNotebook | getVar | mupad |
mupadNotebookTitle | openmn | setVar
Introduced in R2013b
4-200
coeffs
coeffs
Coefficients of polynomial
Syntax
C = coeffs(p)
C = coeffs(p,var)
C = coeffs(p,vars)
[C,T] = coeffs( ___ )
___ = coeffs( ___ ,'All')
Description
C = coeffs(p) returns coefficients of the polynomial p with respect to all variables
determined in p by symvar.
[C,T] = coeffs( ___ ) returns the coefficient C and the corresponding terms T of the
polynomial p.
___ = coeffs( ___ ,'All') returns all coefficients, including coefficients that are 0.
For example, coeffs(2*x^2,'All') returns [ 2, 0, 0] instead of 2.
Examples
4-201
4 Functions Alphabetical List
syms x
c = coeffs(16*x^2 + 19*x + 11)
c =
[ 11, 19, 16]
syms x y
cx = coeffs(x^3 + 2*x^2*y + 3*x*y^2 + 4*y^3, x)
cy = coeffs(x^3 + 2*x^2*y + 3*x*y^2 + 4*y^3, y)
cx =
[ 4*y^3, 3*y^2, 2*y, 1]
cy =
[ x^3, 2*x^2, 3*x, 4]
syms x y
cxy = coeffs(x^3 + 2*x^2*y + 3*x*y^2 + 4*y^3, [x,y])
cyx = coeffs(x^3 + 2*x^2*y + 3*x*y^2 + 4*y^3, [y,x])
cxy =
[ 4, 3, 2, 1]
cyx =
[ 1, 2, 3, 4]
syms x
[c,t] = coeffs(16*x^2 + 19*x + 11)
c =
4-202
coeffs
t =
[ x^2, x, 1]
syms x y
[cx,tx] = coeffs(x^3 + 2*x^2*y + 3*x*y^2 + 4*y^3, x)
[cy,ty] = coeffs(x^3 + 2*x^2*y + 3*x*y^2 + 4*y^3, y)
cx =
[ 1, 2*y, 3*y^2, 4*y^3]
tx =
[ x^3, x^2, x, 1]
cy =
[ 4, 3*x, 2*x^2, x^3]
ty =
[ y^3, y^2, y, 1]
Find the coefficients of this polynomial with respect to both variables x and y.
syms x y
[cxy, txy] = coeffs(x^3 + 2*x^2*y + 3*x*y^2 + 4*y^3, [x,y])
[cyx, tyx] = coeffs(x^3 + 2*x^2*y + 3*x*y^2 + 4*y^3, [y,x])
cxy =
[ 1, 2, 3, 4]
txy =
[ x^3, x^2*y, x*y^2, y^3]
cyx =
[ 4, 3, 2, 1]
tyx =
[ y^3, x*y^2, x^2*y, x^3]
4-203
4 Functions Alphabetical List
c =
[ 3, 0, 0]
If you find coefficients with respect to multiple variables and specify 'All', then coeffs
returns coefficients for all combinations of the variables.
cxy =
[ 0, 0, b]
[ a, 0, 0]
txy =
[ x^2*y, x*y, y]
[ x^2, x, 1]
Input Arguments
p Polynomial
symbolic expression | symbolic function
4-204
coeffs
Output Arguments
C Coefficients of polynomial
symbolic number | symbolic variable | symbolic expression | symbolic vector | symbolic
matrix | symbolic multidimensional array
T Terms of polynomial
symbolic number | symbolic variable | symbolic expression | symbolic vector | symbolic
matrix | symbolic multidimensional array
See Also
poly2sym
4-205
4 Functions Alphabetical List
collect
Collect coefficients
Syntax
collect(P)
collect(P,expr)
Description
collect(P) collects coefficients in P of the powers of the default variable of P. The
default variable is found by symvar.
Examples
coeffs =
x^2 + (exp(x) + 2)*x + 2*exp(x)
Because you did not specify the variable, collect uses the default variable defined by
symvar. For this expression, the default variable is x.
ans =
x
4-206
collect
coeffs_x =
(y - 1)*x^2 + (y - 2)*x
coeffs_y =
(x^2 + x)*y - x^2 - 2*x
coeffs_xy =
(a*b + 1)*x^2 + (a^2 + a)*x*y
coeffs_i =
(2*x - 3*y)*1i
coeffs_pi =
x*pi^2 + (x + 3*y - x*y)*pi + x*1i
4-207
4 Functions Alphabetical List
Expand sin(x + 3*y) and collect coefficients of cos(y), and then of both sin(x) and
sin(y).
syms x y
f = expand(sin(x + 3*y));
coeffs_cosy = collect(f, cos(y))
coeffs_cosy =
(4*sin(x))*cos(y)^3 + (4*cos(x)*sin(y))*cos(y)^2 + (-3*sin(x))*cos(y) - cos(x)*sin(y)
coeffs_sinxsiny =
(4*cos(y)^3 - 3*cos(y))*sin(x) + (4*cos(x)*cos(y)^2 - cos(x))*sin(y)
syms y(x)
f = y^2*x + y*x^2 + y*sin(x) + x*y;
coeffs_y = collect(f, y)
coeffs_y(x) =
x*y(x)^2 + (x + sin(x) + x^2)*y(x)
syms x y
collect([(x + 1)*(y + 1), x^2 + x*(x -y); 2*x*y - x, x*y + x/y], x)
ans =
[ (y + 1)*x + y + 1, 2*x^2 - y*x]
[ (2*y - 1)*x, (y + 1/y)*x]
Collect coefficients of calls to the sin function in F, where F contains multiple calls to
different functions.
4-208
collect
syms a b c d e f x
F = a*sin(2*x) + b*sin(2*x) + c*cos(x) + d*cos(x) + e*sin(3*x) +f*sin(3*x);
collect(F, 'sin')
ans =
(a + b)*sin(2*x) + (e + f)*sin(3*x) + c*cos(x) + d*cos(x)
ans =
(c + d)*cos(x) + (a + b)*sin(2*x) + (e + f)*sin(3*x)
Input Arguments
P Input expression
symbolic expression | symbolic function | symbolic vector | symbolic matrix
Expression in terms of which you collect the coefficients, specified as a symbolic number,
variable, expression, function, or vector; a character vector; a cell array of character
vectors.
Example: i, pi, x, sin(x), y(x), [sin(x) cos(y)], {'sin' 'cos'}.
See Also
combine | expand | factor | horner | numden | rewrite | simplify |
simplifyFraction | symvar
4-209
4 Functions Alphabetical List
colon, :
Create symbolic vectors, array subscripting, and for-loop iterators
Syntax
m:n
m:d:n
x:x+r
x:d:x+r
Description
m:n returns a symbolic vector of values [m,m+1,...,n], where m and n are symbolic
constants. If n is not an increment of m, then the last value of the vector stops before n.
This behavior holds for all syntaxes.
Examples
Create Numeric and Symbolic Arrays
Use the colon operator to create numeric and symbolic arrays. Because these inputs are
not symbolic objects, you receive floating-point results.
1/2:7/2
ans =
0.5000 1.5000 2.5000 3.5000
4-210
colon, :
ans =
[ 1/2, 3/2, 5/2, 7/2]
ans =
[ 1/2, 7/6, 11/6, 5/2, 19/6]
ans =
[ x, x + 1, x + 2]
ans =
[ x, x + 3/7, x + 6/7, x + 9/7, x + 12/7]
ans =
[ x, (4*x)/3, (5*x)/3, 2*x]
4-211
4 Functions Alphabetical List
p = p*1/i;
end
p
p =
1/(x*(x + 1)*(x + 2)*(x + 3))
ans =
1/(x^4 + 6*x^3 + 11*x^2 + 6*x)
p =
1/24
ans =
0.041666666666666666666666666666667
You can also perform the described operations in a single line of code.
vpa(subs( expand(prod(1./(x:x+3))) ,x,1))
ans =
0.041666666666666666666666666666667
Input Arguments
m Input
symbolic constant
n Input
symbolic constant
4-212
colon, :
x Input
symbolic variable
Upper bound on vector values, specified as a symbolic rational. For example, x:x+2
returns [ x, x + 1, x + 2].
See Also
reshape
4-213
4 Functions Alphabetical List
colspace
Column space of matrix
Syntax
B = colspace(A)
Description
B = colspace(A) returns a matrix whose columns form a basis for the column space of
A. The matrix A can be symbolic or numeric.
Examples
Find the basis for the column space of this matrix:
A = sym([2,0;3,4;0,5])
B = colspace(A)
A =
[ 2, 0]
[ 3, 4]
[ 0, 5]
B =
[ 1, 0]
[ 0, 1]
[ -15/8, 5/4]
See Also
null | size
4-214
combine
combine
Combine terms of identical algebraic structure
Syntax
Y = combine(S)
Y = combine(S,T)
Y = combine( ___ ,Name,Value)
Description
Y = combine(S) rewrites products of powers in the expression S as a single power.
Examples
Powers of the Same Base
Combine powers of the same base.
syms x y z
combine(x^y*x^z)
ans =
x^(y + z)
4-215
4 Functions Alphabetical List
combine(x^(3)*x^y*x^exp(sym(1)))
ans =
x^(y + exp(1) + 3)
Here, sym converts 1 into a symbolic value, preventing MATLAB from evaluating the
expression e .
1
combine(sqrt(sym(2))*sqrt(3))
ans =
6^(1/2)
combine does not usually combine the powers because the internal simplifier applies the
same rules in the opposite direction to expand the result.
syms x y
combine(y^5*x^5)
ans =
x^5*y^5
S = log(sym(2)) + log(sym(3));
combine(S,'log')
ans =
log(6)
Try combining log(a) + log(b). Because a and b are assumed to be complex numbers
by default, the rule does not hold and combine does not combine the terms.
syms a b
4-216
combine
S = log(a) + log(b);
combine(S,'log')
ans =
log(a) + log(b)
Apply the rule by setting assumptions such that a and b satisfy the conditions for the
rule.
assume(a > 0)
assume(b > 0)
S = log(a) + log(b);
combine(S,'log')
ans =
log(a*b)
syms a clear
syms b clear
syms a b
S = log(a) + log(b);
combine(S,'log','IgnoreAnalyticConstraints',true)
ans =
log(a*b)
syms a b
combine(sin(a)*cos(b) + sin(b)^2,'sincos')
ans =
sin(a + b)/2 - cos(2*b)/2 + sin(a - b)/2 + 1/2
Rewrite sums of sine and cosine functions by setting the target argument to sincos.
4-217
4 Functions Alphabetical List
combine(cos(a) + sin(a),'sincos')
ans =
2^(1/2)*cos(a - pi/4)
combine does not rewrite powers of sine or cosine functions with negative integer
exponents.
syms a b
combine(sin(b)^(-2)*cos(b)^(-2),'sincos')
ans =
1/(cos(b)^2*sin(b)^2)
Exponential Terms
Combine terms with exponents by specifying the target argument as exp.
combine(exp(sym(3))*exp(sym(2)),'exp')
ans =
exp(5)
syms a
combine(exp(a)^3, 'exp')
ans =
exp(3*a)
ans =
int(f(x) + g(x), x)
ans =
int(a*f(x), x)
4-218
combine
syms a b h(z)
combine(int(f(x),x,a,b)+int(h(z),z,a,b),'int')
ans =
int(f(x) + h(x), x, a, b)
syms a b
assume(-1 < a < 1)
assume(-1 < b < 1)
combine(atan(a) + atan(b),'atan')
ans =
-atan((a + b)/(a*b - 1))
Combine two calls to the inverse tangent function. combine simplifies the expression to
a symbolic value if possible.
assume(a > 0)
combine(atan(a) + atan(1/a),'atan')
ans =
pi/2
syms a clear
syms b clear
syms x
combine(gamma(x)*gamma(1-x),'gamma')
ans =
-pi/sin(pi*(x - 1))
4-219
4 Functions Alphabetical List
S = [sqrt(sym(2))*sqrt(5), sqrt(2)*sqrt(sym(11))];
combine(S)
ans =
[ 10^(1/2), 22^(1/2)]
Input Arguments
S Input expression
symbolic expression | symbolic vector | symbolic matrix | symbolic function
T Target function
'atan' | 'exp' | 'gamma' | 'int' | 'log' | 'sincos' | 'sinhcosh'
4-220
combine
Output Arguments
Y Expression with combined functions
symbolic variable | symbolic number | symbolic expression | symbolic vector | symbolic
matrix
More About
Algorithms
combine applies the following rewriting rules to the input expression S, depending on
the value of the target argument T.
e a eb = e a + b
4-221
4 Functions Alphabetical List
( ea ) b = eab .
When T = 'log',
If b < 1000,
b log( a) = log ( ab ) .
When b >= 1000, combine does not apply this second rule.
The rules applied to rewrite logarithms do not hold for arbitrary complex values of a
and b. Specify appropriate properties for a or b to enable these rewriting rules.
When T = 'int',
a f ( x ) dx = af ( x ) dx
cos ( x - y ) cos ( x + y )
sin ( x ) sin ( y ) = - .
2 2
B2 -B
A cos ( x) + B sin ( x) = A 1 + cos x + tan -1 .
2 A
A
x+y
atan ( x ) + atan ( y ) = atan .
1 - xy
When T = 'sinhcosh',
cosh ( x + y ) cosh( x - y )
sinh ( x ) sinh ( y ) = - .
2 2
combine applies the previous rules recursively to powers of sinh and cosh with
positive integral exponents.
When T = 'gamma',
aG ( a ) = G ( a + 1) .
and,
G ( a + 1)
= a.
G (a )
p
G (-a ) G ( a ) = - .
sin ( p a )
See Also
collect | expand | factor | horner | numden | rewrite | simplify |
simplifyFraction
4-223
4 Functions Alphabetical List
Introduced in R2014a
4-224
compose
compose
Functional composition
Syntax
compose(f,g)
compose(f,g,z)
compose(f,g,x,z)
compose(f,g,x,y,z)
Description
compose(f,g) returns f(g(y)) where f = f(x) and g = g(y). Here x is the
symbolic variable of f as defined by symvar and y is the symbolic variable of g as defined
by symvar.
compose(f,g,z) returns f(g(z)) where f = f(x), g = g(y), and x and y are the
symbolic variables of f and g as defined by symvar.
Examples
Suppose
syms x y z t u
f = 1/(1 + x^2);
g = sin(y);
h = x^t;
4-225
4 Functions Alphabetical List
p = exp(-y/u);
Then
a = compose(f,g)
b = compose(f,g,t)
c = compose(h,g,x,z)
d = compose(h,g,t,z)
e = compose(h,p,x,y,z)
f = compose(h,p,t,u,z)
returns:
a =
1/(sin(y)^2 + 1)
b =
1/(sin(t)^2 + 1)
c =
sin(z)^t
d =
x^sin(z)
e =
exp(-z/u)^t
f =
x^exp(-y/z)
See Also
finverse | subs | syms
4-226
cond
cond
Condition number of matrix
Syntax
cond(A)
cond(A,P)
Description
cond(A) returns the 2-norm condition number of matrix A.
Input Arguments
A
Symbolic matrix.
Default: 2
Examples
Compute the 2-norm condition number of the inverse of the 3-by-3 magic square A:
A = inv(sym(magic(3)));
4-227
4 Functions Alphabetical List
condN2 = cond(A)
condN2 =
(5*3^(1/2))/2
ans =
4.3301270189221932338
Compute the 1-norm condition number, the Frobenius condition number, and the infinity
condition number of the inverse of the 3-by-3 magic square A:
A = inv(sym(magic(3)));
condN1 = cond(A, 1)
condNf = cond(A, 'fro')
condNi = cond(A, inf)
condN1 =
16/3
condNf =
(285^(1/2)*391^(1/2))/60
condNi =
16/3
ans =
5.3333333333333333333
ans =
5.5636468855119361059
ans =
5.3333333333333333333
Compute the condition numbers of the 3-by-3 Hilbert matrix H approximating the results
with 30-digit accuracy:
4-228
cond
H = sym(hilb(3));
condN2 = vpa(cond(H), 30)
condN1 = vpa(cond(H, 1), 30)
condNf = vpa(cond(H, 'fro'), 30)
condNi = vpa(cond(H, inf), 30)
condN2 =
524.056777586060817870782845928 +...
1.42681147881398269481283800423e-38i
condN1 =
748.0
condNf =
526.158821079719236517033364845
condNi =
748.0
More About
Condition Number of a Matrix
Condition number of a matrix is the ratio of the largest singular value of that matrix to
the smallest singular value. The P-norm condition number of the matrix A is defined as
norm(A,P)*norm(inv(A),P), where norm is the norm of the matrix A.
Tips
Calling cond for a numeric matrix that is not a symbolic object invokes the MATLAB
cond function.
See Also
equationsToMatrix | inv | linsolve | norm | rank
Introduced in R2012b
4-229
4 Functions Alphabetical List
conj
Symbolic complex conjugate
Syntax
conj(X)
Description
conj(X) is the complex conjugate of X.
See Also
real | imag
4-230
convertMuPADNotebook
convertMuPADNotebook
Convert MuPAD notebook to MATLAB live script
Syntax
convertMuPADNotebook(MuPADfile,MATLABLiveScript)
convertMuPADNotebook(MuPADfile)
Description
convertMuPADNotebook(MuPADfile,MATLABLiveScript) converts a MuPAD
notebook file MuPADfile (.mn) to a MATLAB live script file MATLABLiveScript (.mlx).
Both MuPADfile and MATLABLiveScript must be full paths unless the files are in the
current folder. For information on live scripts, see Create Live Scripts.
Examples
Suppose that your current folder contains a MuPAD notebook named myNotebook.mn.
Convert this notebook to the MATLAB live script file named myScript.mlx.
convertMuPADNotebook('myNotebook.mn','myScript.mlx')
edit('myScript.mlx')
4-231
4 Functions Alphabetical List
Visually check the code for correctness and completeness. Then verify it by running it.
Suppose that your current folder contains a MuPAD notebook named myFile.mn.
Convert this notebook to the MATLAB live script file named myFile.mlx.
convertMuPADNotebook('myFile.mn')
edit('myFile.mlx')
Visually check the code for correctness and completeness. Then verify it by executing it.
Convert the MuPAD notebook, myNotebook.mn, to the MATLAB live script file,
myScript.mlx. Because myNotebook.mn contains commands that cannot be directly
translated to MATLAB code, convertMuPADNotebook flags these commands as
translation errors and warnings.
convertMuPADNotebook('myNotebook.mn','myScript.mlx')
4-232
convertMuPADNotebook
edit('myScript.mlx');
Eliminate translation errors. First, search for translation error. Next to translation
error, the converted code displays short comments explaining which MuPAD command
did not translate properly. There is also a link to documentation that provides
more details and suggestions for fixing the issue. After fixing the issue, remove the
corresponding error message and any comments related to it.
Find translation warnings by searching for translation warning. The converted code
displays a short comment and a link to documentation next to translation warning.
Some warnings might require you to adapt the code so it runs properly. In most cases,
you can ignore translation warnings. Whether you fixed the code or decided to ignore the
warning, remove the warning message and any comments related to it.
Verify that the resulting MATLAB code runs properly by executing it.
Input Arguments
MuPADfile Name of MuPAD notebook
character vector
Name of a MuPAD notebook, specified as a character vector. This character vector must
specify the full path to the file, unless the file is in the current folder.
Example: 'C:\MuPAD_Notebooks\myFile.mn'
4-233
4 Functions Alphabetical List
Name of a MATLAB live script file, specified as a character vector. This character vector
must specify the full path to the file, unless you intend to create a file in the current
folder.
Example: 'C:\MATLAB_Scripts\myFile.mlx'
More About
Convert MuPAD Notebooks to MATLAB Live Scripts on page 3-19
Troubleshoot MuPAD to MATLAB Translation Errors on page 3-25
Troubleshoot MuPAD to MATLAB Translation Warnings on page 3-34
See Also
generate::MATLAB
Introduced in R2016a
4-234
cos
cos
Symbolic cosine function
Syntax
cos(X)
Description
cos(X) returns the cosine function of X.
Examples
Compute the cosine function for these numbers. Because these numbers are not symbolic
objects, cos returns floating-point results.
A =
-0.4161 -1.0000 0.8660 -0.6235 0.0044
Compute the cosine function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, cos returns unresolved symbolic calls.
symA =
[ cos(2), -1, 3^(1/2)/2, -cos((2*pi)/7), cos(11)]
4-235
4 Functions Alphabetical List
vpa(symA)
ans =
[ -0.41614683654714238699756822950076,...
-1.0,...
0.86602540378443864676372317075294,...
-0.62348980185873353052500488400424,...
0.0044256979880507857483550247239416]
syms x
fplot(cos(x), [-4*pi, 4*pi])
grid on
4-236
cos
syms x
diff(cos(x), x)
diff(cos(x), x, x)
ans =
-sin(x)
4-237
4 Functions Alphabetical List
ans =
-cos(x)
ans =
sin(x)
taylor(cos(x), x)
ans =
x^4/24 - x^2/2 + 1
ans =
exp(-x*1i)/2 + exp(x*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 | atan | cot | csc | sec | sin | tan
4-238
cosh
cosh
Symbolic hyperbolic cosine function
Syntax
cosh(X)
Description
cosh(X) returns the hyperbolic cosine function of X.
Examples
Compute the hyperbolic cosine function for these numbers. Because these numbers are
not symbolic objects, cosh returns floating-point results.
A =
3.7622 -1.0000 0.8660 -0.6235 -0.0000
Compute the hyperbolic cosine function for the numbers converted to symbolic objects.
For many symbolic (exact) numbers, cosh returns unresolved symbolic calls.
symA =
[ cosh(2), -1, 3^(1/2)/2, -cosh((pi*2i)/7), 0]
4-239
4 Functions Alphabetical List
vpa(symA)
ans =
[ 3.7621956910836314595622134777737,...
-1.0,...
0.86602540378443864676372317075294,...
-0.62348980185873353052500488400424,...
0]
syms x
fplot(cosh(x), [-pi, pi])
grid on
4-240
cosh
Find the first and second derivatives of the hyperbolic cosine function:
syms x
diff(cosh(x), x)
diff(cosh(x), x, x)
ans =
sinh(x)
4-241
4 Functions Alphabetical List
ans =
cosh(x)
ans =
sinh(x)
taylor(cosh(x), x)
ans =
x^4/24 + x^2/2 + 1
ans =
exp(-x)/2 + exp(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 | atanh | coth | csch | sech | sinh |
tanh
4-242
coshint
coshint
Hyperbolic cosine integral function
Syntax
coshint(X)
Description
coshint(X) returns the hyperbolic cosine integral function of X.
Examples
Compute the hyperbolic cosine integral function for these numbers. Because these
numbers are not symbolic objects, coshint returns floating-point results.
A =
0.8379 + 3.1416i -Inf + 0.0000i -0.0528 + 0.0000i 0.8379...
+ 0.0000i 1.7127 + 0.0000i 5.4587 + 0.0000i
Compute the hyperbolic cosine integral function for the numbers converted to symbolic
objects. For many symbolic (exact) numbers, coshint returns unresolved symbolic calls.
symA =
[ coshint(1) + pi*1i, -Inf, coshint(1/2), coshint(1), coshint(pi/2), coshint(pi)]
4-243
4 Functions Alphabetical List
vpa(symA)
ans =
[ 0.83786694098020824089467857943576...
+ 3.1415926535897932384626433832795i,...
-Inf,...
-0.052776844956493615913136063326141,...
0.83786694098020824089467857943576,...
1.7126607364844281079951569897796,...
5.4587340442160681980014878977798]
syms x
fplot(coshint(x), [0, 2*pi])
grid on
4-244
coshint
Find the first and second derivatives of the hyperbolic cosine integral function:
syms x
diff(coshint(x), x)
diff(coshint(x), x, x)
ans =
cosh(x)/x
ans =
4-245
4 Functions Alphabetical List
sinh(x)/x - cosh(x)/x^2
ans =
x*coshint(x) - sinh(x)
Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
More About
Hyperbolic Cosine Integral Function
cosh ( t ) - 1
x
Chi ( x ) = g + log ( x) + dt
t
0
n 1
g = lim - ln ( n )
n k
k=1
References
[1] Cautschi, W. and W. F. Cahill. Exponential Integral and Related Functions.
Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical
Tables. (M. Abramowitz and I. A. Stegun, eds.). New York: Dover, 1972.
4-246
coshint
See Also
cos | cosint | eulergamma | int | sinhint | sinint | ssinint
Introduced in R2014a
4-247
4 Functions Alphabetical List
cosint
Cosine integral function
Syntax
cosint(X)
Description
cosint(X) returns the cosine integral function of X.
Examples
Compute the cosine integral function for these numbers. Because these numbers are not
symbolic objects, cosint returns floating-point results.
A =
0.3374 + 3.1416i -Inf + 0.0000i 0.4720 + 0.0000i...
0.0737 + 0.0000i 0.3374 + 0.0000i
Compute the cosine integral function for the numbers converted to symbolic objects. For
many symbolic (exact) numbers, cosint returns unresolved symbolic calls.
symA =
[ cosint(1) + pi*1i, -Inf, cosint(pi/2), cosint(pi), cosint(1)]
4-248
cosint
vpa(symA)
ans =
[ 0.33740392290096813466264620388915...
+ 3.1415926535897932384626433832795i,...
-Inf,...
0.47200065143956865077760610761413,...
0.07366791204642548599010096523015,...
0.33740392290096813466264620388915]
syms x
fplot(cosint(x), [0, 4*pi])
grid on
4-249
4 Functions Alphabetical List
Find the first and second derivatives of the cosine integral function:
syms x
diff(cosint(x), x)
diff(cosint(x), x, x)
ans =
cos(x)/x
ans =
4-250
cosint
- cos(x)/x^2 - sin(x)/x
ans =
x*cosint(x) - sin(x)
Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
More About
Cosine Integral Function
x
cos ( t ) - 1
Ci ( x ) = g + log( x) + dt
t
0
n 1
g = lim - ln ( n )
n k
k=1
References
[1] Gautschi, W. and W. F. Cahill. Exponential Integral and Related Functions.
Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical
Tables. (M. Abramowitz and I. A. Stegun, eds.). New York: Dover, 1972.
4-251
4 Functions Alphabetical List
See Also
cos | coshint | eulergamma | int | sinhint | sinint | ssinint
4-252
cot
cot
Symbolic cotangent function
Syntax
cot(X)
Description
cot(X) returns the cotangent function of X.
Examples
Compute the cotangent function for these numbers. Because these numbers are not
symbolic objects, cot returns floating-point results.
A =
0.4577 -0.0000 1.7321 -0.7975 -0.0044
Compute the cotangent function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, cot returns unresolved symbolic calls.
symA =
[ -cot(2), 0, 3^(1/2), -cot((2*pi)/7), cot(11)]
4-253
4 Functions Alphabetical List
vpa(symA)
ans =
[ 0.45765755436028576375027741043205,...
0,...
1.7320508075688772935274463415059,...
-0.79747338888240396141568825421443,...
-0.0044257413313241136855482762848043]
syms x
fplot(cot(x), [-pi, pi])
grid on
4-254
cot
syms x
diff(cot(x), x)
diff(cot(x), x, x)
ans =
- cot(x)^2 - 1
4-255
4 Functions Alphabetical List
ans =
2*cot(x)*(cot(x)^2 + 1)
ans =
log(sin(x))
ans =
pi/2 - x - (x - pi/2)^3/3 - (2*(x - pi/2)^5)/15
Rewrite the cotangent function in terms of the sine and cosine functions:
rewrite(cot(x), 'sincos')
ans =
cos(x)/sin(x)
ans =
(exp(x*2i)*1i + 1i)/(exp(x*2i) - 1)
Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
See Also
acos | acot | acsc | asec | asin | atan | cos | csc | sec | sin | tan
4-256
cot
4-257
4 Functions Alphabetical List
coth
Symbolic hyperbolic cotangent function
Syntax
coth(X)
Description
coth(X) returns the hyperbolic cotangent function of X
Examples
Compute the hyperbolic cotangent function for these numbers. Because these numbers
are not symbolic objects, coth returns floating-point results.
A =
-1.0373 + 0.0000i 0.0000 + 0.5774i 0.0000 - 1.7321i...
0.0000 + 0.7975i 0.0000 - 0.0000i
Compute the hyperbolic cotangent function for the numbers converted to symbolic
objects. For many symbolic (exact) numbers, coth returns unresolved symbolic calls.
symA =
[ -coth(2), (3^(1/2)*1i)/3, -3^(1/2)*1i, -coth((pi*2i)/7), 0]
4-258
coth
vpa(symA)
ans =
[ -1.0373147207275480958778097647678,...
0.57735026918962576450914878050196i,...
-1.7320508075688772935274463415059i,...
0.79747338888240396141568825421443i,...
0]
syms x
fplot(coth(x), [-10, 10])
grid on
4-259
4 Functions Alphabetical List
Find the first and second derivatives of the hyperbolic cotangent function:
syms x
diff(coth(x), x)
diff(coth(x), x, x)
ans =
1 - coth(x)^2
4-260
coth
ans =
2*coth(x)*(coth(x)^2 - 1)
ans =
log(sinh(x))
taylor(coth(x), x, pi*i/2)
ans =
x - (pi*1i)/2 - (x - (pi*1i)/2)^3/3 + (2*(x - (pi*1i)/2)^5)/15
ans =
(exp(2*x) + 1)/(exp(2*x) - 1)
Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
See Also
acosh | acoth | acsch | asech | asinh | atanh | cosh | csch | sech | sinh |
tanh
4-261
4 Functions Alphabetical List
csc
Symbolic cosecant function
Syntax
csc(X)
Description
csc(X) returns the cosecant function of X.
Examples
Compute the cosecant function for these numbers. Because these numbers are not
symbolic objects, csc returns floating-point results.
A =
-1.0998 -1.0000 2.0000 1.2790 -1.0000
Compute the cosecant function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, csc returns unresolved symbolic calls.
symA =
[ -1/sin(2), -1, 2, 1/sin((2*pi)/7), 1/sin(11)]
4-262
csc
vpa(symA)
ans =
[ -1.0997501702946164667566973970263,...
-1.0,...
2.0,...
1.2790480076899326057478506072714,...
-1.0000097935452091313874644503551]
syms x
fplot(csc(x), [-4*pi, 4*pi])
grid on
4-263
4 Functions Alphabetical List
syms x
diff(csc(x), x)
diff(csc(x), x, x)
ans =
-cos(x)/sin(x)^2
4-264
csc
ans =
1/sin(x) + (2*cos(x)^2)/sin(x)^3
ans =
log(tan(x/2))
taylor(csc(x), x, pi/2)
ans =
(x - pi/2)^2/2 + (5*(x - pi/2)^4)/24 + 1
ans =
1/((exp(-x*1i)*1i)/2 - (exp(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 | atan | cos | cot | csc | sin | tan
4-265
4 Functions Alphabetical List
csch
Symbolic hyperbolic cosecant function
Syntax
csch(X)
Description
csch(X) returns the hyperbolic cosecant function of X.
Examples
Compute the hyperbolic cosecant function for these numbers. Because these numbers are
not symbolic objects, csch returns floating-point results.
A =
-0.2757 + 0.0000i 0.0000 + 1.0000i Inf + 0.0000i...
0.0000 - 1.1547i 0.0000 - 1.2790i 0.0000 - 1.0000i
Compute the hyperbolic cosecant function for the numbers converted to symbolic objects.
For many symbolic (exact) numbers, csch returns unresolved symbolic calls.
symA =
[ -1/sinh(2), 1i, Inf, -(3^(1/2)*2i)/3, 1/sinh((pi*2i)/7), -1i]
4-266
csch
vpa(symA)
ans =
[ -0.27572056477178320775835148216303,...
1.0i,...
Inf,...
-1.1547005383792515290182975610039i,...
-1.2790480076899326057478506072714i,...
-1.0i]
syms x
fplot(csch(x), [-10, 10])
grid on
4-267
4 Functions Alphabetical List
Find the first and second derivatives of the hyperbolic cosecant function:
syms x
diff(csch(x), x)
diff(csch(x), x, x)
ans =
-cosh(x)/sinh(x)^2
4-268
csch
ans =
(2*cosh(x)^2)/sinh(x)^3 - 1/sinh(x)
ans =
log(tanh(x/2))
taylor(csch(x), x, pi*i/2)
ans =
((x - (pi*1i)/2)^2*1i)/2 - ((x - (pi*1i)/2)^4*5i)/24 - 1i
ans =
-1/(exp(-x)/2 - exp(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 | atanh | cosh | coth | sech | sinh |
tanh
4-269
4 Functions Alphabetical List
ctranspose, '
Symbolic matrix complex conjugate transpose
Syntax
A'
ctranspose(A)
Description
A' computes the complex conjugate transpose of A.
Examples
Conjugate Transpose of Real Matrix
Create a 2-by-3 matrix, the elements of which represent real numbers.
syms x y real
A = [x x x; y y y]
A =
[ x, x, x]
[ y, y, y]
ans =
[ x, y]
[ x, y]
[ x, y]
If all elements of a matrix represent real numbers, then its complex conjugate transform
equals to its nonconjugate transform.
4-270
ctranspose, '
isAlways(A' == A.')
ans =
32 logical array
1 1
1 1
1 1
A =
[ x + y*1i, x - y*1i]
[ y + x*1i, y - x*1i]
Find the conjugate transpose of this matrix. The complex conjugate transpose operator,
A', performs a transpose and negates the sign of the imaginary portion of the complex
elements in A.
A'
ans =
[ x - y*1i, y - x*1i]
[ x + y*1i, y + x*1i]
For a matrix of complex numbers with nonzero imaginary parts, the complex conjugate
transform is not equal to the nonconjugate transform.
isAlways(A' == A.','Unknown','false')
ans =
22 logical array
0 0
0 0
Input Arguments
A Input
number | symbolic number | symbolic variable | symbolic expression | symbolic vector |
symbolic matrix | symbolic multidimensional array
4-271
4 Functions Alphabetical List
More About
Complex Conjugate Transpose
The complex conjugate transpose of a matrix interchanges the row and column index
for each element, reflecting the elements across the main diagonal. The operation also
negates the imaginary part of any complex numbers.
For example, if B = A' and A(1,2) is 1+1i, then the element B(2,1) is 1-1i.
See Also
ldivide | minus | mldivide | mpower | mrdivide | mtimes | plus | power |
rdivide | times | transpose
4-272
cumprod
cumprod
Symbolic cumulative product
Syntax
B = cumprod(A)
B = cumprod(A,dim)
B = cumprod( ___ ,direction)
Description
B = cumprod(A) returns an array the same size as A containing the cumulative
product.
B = cumprod( ___ ,direction) specifies the direction using any of the previous
syntaxes. For instance, cumprod(A,2,'reverse') returns the cumulative product
within the rows of A by working from end to beginning of the second dimension.
Examples
Cumulative Product of Vector
Create a vector and find the cumulative product of its elements.
V = 1./factorial(sym([1:5]))
prod_V = cumprod(V)
4-273
4 Functions Alphabetical List
V =
[ 1, 1/2, 1/6, 1/24, 1/120]
prod_V =
[ 1, 1/2, 1/12, 1/288, 1/34560]
X =
[ x, x, x, x]
[ x, x, x, x]
[ x, x, x, x]
[ x, x, x, x]
Compute the cumulative product of the elements of X. By default, cumprod returns the
cumulative product of each column.
productX = cumprod(X)
productX =
[ x, x, x, x]
[ x^2, x^2, x^2, x^2]
[ x^3, x^3, x^3, x^3]
[ x^4, x^4, x^4, x^4]
X =
[ x, x, x, x]
[ x, x, x, x]
[ x, x, x, x]
[ x, x, x, x]
4-274
cumprod
productX = cumprod(X,2)
productX =
[ x, x^2, x^3, x^4]
[ x, x^2, x^3, x^4]
[ x, x^2, x^3, x^4]
[ x, x^2, x^3, x^4]
syms x
X = x*ones(4,4)
X =
[ x, x, x, x]
[ x, x, x, x]
[ x, x, x, x]
[ x, x, x, x]
Calculate the cumulative product along the columns in both directions. Specify the
'reverse' option to work from right to left in each row.
columnsDirect = cumprod(X)
columnsReverse = cumprod(X,'reverse')
columnsDirect =
[ x, x, x, x]
[ x^2, x^2, x^2, x^2]
[ x^3, x^3, x^3, x^3]
[ x^4, x^4, x^4, x^4]
columnsReverse =
[ x^4, x^4, x^4, x^4]
[ x^3, x^3, x^3, x^3]
[ x^2, x^2, x^2, x^2]
[ x, x, x, x]
Calculate the cumulative product along the rows in both directions. Specify the
'reverse' option to work from right to left in each row.
rowsDirect = cumprod(X,2)
rowsReverse = cumprod(X,2,'reverse')
4-275
4 Functions Alphabetical List
rowsDirect =
[ x, x^2, x^3, x^4]
[ x, x^2, x^3, x^4]
[ x, x^2, x^3, x^4]
[ x, x^2, x^3, x^4]
rowsReverse =
[ x^4, x^3, x^2, x]
[ x^4, x^3, x^2, x]
[ x^4, x^3, x^2, x]
[ x^4, x^3, x^2, x]
Input Arguments
A Input array
symbolic vector | symbolic matrix
4-276
cumprod
Output Arguments
B Cumulative product array
vector | matrix
Cumulative product array, returned as a vector or matrix of the same size as the input A.
See Also
cumsum | fold | int | symprod | symsum
Introduced in R2013b
4-277
4 Functions Alphabetical List
cumsum
Symbolic cumulative sum
Syntax
B = cumsum(A)
B = cumsum(A,dim)
B = cumsum( ___ ,direction)
Description
B = cumsum(A) returns an array the same size as A containing the cumulative sum.
B = cumsum(A,dim) returns the cumulative sum along dimension dim. For example, if
A is a matrix, then cumsum(A,2) returns the cumulative sum of each row.
B = cumsum( ___ ,direction) specifies the direction using any of the previous
syntaxes. For instance, cumsum(A,2,'reverse') returns the cumulative sum within
the rows of A by working from end to beginning of the second dimension.
Examples
V =
4-278
cumsum
sum_V =
[ 1, 3/2, 5/3, 41/24, 103/60]
A = sym(ones(4,4))
A =
[ 1, 1, 1, 1]
[ 1, 1, 1, 1]
[ 1, 1, 1, 1]
[ 1, 1, 1, 1]
sumA = cumsum(A)
sumA =
[ 1, 1, 1, 1]
[ 2, 2, 2, 2]
[ 3, 3, 3, 3]
[ 4, 4, 4, 4]
A = sym(ones(4,4))
A =
[ 1, 1, 1, 1]
[ 1, 1, 1, 1]
[ 1, 1, 1, 1]
[ 1, 1, 1, 1]
sumA = cumsum(A,2)
4-279
4 Functions Alphabetical List
sumA =
[ 1, 2, 3, 4]
[ 1, 2, 3, 4]
[ 1, 2, 3, 4]
[ 1, 2, 3, 4]
A = sym(ones(4,4))
A =
[ 1, 1, 1, 1]
[ 1, 1, 1, 1]
[ 1, 1, 1, 1]
[ 1, 1, 1, 1]
Calculate the cumulative sum along the columns in both directions. Specify the
'reverse' option to work from right to left in each row.
columnsDirect = cumsum(A)
columnsReverse = cumsum(A,'reverse')
columnsDirect =
[ 1, 1, 1, 1]
[ 2, 2, 2, 2]
[ 3, 3, 3, 3]
[ 4, 4, 4, 4]
columnsReverse =
[ 4, 4, 4, 4]
[ 3, 3, 3, 3]
[ 2, 2, 2, 2]
[ 1, 1, 1, 1]
Calculate the cumulative sum along the rows in both directions. Specify the 'reverse'
option to work from right to left in each row.
rowsDirect = cumsum(A,2)
rowsReverse = cumsum(A,2,'reverse')
rowsDirect =
[ 1, 2, 3, 4]
4-280
cumsum
[ 1, 2, 3, 4]
[ 1, 2, 3, 4]
[ 1, 2, 3, 4]
rowsReverse =
[ 4, 3, 2, 1]
[ 4, 3, 2, 1]
[ 4, 3, 2, 1]
[ 4, 3, 2, 1]
Input Arguments
A Input array
symbolic vector | symbolic matrix
4-281
4 Functions Alphabetical List
Output Arguments
B Cumulative sum array
vector | matrix
Cumulative sum array, returned as a vector or matrix of the same size as the input A.
See Also
cumprod | fold | int | symprod | symsum
Introduced in R2013b
4-282
curl
curl
Curl of vector field
Syntax
curl(V,X)
curl(V)
Description
curl(V,X) returns the curl of the vector field V with respect to the vector X. The vector
field V and the vector X are both three-dimensional.
curl(V) returns the curl of the vector field V with respect to the vector of variables
returned by symvar(V,3).
Input Arguments
V
Examples
Compute the curl of this vector field with respect to vector X=(x, y, z) in Cartesian
coordinates:
syms x y z
4-283
4 Functions Alphabetical List
ans =
x^2*z^3 - 2*x*y^3*z
x^3*y^2 - 2*x*y*z^3
- 2*x^3*y*z + y^3*z^2
Compute the curl of the gradient of this scalar function. The curl of the gradient of any
scalar function is the vector of 0s:
syms x y z
f = x^2 + y^2 + z^2;
curl(gradient(f, [x, y, z]), [x, y, z])
ans =
0
0
0
2V = ( V ) - ( V )
Compute the vector Laplacian of this vector field using the curl, divergence, and
gradient functions:
syms x y z
V = [x^2*y, y^2*z, z^2*x];
gradient(divergence(V, [x, y, z])) - curl(curl(V, [x, y, z]), [x, y, z])
ans =
2*y
2*z
2*x
More About
Curl of a Vector Field
The curl of the vector field V=(V1, V2, V3) with respect to the vector X=(X1, X2, X3) in
Cartesian coordinates is the vector
4-284
curl
V3 V2
-
X 2 X 3
V V
curl (V ) = V = 1 - 3
X 3 X1
V V
2 - 1
X
1 X 2
See Also
diff | divergence | gradient | jacobian | hessian | laplacian | potential |
vectorPotential
Introduced in R2012a
4-285
4 Functions Alphabetical List
daeFunction
Convert system of differential algebraic equations to MATLAB function handle suitable
for ode15i
Syntax
f = daeFunction(eqs,vars)
f = daeFunction(eqs,vars,p1,...,pN)
f = daeFunction( ___ ,Name,Value)
Description
f = daeFunction(eqs,vars) converts a system of symbolic first-order differential
algebraic equations (DAEs) to a MATLAB function handle acceptable as an input
argument to the numerical MATLAB DAE solver ode15i.
Examples
4-286
daeFunction
f =
function_handle with value:
@(t,in2,in3,param1,param2,param3)[in3(1,:)-param1.*in2(1,:)...
-param2.*in2(2,:).^2;-param3.^2+in2(1,:).^2+in2(2,:).^2]
You also can generate a file instead of generating a MATLAB function handle. If the
file myfile.m already exists in the current folder, daeFunction replaces the existing
function with the converted symbolic expression. You can open and edit the resulting file.
YP1 = in3(1,:);
x1 = in2(1,:);
x2 = in2(2,:);
t2 = x2.^2;
eqs = [YP1-param2.*t2-param1.*x1;t2-param3.^2+x1.^2];
Specify the parameter values, and create the reduced function handle F as follows.
a = -0.6;
b = -0.1;
r = @(t) cos(t)/(1 + t^2);
F = @(t, Y, YP) f(t,Y,YP,a,b,r(t));
t0 = 0;
y0 = [-r(t0)*sin(0.1); r(t0)*cos(0.1)];
yp0= [a*y0(1) + b*y0(2)^2; 1.234];
4-287
4 Functions Alphabetical List
Input Arguments
eqs System of first-order DAEs
vector of symbolic equations | vector of symbolic expressions
4-288
daeFunction
State variables, specified as a vector of symbolic functions or function calls, such as x(t).
Example: [x(t),y(t)] or [x(t);y(t)]
Path to the file containing generated code, specified as a character vector. The generated
file accepts arguments of type double, and can be used without Symbolic Math Toolbox.
If the value is an empty character vector, odeFunction generates an anonymous
function. If the character vector does not end in .m, the function appends .m.
By default, daeFunction with the File argument generates a file containing optimized
code. Optimized means intermediate variables are automatically generated to simplify
or speed up the code. MATLAB generates intermediate variables as a lowercase letter
t followed by an automatically generated number, for example t32. To disable code
optimization, use the Optimize argument.
4-289
4 Functions Alphabetical List
By default, daeFunction with the File argument generates a file containing optimized
code. Optimized means intermediate variables are automatically generated to simplify
or speed up the code. MATLAB generates intermediate variables as a lowercase letter t
followed by an automatically generated number, for example t32.
daeFunction without the File argument (or with a file path specified by an empty
character vector) creates a function handle. In this case, the code is not optimized. If you
try to enforce code optimization by setting Optimize to true, then daeFunction throws
an error.
'Sparse' Flag that switches between sparse and dense matrix generation
false (default) | true
Flag that switches between sparse and dense matrix generation, specified as true or
false. When you specify 'Sparse',true, the generated function represents symbolic
matrices by sparse numeric matrices. Use 'Sparse',true when you convert symbolic
matrices containing many zero elements. Often, operations on sparse matrices are more
efficient than the same operations on dense matrices.
Output Arguments
f Function handle that can serve as input argument to ode15i
MATLAB function handle
Function handle that can serve as input argument to ode15i, returned as a MATLAB
function handle.
See Also
decic | findDecoupledBlocks | incidenceMatrix | isLowIndexDAE |
massMatrixForm | matlabFunction | ode15i | odeFunction | reduceDAEIndex |
reduceDAEToODE | reduceDifferentialOrder | reduceRedundancies
Introduced in R2014b
4-290
dawson
dawson
Dawson integral
Syntax
dawson(X)
Description
dawson(X) represents the Dawson integral.
Examples
Compute the Dawson integrals for these numbers. Because these numbers are not
symbolic objects, dawson returns floating-point results.
A =
0 -0.4282 -0.5381 0 0.3013 0
Compute the Dawson integrals for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, dawson returns unresolved symbolic calls.
symA =
[ 0, -dawson(3/2), -dawson(1), 0, dawson(2), 0]
4-291
4 Functions Alphabetical List
vpa(symA)
ans =
[ 0,...
-0.42824907108539862547719010515175,...
-0.53807950691276841913638742040756,...
0,...
0.30134038892379196603466443928642,...
0]
syms x
fplot(dawson(x), [-10, 10])
grid on
4-292
dawson
syms x
diff(dawson(x), x)
diff(dawson(x), x, x)
ans =
1 - 2*x*dawson(x)
4-293
4 Functions Alphabetical List
ans =
2*x*(2*x*dawson(x) - 1) - 2*dawson(x)
ans =
1/2
Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
More About
Dawson Integral
The Dawson integral, also called the Dawson function, is defined as follows:
x
2
t2
dawson ( x) = D ( x ) = e- x e dt
0
x
2
- t2
D ( x) = ex e dt
0
Tips
dawson(0) returns 0.
4-294
dawson
dawson(Inf) returns 0.
dawson(-Inf) returns 0.
See Also
erf | erfc
Introduced in R2014a
4-295
4 Functions Alphabetical List
decic
Find consistent initial conditions for first-order implicit ODE system with algebraic
constraints
Syntax
[y0,yp0] = decic(eqs,vars,constraintEqs,t0,y0_est,fixedVars,yp0_est,
options)
Description
[y0,yp0] = decic(eqs,vars,constraintEqs,t0,y0_est,fixedVars,
yp0_est,options) finds consistent initial conditions for the system of first-order
implicit ordinary differential equations with algebraic constraints returned by the
reduceDAEToODE function.
Substituting the numerical values y0, yp0 into the differential equations subs(eqs,
[t; vars(t); diff(vars(t))], [t0; y0; yp0]) and the constraint equations
subs(constr, [t; vars(t); diff(vars(t))], [t0; y0; yp0]) produces zero
vectors. Here, vars must be a column vector.
y0_est specifies numerical estimates for the values of the variables vars at the time
t0, and fixedVars indicates the values in y0_est that must not change during the
numerical search. The optional argument yp0_est lets you specify numerical estimates
for the values of the derivatives of the variables vars at the time t0.
4-296
decic
Examples
Find Consistent Initial Conditions for ODE System
Reduce the DAE system to a system of implicit ODEs. Then, find consistent initial
conditions for the variables of the resulting ODE system and their first derivatives.
eqs =
diff(x(t), t) - y(t) - cos(t)
- 2*x(t)*diff(x(t), t) - 2*y(t)*diff(y(t), t)
constraintEqs =
1 - y(t)^2 - x(t)^2
Create an option set that specifies numerical tolerances for the numerical search.
options = odeset('RelTol', 10.0^(-7), 'AbsTol', 10.0^(-7));
Fix values t0 = 0 for the time and numerical estimates for consistent values of the
variables and their derivatives.
t0 = 0;
y0_est = [0.1, 0.9];
yp0_est = [0.0, 0.0];
You can treat the constraint as an algebraic equation for the variable x with the fixed
parameter y. For this, set fixedVars = [0 1]. Alternatively, you can treat it as an
algebraic equation for the variable y with the fixed parameter x. For this, set fixedVars
= [1 0].
4-297
4 Functions Alphabetical List
[y0,yp0] = decic(eqs,vars,constraintEqs,t0,y0_est,fixedVars,yp0_est,options)
y0 =
0.1000
0.9950
yp0 =
1.9950
-0.2005
y0 =
-0.4359
0.9000
yp0 =
1.9000
0.9202
Verify that these initial values are consistent initial values satisfying the equations and
the constraints.
subs(eqs, [t; vars; diff(vars,t)], [t0; y0; yp0])
ans =
0
0
ans =
0
Input Arguments
eqs System of implicit ordinary differential equations
vector of symbolic equations | vector of symbolic expressions
4-298
decic
t0 Initial time
number
Estimates for the values of the variables vars at the initial time t0, specified as a
numeric vector.
fixedVars Input vector indicating which elements of y0_est are fixed values
vector with elements 0 or 1
Input vector indicating which elements of y0_est are fixed values, specified as a vector
with 0s or 1s. Fixed values of y0_est correspond to values 1 in fixedVars. These
values are not modified during the numerical search. The zero entries in fixedVars
correspond to those variables in y0_est for which decic solves the constraint equations.
The number of 0s must coincide with the number of constraint equations. The Jacobian
matrix of the constraints with respect to the variables vars(fixedVars == 0) must be
invertible.
yp0_est Estimates for values of first derivatives of variables vars at initial time t0
numeric vector
4-299
4 Functions Alphabetical List
Estimates for the values of the first derivatives of the variables vars at the initial time
t0, specified as a numeric vector.
Options for numerical search, specified as an options structure, returned by odeset. For
example, you can specify tolerances for the numerical search here.
Output Arguments
y0 Consistent initial values for variables
numeric column vector
Consistent initial values for first derivatives of variables, returned as a numeric column
vector.
See Also
daeFunction | findDecoupledBlocks | incidenceMatrix | isLowIndexDAE
| massMatrixForm | odeFunction | reduceDAEIndex | reduceDAEToODE |
reduceDifferentialOrder | reduceRedundancies
Introduced in R2014b
4-300
det
det
Compute determinant of symbolic matrix
Syntax
r = det(A)
Description
r = det(A) computes the determinant of A, where A is a symbolic or numeric matrix.
det(A) returns a symbolic expression for a symbolic A and a numeric value for a
numeric A.
Examples
Compute the determinant of the following symbolic matrix:
syms a b c d
det([a, b; c, d])
ans =
a*d - b*c
Compute the determinant of the following matrix containing the symbolic numbers:
A = sym([2/3 1/3; 1 1])
r = det(A)
A =
[ 2/3, 1/3]
[ 1, 1]
r =
1/3
See Also
rank | eig
4-301
4 Functions Alphabetical List
4-302
diag
diag
Create or extract diagonals of symbolic matrices
Syntax
diag(A,k)
diag(A)
Description
diag(A,k) returns a square symbolic matrix of order n + abs(k), with the elements
of A on the k-th diagonal. A must present a row or column vector with n components. The
value k = 0 signifies the main diagonal. The value k > 0 signifies the k-th diagonal
above the main diagonal. The value k < 0 signifies the k-th diagonal below the main
diagonal. If A is a square symbolic matrix, diag(A, k) returns a column vector formed
from the elements of the k-th diagonal of A.
Examples
Create a symbolic matrix with the main diagonal presented by the elements of the vector
v:
syms a b c
v = [a b c];
diag(v)
ans =
[ a, 0, 0]
[ 0, b, 0]
[ 0, 0, c]
Create a symbolic matrix with the second diagonal below the main one presented by the
elements of the vector v:
4-303
4 Functions Alphabetical List
syms a b c
v = [a b c];
diag(v, -2)
ans =
[ 0, 0, 0, 0, 0]
[ 0, 0, 0, 0, 0]
[ a, 0, 0, 0, 0]
[ 0, b, 0, 0, 0]
[ 0, 0, c, 0, 0]
ans =
a
2
z
ans =
b
3
See Also
tril | triu
4-304
diff
diff
Differentiate symbolic expression or function
Syntax
diff(F)
diff(F,var)
diff(F,n)
diff(F,var,n)
diff(F,var1,...,varN)
Description
diff(F) differentiates F with respect to the variable determined by symvar(F,1).
diff(F,n) computes the nth derivative of F with respect to the variable determined by
symvar.
diff(F,var,n) computes the nth derivative of F with respect to the variable var.
Examples
Differentiation of Univariate Function
Find the first derivative of this univariate function:
syms x
f(x) = sin(x^2);
df = diff(f,x)
df(x) =
4-305
4 Functions Alphabetical List
2*x*cos(x^2)
syms x t
diff(sin(x*t^2))
ans =
t^2*cos(t^2*x)
Because you did not specify the differentiation variable, diff uses the default variable
defined by symvar. For this expression, the default variable is x:
symvar(sin(x*t^2),1)
ans =
x
Now, find the derivative of this expression with respect to the variable t:
diff(sin(x*t^2),t)
ans =
2*t*x*cos(t^2*x)
syms t
d4 = diff(t^6,4)
d5 = diff(t^6,5)
d6 = diff(t^6,6)
d4 =
360*t^2
d5 =
720*t
d6 =
4-306
diff
720
syms x y
diff(x*cos(x*y), y, 2)
ans =
-x^3*cos(x*y)
syms x y
diff(x*y, 2)
ans =
0
If you use nested diff calls and do not specify the differentiation variable, diff
determines the differentiation variable for each call. For example, differentiate the
expression x*y by calling the diff function twice:
diff(diff(x*y))
ans =
1
In the first call, diff differentiate x*y with respect to x, and returns y. In the second
call, diff differentiates y with respect to y, and returns 1.
4-307
4 Functions Alphabetical List
Mixed Derivatives
Differentiate this expression with respect to the variables x and y:
syms x y
diff(x*sin(x*y), x, y)
ans =
2*x*cos(x*y) - x^2*y*sin(x*y)
You also can compute mixed higher-order derivatives by providing all differentiation
variables:
syms x y
diff(x*sin(x*y), x, x, x, y)
ans =
x^2*y^3*sin(x*y) - 6*x*y^2*cos(x*y) - 6*y*sin(x*y)
Input Arguments
F Expression or function to differentiate
symbolic expression | symbolic function | symbolic vector | symbolic matrix
n Differentiation order
nonnegative integer
4-308
diff
More About
Tips
f ( x, y ) = f ( x, y)
x y y x
See Also
curl | divergence | functionalDerivative | gradient | hessian | int |
jacobian | laplacian | symvar
4-309
4 Functions Alphabetical List
digits
Change variable precision used
Syntax
digits(d)
d1 = digits
d1 = digits(d)
Description
digits(d) sets the precision used by vpa to d significant decimal digits. The default is
32 digits.
d1 = digits(d) sets the new precision d and returns the old precision in d1.
Examples
Increase Precision of Results
By default, MATLAB uses 16 digits of precision. For higher precision, use vpa. The
default precision for vpa is 32 digits. Increase precision beyond 32 digits by using
digits.
Find pi using vpa, which uses the default 32 digits of precision. Confirm that the current
precision is 32 by using digits.
pi32 = vpa(pi)
pi32 =
3.1415926535897932384626433832795
currentPrecision = digits
currentPrecision =
4-310
digits
32
Save the current value of digits in digitsOld and set the new precision to 100 digits.
Find pi using vpa. The result has 100 digits.
digitsOld = digits(100);
pi100 = vpa(pi)
pi100 =
3.1415926535897932384626433832795028841971693993751058209...
74944592307816406286208998628034825342117068
Note: vpa output is symbolic. To use symbolic output with a MATLAB function that does
not accept symbolic values, convert symbolic values to double precision by using double.
For more information, see Increase Precision of Numeric Calculations on page 2-84.
Now, repeat the operation with a lower precision by using vpa. Lower the precision to 10
digits by using digits. Then, use vpa to reduce the precision of input and perform the
same operation. The time taken decreases significantly.
digitsOld = digits(10);
vpaInput = vpa(input);
tic
zeta(vpaInput);
4-311
4 Functions Alphabetical List
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 more information, see Increase Speed by Reducing Precision on page 2-91.
Guard Digits
The number of digits that you specify using the vpa function or the digits function is
the guaranteed number of digits. Internally, the toolbox can use a few more digits than
you specify. These additional digits are called guard digits. For example, set the number
of digits to 4, and then display the floating-point approximation of 1/3 using four digits:
old = digits(4);
a = vpa(1/3)
a =
0.3333
Now, display a using 20 digits. The result shows that the toolbox internally used more
than four digits when computing a. The last digits in the following result are incorrect
because of the round-off error:
digits(20)
vpa(a)
digits(old)
ans =
0.33333333333303016843
4-312
digits
a = vpa(1/10)
old = digits(10);
b = vpa(1/10)
digits(old)
a =
0.1
b =
0.1
a - b
ans =
0.000000000000000000086736173798840354720600815844403
The difference a - b is not equal to zero because the toolbox internally boosts the 10-
digit number b = 0.1 to 32-digit accuracy. This process implies round-off errors. The
toolbox actually computes the difference a - b as follows:
b = vpa(b)
a - b
b =
0.09999999999999999991326382620116
ans =
0.000000000000000000086736173798840354720600815844403
r = sym(pi)
f = sym(pi,'f')
d = sym(pi,'d')
4-313
4 Functions Alphabetical List
e = sym(pi,'e')
r =
pi
f =
884279719003555/281474976710656
d =
3.1415926535897931159979634685442
e =
pi - (198*eps)/359
Although the toolbox displays these numbers differently on the screen, they are rational
approximations of pi. Use vpa to convert these rational approximations of pi back to
floating-point values.
Set the number of digits to 4. Three of the four approximations give the same result.
digits(4)
vpa(r)
vpa(f)
vpa(d)
vpa(e)
ans =
3.142
ans =
3.142
ans =
3.142
ans =
3.142 - 0.5515*eps
Now, set the number of digits to 40. The differences between the symbolic
approximations of pi become more visible.
digits(40)
vpa(r)
vpa(f)
vpa(d)
4-314
digits
vpa(e)
ans =
3.141592653589793238462643383279502884197
ans =
3.141592653589793115997963468544185161591
ans =
3.1415926535897931159979634685442
ans =
3.141592653589793238462643383279502884197 -...
0.5515320334261838440111420612813370473538*eps
Input Arguments
d New accuracy setting
number | symbolic number
New accuracy setting, specified as a number or symbolic number. The setting specifies
the number of significant decimal digits to be used for variable-precision calculations. If
the value d is not an integer, digits rounds it to the nearest integer.
Output Arguments
d1 Current accuracy setting
double-precision number
See Also
double | vpa
4-315
4 Functions Alphabetical List
dilog
Dilogarithm function
Syntax
dilog(X)
Description
dilog(X) returns the dilogarithm function.
Examples
Compute the dilogarithm function for these numbers. Because these numbers are not
symbolic objects, dilog returns floating-point results.
A =
2.4674 - 2.1776i 1.6449 + 0.0000i 0.9785 + 0.0000i...
0.5822 + 0.0000i 0.0000 + 0.0000i -0.8225 + 0.0000i
Compute the dilogarithm function for the numbers converted to symbolic objects. For
many symbolic (exact) numbers, dilog returns unresolved symbolic calls.
symA =
[ pi^2/4 - pi*log(2)*1i, pi^2/6, dilog(1/4), pi^2/12 - log(2)^2/2, 0, -pi^2/12]
4-316
dilog
vpa(symA)
ans =
[ 2.467401100272339654708622749969 - 2.1775860903036021305006888982376i,...
1.644934066848226436472415166646,...
0.97846939293030610374306666652456,...
0.58224052646501250590265632015968,...
0,...
-0.82246703342411321823620758332301]
syms x
fplot(dilog(x), [0, 10])
grid on
4-317
4 Functions Alphabetical List
syms x
diff(dilog(x), x)
diff(dilog(x), x, x)
ans =
-log(x)/(x - 1)
4-318
dilog
ans =
log(x)/(x - 1)^2 - 1/(x*(x - 1))
int(dilog(x), x)
ans =
x*(dilog(x) + log(x) - 1) - dilog(x)
limit(dilog(x)/x, Inf)
ans =
0
Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
More About
Dilogarithm Function
x
ln ( t )
dilog ( x ) = 1 - t dt
1
4-319
4 Functions Alphabetical List
0
ln ( 1 - t)
( )
Li 2 x = dt
t
x
Thus, dilog(x)=Li2(1x).
Tips
References
[1] Stegun, I. A. Miscellaneous Functions. Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun,
eds.). New York: Dover, 1972.
See Also
log | zeta
Introduced in R2014a
4-320
dirac
dirac
Dirac delta function
Syntax
dirac(x)
dirac(n,x)
Description
dirac(x) represents the Dirac delta function of x.
Examples
Handle Expressions Involving Dirac and Heaviside Functions
Compute derivatives and integrals of expressions involving the Dirac delta and Heaviside
functions.
Find the first and second derivatives of the Heaviside function. The result is the Dirac
delta function and its first derivative.
syms x
diff(heaviside(x), x)
diff(heaviside(x), x, x)
ans =
dirac(x)
ans =
dirac(1, x)
Find the indefinite integral of the Dirac delta function. The results returned by int do
not include integration constants.
4-321
4 Functions Alphabetical List
int(dirac(x), x)
ans =
sign(x)/2
Find the integral of this expression involving the Dirac delta function.
syms a
int(dirac(x - a)*sin(x), x, -Inf, Inf)
ans =
sin(a)
syms x real
assumeAlso(x ~= 0)
dirac(x)
ans =
0
Use a vector n = [0, 1, 2, 3] to specify the order of derivatives. The dirac function
expands the scalar into a vector of the same size as n and computes the result.
n = [0, 1, 2, 3];
d = dirac(n, x)
d =
[ dirac(x), dirac(1, x), dirac(2, x), dirac(3, x)]
Substitute x with 0.
subs(d, x, 0)
4-322
dirac
ans =
[ Inf, -Inf, Inf, -Inf]
Input Arguments
x Input
number | symbolic number | symbolic variable | symbolic expression | symbolic
function | vector | matrix | multidimensional array
n Order of derivative
nonnegative number | symbolic variable | symbolic expression | symbolic function |
vector | matrix | multidimensional array
More About
Dirac delta Function
The Dirac delta function, (x), has the value 0 for all x0, and for x=0.
Tips
For complex values x with nonzero imaginary parts, dirac returns NaN.
dirac returns floating-point results for numeric arguments that are not symbolic
objects.
4-323
4 Functions Alphabetical List
See Also
heaviside | kroneckerDelta
4-324
disp
disp
Display symbolic input
Syntax
disp(X)
Description
disp(X) displays the symbolic input X. disp does not display the arguments name.
Examples
x^3 - exp(x)
4-325
4 Functions Alphabetical List
x + 1
symbolic function inputs: x
syms x
disp(['Euler''s formula is ',char(exp(i*x)),' = ',char(cos(x)+i*sin(x)),'.'])
Because ' terminates the character vector, repeat it in Euler''s for MATLAB to
interpret it as an apostrophe and not a character vector terminator.
Input Arguments
X Symbolic input to display
symbolic variable | symbolic vector | symbolic matrix | symbolic function | symbolic
multidimensional array | symbolic expression
See Also
char | disp | display | pretty
4-326
display
display
Display symbolic input
Syntax
display(X)
Description
display(X) displays the symbolic input X.
Examples
y =
x^3 - exp(x)
A =
[ a11, a12, a13]
[ a21, a22, a23]
[ a31, a32, a33]
4-327
4 Functions Alphabetical List
f(x) = x+1;
display(f)
f(x) =
x + 1
syms x
display(['Euler''s formula is ',char(exp(i*x)),' = ',char(cos(x)+i*sin(x)),'.'])
Because ' terminates the character vector, you need to repeat it in Euler''s for
MATLAB to interpret it as an apostrophe and not a character vector terminator.
Input Arguments
X Symbolic input to display
symbolic variable | symbolic vector | symbolic matrix | symbolic function | symbolic
multidimensional array | symbolic expression
See Also
char | disp | display | pretty
4-328
divergence
divergence
Divergence of vector field
Syntax
divergence(V,X)
Description
divergence(V,X) returns the divergence of vector field V with respect to the vector X in
Cartesian coordinates. Vectors V and X must have the same length.
Examples
Find Divergence of Vector Field
Find the divergence of the vector field V(x,y,z)=(x, 2y2, 3z3) with respect to vector
X=(x,y,z) in Cartesian coordinates.
syms x y z
divergence([x, 2*y^2, 3*z^3], [x, y, z])
ans =
9*z^2 + 4*y + 1
Find the divergence of the curl of this vector field. The divergence of the curl of any
vector field is 0.
syms x y z
divergence(curl([x, 2*y^2, 3*z^3], [x, y, z]), [x, y, z])
ans =
0
Find the divergence of the gradient of this scalar function. The result is the Laplacian of
the scalar function.
syms x y z
4-329
4 Functions Alphabetical List
ans =
6
r ( r)
r r r r
. E ( r ) = .
e0
syms x y ep0
E = [x^2 y^2];
rho = divergence(E,[x y])*ep0
rho =
ep0*(2*x + 2*y)
Visualize the electric field and electric charge density for -2 < x < 2 and -2 <
y < 2 with ep0 = 1. Create a grid of values of x and y using meshgrid. Find the
values of electric field and charge density by substituting grid values using subs. To
simultaneously substitute the grid values xPlot and yPlot into the charge density rho,
use cells arrays as inputs to subs.
rho = subs(rho,ep0,1);
v = -2:0.1:2;
[xPlot,yPlot] = meshgrid(v);
Ex = subs(E(1),x,xPlot);
Ey = subs(E(2),y,yPlot);
rhoPlot = double(subs(rho,{x,y},{xPlot,yPlot}));
Plot the electric field using quiver. Overlay the charge density using contour. The
contour lines indicate the values of the charge density.
quiver(xPlot,yPlot,Ex,Ey)
hold on
contour(xPlot,yPlot,rhoPlot,'ShowText','on')
4-330
divergence
Input Arguments
V Vector field
symbolic expression | symbolic function | vector of symbolic expressions | vector of
symbolic functions
4-331
4 Functions Alphabetical List
Variables with respect to which you find the divergence, specified as a symbolic variable
or a vector of symbolic variables. X must be the same length as V.
More About
Divergence of Vector Field
The divergence of the vector field V=(V1,...,Vn) with respect to the vector X=(X1,...,Xn) in
Cartesian coordinates is the sum of partial derivatives of V with respect to X1,...,Xn
n
r r Vi
div(V ) = V = .
i=1 xi
See Also
curl | diff | gradient | hessian | jacobian | laplacian | potential |
vectorPotential
Introduced in R2012a
4-332
divisors
divisors
Divisors of integer or expression
Syntax
divisors(n)
divisors(expr,vars)
Description
divisors(n) finds all nonnegative divisors of an integer n.
Examples
Divisors of Integers
Find all nonnegative divisors of these integers.
Find the divisors of integers. You can use double precision numbers or numbers
converted to symbolic objects. If you call divisors for a double-precision number, then it
returns a vector of double-precision numbers.
divisors(42)
ans =
1 2 3 6 7 14 21 42
Find the divisors of negative integers. divisors returns nonnegative divisors for
negative integers.
divisors(-42)
ans =
4-333
4 Functions Alphabetical List
1 2 3 6 7 14 21 42
divisors(sym(42))
ans =
[ 1, 2, 3, 6, 7, 14, 21, 42]
divisors(0)
ans =
0
Find the divisors of this univariate polynomial. You can specify the polynomial as a
symbolic expression.
syms x
divisors(x^4 - 1, x)
ans =
[ 1, x - 1, x + 1, (x - 1)*(x + 1), x^2 + 1, (x^2 + 1)*(x - 1),...
(x^2 + 1)*(x + 1), (x^2 + 1)*(x - 1)*(x + 1)]
syms f(t)
f(t) = t^5;
divisors(f,t)
ans(t) =
[ 1, t, t^2, t^3, t^4, t^5]
When finding the divisors of a polynomial, divisors does not return the divisors of the
constant factor.
f(t) = 9*t^5;
divisors(f,t)
4-334
divisors
ans(t) =
[ 1, t, t^2, t^3, t^4, t^5]
Find the divisors of the multivariate polynomial expression. Suppose that u and v are
variables, and a is a symbolic parameter. Specify the variables as a symbolic vector.
syms a u v
divisors(a*u^2*v^3, [u,v])
ans =
[ 1, u, u^2, v, u*v, u^2*v, v^2, u*v^2, u^2*v^2, v^3, u*v^3, u^2*v^3]
Now, suppose that this expression contains only one variable (for example, v), while
a and u are symbolic parameters. Here, divisors treats the expression a*u^2 as a
constant and ignores it, returning only the divisors of v^3.
divisors(a*u^2*v^3, v)
ans =
[ 1, v, v^2, v^3]
Input Arguments
n Number for which to find divisors
number | symbolic number
Number for which to find the divisors, specified as a number or symbolic number.
4-335
4 Functions Alphabetical List
More About
Tips
divisors(0) returns 0.
divisors(expr,vars) does not return the divisors of the constant factor when
finding the divisors of a polynomial.
If you do not specify polynomial variables, divisors returns as many divisors as
it can find, including the divisors of constant symbolic expressions. For example,
divisors(sym(pi)^2*x^2) returns [ 1, pi, pi^2, x, pi*x, pi^2*x, x^2,
pi*x^2, pi^2*x^2] while divisors(sym(pi)^2*x^2, x) returns [ 1, x,
x^2].
For rational numbers, divisors returns all divisors of the numerator divided by all
divisors of the denominator. For example, divisors(sym(9/8)) returns [ 1, 3,
9, 1/2, 3/2, 9/2, 1/4, 3/4, 9/4, 1/8, 3/8, 9/8].
See Also
coeffs | factor | numden
Introduced in R2014b
4-336
doc
doc
Get help for MuPAD functions
Syntax
doc(symengine)
doc(symengine,'MuPAD_function_name')
Description
doc(symengine) opens Getting Started with MuPAD.
Examples
doc(symengine,'simplify') opens the documentation page for the MuPAD
simplify function.
Introduced in R2008b
4-337
4 Functions Alphabetical List
double
Convert symbolic values to MATLAB double precision
Syntax
double(s)
Description
double(s) converts the symbolic value s to double precision. Converting symbolic
values to double precision is useful when a MATLAB function does not accept symbolic
values. For differences between symbolic and double-precision numbers, see Choose
Symbolic or Numeric Arithmetic on page 2-82.
Examples
symN =
[ pi, 1/3]
doubleN = double(symN)
doubleN =
3.1416 0.3333
For information on round-off errors, see Recognize and Avoid Round-Off Errors on page
2-86.
4-338
double
vpaN =
[ 3.1415926535897932384626433832795, 0.33333333333333333333333333333333]
doubleN = double(vpaN)
doubleN =
3.1416 0.3333
symM =
[ 2^(1/2), 2/3]
[ (2*2^(1/2))/3, 2^(1/2)/3]
doubleM = double(symM)
doubleM =
1.4142 0.6667
0.9428 0.4714
High-Precision Conversion
When converting symbolic expressions that suffer from internal cancelation or round-off
errors, increase the working precision by using digits before converting the number.
4-339
4 Functions Alphabetical List
lowPrecisionY =
0
digitsOld = digits(100);
highPrecisionY = double(Y)
highPrecisionY =
2.7678e-87
digits(digitsOld)
Input Arguments
s Symbolic input
symbolic number | vector of symbolic numbers | matrix of symbolic numbers |
multidimensional array of symbolic numbers
More About
Choose Symbolic or Numeric Arithmetic on page 2-82
Increase Precision of Numeric Calculations on page 2-84
Recognize and Avoid Round-Off Errors on page 2-86
Increase Speed by Reducing Precision on page 2-91
See Also
sym | vpa
4-340
dsolve
dsolve
Differential equations and systems solver
Compatibility
Character vector inputs are not recommended. Instead, use syms to declare variables
and replace inputs such as dsolve('Dy = y') with syms y(t); dsolve(diff(y,t)
== y).
Syntax
S = dsolve(eqn)
S = dsolve(eqn,cond)
S = dsolve(eqn,cond,Name,Value)
Description
S = dsolve(eqn) solves the differential equation eqn, where eqn is a symbolic
equation. Use diff and == to represent differential equations. For example, diff(y,x)
== y represents the equation dy/dx=y. Solve a system of differential equations by
specifying eqn as a vector of those equations.
4-341
4 Functions Alphabetical List
Examples
Solve Differential Equation
Specify a differential equation by using == and represent differentiation by using the
diff function. Then, solve the equation by using dsolve.
dy
Solve the equation = ay .
dt
syms a y(t)
eqn = diff(y,t) == a*y;
dsolve(eqn)
ans =
C2*exp(a*t)
For more examples, see Solve a Single Differential Equation on page 2-151. For a
complex workflow involving differential equations, see Solving Partial Differential
Equations.
d2 y
Solve the equation = ay .
dt2
syms y(t) a
eqn = diff(y,t,2) == a*y;
ySol(t) = dsolve(eqn)
ySol(t) =
C5*exp(a^(1/2)*t) + C6*exp(-a^(1/2)*t)
C5 and C6 are constants. You can eliminate constants by specifying conditions. See Solve
Differential Equation with Condition on page 4-343.
4-342
dsolve
dy
Solve the equation = ay with the condition y ( 0 ) = 5 .
dt
syms y(t) a
eqn = diff(y,t) == a*y;
cond = y(0) == 5;
ySol(t) = dsolve(eqn,cond)
ySol(t) =
5*exp(a*t)
d2 y
Solve the second-order differential equation = a2 y with two conditions, y ( 0 ) = b
dt2
and y ( 0 ) = 1 . Create the second condition by assigning diff(y,t) to Dy and then using
Dy(0) == 1.
syms y(t) a b
eqn = diff(y,t,2) == a^2*y;
Dy = diff(y,t);
cond = [y(0)==b, Dy(0)==1];
ySol(t) = dsolve(eqn,cond)
ySol(t) =
(exp(a*t)*(a*b + 1))/(2*a) + (exp(-a*t)*(a*b - 1))/(2*a)
Since two conditions are specified here, constants are eliminated from the solution of the
second-order equation. In general, to eliminate constants from the solution, the number
of conditions must equal the order of the equation.
4-343
4 Functions Alphabetical List
dy
=z
dt
dz
= - y.
dt
sol =
struct with fields:
z: [11 sym]
y: [11 sym]
soly(t) = sol.y
soly(t) =
C2*cos(t) + C1*sin(t)
solz(t) = sol.z
solz(t) =
C1*cos(t) - C2*sin(t)
ySol(t) =
C2*cos(t) + C1*sin(t)
zSol(t) =
4-344
dsolve
C1*cos(t) - C2*sin(t)
syms y(x)
eqn = exp(diff(y)) == 0;
dsolve(eqn)
ans =
[ empty sym ]
dy a
Solve = + y where y ( a ) = 1 with and without simplifications. Turn off
dt y
simplifications by setting IgnoreAnalyticConstraints to false.
syms a y(t)
eqn = diff(y) == a/sqrt(y) + y;
cond = y(a) == 1;
withSimplifications = dsolve(eqn, cond)
withSimplifications =
(exp((3*t)/2 - (3*a)/2 + log(a + 1)) - a)^(2/3)
withoutSimplifications =
piecewise(pi/2 < angle(-a), {piecewise(in(C11, 'integer'),...
(- a + exp((3*t)/2 - (3*a)/2 + log(a + 1) + pi*C11*2i))^(2/3))},...
angle(-a) <= -pi/2, {piecewise(in(C12, 'integer'),...
(- a + exp((3*t)/2 - (3*a)/2 + log(a + 1) + pi*C12*2i))^(2/3))},...
4-345
4 Functions Alphabetical List
Further, for certain equations, dsolve cannot find an explicit solution if you set
IgnoreAnalyticConstraints to false.
Input Arguments
eqn Differential equation or system of equations
symbolic equation | vector of symbolic equations
syms y(x)
dsolve(diff(y,x,2) == x*y)
When a condition contains a derivative, represent the derivative with diff and assign
the diff call to a variable. Then create conditions by using that variable. For an
example, see Solve Differential Equation with Condition on page 4-343.
4-346
dsolve
'MaxDegree' Maximum degree of polynomial equation for which solver uses explicit
formulas
2 (default) | positive integer smaller than 5
Maximum degree of polynomial equations for which solver uses explicit formulas,
specified as a positive integer smaller than 5. dsolve does not use explicit formulas
when solving polynomial equations of degrees larger than MaxDegree.
Output Arguments
S Solutions of differential equation
symbolic expression | vector of symbolic expressions
4-347
4 Functions Alphabetical List
More About
Tips
Algorithms
log(a) + log(b)=log(ab) for all values of a and b. In particular, the following equality
is applied for all values of a, b, and c:
(ab)c=acbc.
log(ab)=blog(a) for all values of a and b. In particular, the following equality is
applied for all values of a, b, and c:
(ab)c=abc.
If f and g are standard mathematical functions and f(g(x))=x for all small positive
numbers, f(g(x))=x is assumed to be valid for all complex x. In particular:
log(ex)=x
4-348
dsolve
See Also
functionalDerivative | linsolve | ode23 | ode45 | odeToVectorField | solve
| syms | vpasolve
4-349
4 Functions Alphabetical List
ei
One-argument exponential integral function
Syntax
ei(x)
Description
ei(x) returns the one-argument exponential integral defined as
x
et
ei ( x) = dt.
t
-
Examples
Exponential Integral for Floating-Point and Symbolic Numbers
Compute exponential integrals for numeric inputs. Because these numbers are not
symbolic objects, you get floating-point results.
s = [ei(-2), ei(-1/2), ei(1), ei(sqrt(2))]
s =
-0.0489 -0.5598 1.8951 3.0485
Compute exponential integrals for the same numbers converted to symbolic objects. For
most symbolic (exact) numbers, ei returns unresolved symbolic calls.
s = [ei(sym(-2)), ei(sym(-1/2)), ei(sym(1)), ei(sqrt(sym(2)))]
s =
[ ei(-2), ei(-1/2), ei(1), ei(2^(1/2))]
4-350
ei
vpa(s, 10)
ans =
[ -0.04890051071, -0.5597735948, 1.895117816, 3.048462479]
ans =
-0.2194 + 0.0000i -0.2194 + 3.1416i -0.2194 - 3.1416i
syms x
diff(ei(x), x)
diff(ei(x), x, 2)
diff(ei(x), x, 3)
ans =
exp(x)/x
ans =
exp(x)/x - exp(x)/x^2
ans =
exp(x)/x - (2*exp(x))/x^2 + (2*exp(x))/x^3
syms x
limit(ei(2*x^2/(1+x)), x, -Inf)
limit(ei(2*x^2/(1+x)), x, 0)
limit(ei(2*x^2/(1+x)), x, Inf)
4-351
4 Functions Alphabetical List
ans =
0
ans =
-Inf
ans =
Inf
Input Arguments
x Input
floating-point number | symbolic number | symbolic variable | symbolic expression |
symbolic function | symbolic vector | symbolic matrix
More About
Tips
Algorithms
Both functions ei(x) and expint(1,x) have a logarithmic singularity at the origin
and a branch cut along the negative real axis. The ei function is not continuous when
approached from above or below this branch cut.
References
[1] Gautschi, W., and W. F. Gahill Exponential Integral and Related Functions.
Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical
Tables. (M. Abramowitz and I. A. Stegun, eds.). New York: Dover, 1972.
4-352
ei
See Also
expint | expint | int | vpa
Introduced in R2013a
4-353
4 Functions Alphabetical List
eig
Eigenvalues and eigenvectors of symbolic matrix
Syntax
lambda = eig(A)
[V,D] = eig(A)
[V,D,P] = eig(A)
lambda = eig(vpa(A))
[V,D] = eig(vpa(A))
Description
lambda = eig(A) returns a symbolic vector containing the eigenvalues of the square
symbolic matrix A.
[V,D,P] = eig(A) returns a vector of indices P. The length of P equals to the total
number of linearly independent eigenvectors, so that A*V = V*D(P,P).
Examples
Compute the eigenvalues for the magic square of order 5:
M = sym(magic(5));
eig(M)
4-354
eig
ans =
65
(625/2 - (5*3145^(1/2))/2)^(1/2)
((5*3145^(1/2))/2 + 625/2)^(1/2)
-(625/2 - (5*3145^(1/2))/2)^(1/2)
-((5*3145^(1/2))/2 + 625/2)^(1/2)
Compute the eigenvalues for the magic square of order 5 using variable-precision
arithmetic:
M = sym(magic(5));
eig(vpa(M))
ans =
65.0
21.27676547147379553062642669797423
13.12628093070921880252564308594914
-13.126280930709218802525643085949
-21.276765471473795530626426697974
Compute the eigenvalues and eigenvectors for one of the MATLAB test matrices:
A = sym(gallery(5))
[v, lambda] = eig(A)
A =
[ -9, 11, -21, 63, -252]
[ 70, -69, 141, -421, 1684]
[ -575, 575, -1149, 3451, -13801]
[ 3891, -3891, 7782, -23345, 93365]
[ 1024, -1024, 2048, -6144, 24572]
v =
0
21/256
-71/128
973/256
1
lambda =
[ 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]
4-355
4 Functions Alphabetical List
More About
Eigenvalues on page 2-105
See Also
charpoly | svd | vpa | jordan
4-356
ellipke
ellipke
Complete elliptic integrals of the first and second kinds
Syntax
[K,E] = ellipke(m)
Description
[K,E] = ellipke(m) returns the complete elliptic integrals of the first and second
kinds.
Input Arguments
m
Symbolic number, variable, expression, or function. This argument also can be a vector or
matrix of symbolic numbers, variables, expressions, or functions.
Output Arguments
K
Examples
Compute the complete elliptic integrals of the first and second kinds for these numbers.
Because these numbers are not symbolic objects, you get floating-point results.
4-357
4 Functions Alphabetical List
K0 =
1.5708
E0 =
1.5708
K05 =
1.8541
E05 =
1.3506
Compute the complete elliptic integrals for the same numbers converted to symbolic
objects. For most symbolic (exact) numbers, ellipke returns results using the
ellipticK and ellipticE functions.
K0 =
pi/2
E0 =
pi/2
K05 =
ellipticK(1/2)
E05 =
ellipticE(1/2)
ans =
[ 1.854074677, 1.350643881]
If the argument does not belong to the range from 0 to 1, then convert that argument to a
symbolic object before using ellipke:
[K, E] = ellipke(sym(pi/2))
4-358
ellipke
K =
ellipticK(pi/2)
E =
ellipticE(pi/2)
Alternatively, use ellipticK and ellipticE to compute the integrals of the first and
the second kinds separately:
K = ellipticK(sym(pi/2))
E = ellipticE(sym(pi/2))
K =
ellipticK(pi/2)
E =
ellipticE(pi/2)
Call ellipke for this symbolic matrix. When the input argument is a matrix, ellipke
computes the complete elliptic integrals of the first and second kinds for each element.
K =
[ ellipticK(-1), pi/2]
[ ellipticK(1/2), Inf]
E =
[ ellipticE(-1), pi/2]
[ ellipticE(1/2), 1]
Alternatives
You can use ellipticK and ellipticE to compute elliptic integrals of the first and
second kinds separately.
More About
Complete Elliptic Integral of the First Kind
4-359
4 Functions Alphabetical List
p 2
p 1
K (m ) = F | m = dq
2 1 - m sin2 q
0
Note that some definitions use the elliptical modulus k or the modular angle instead of
the parameter m. They are related as m=k2=sin2.
p 2
p
E ( m) = E | m = 1 - m sin 2 q dq
2
0
Note that some definitions use the elliptical modulus k or the modular angle instead of
the parameter m. They are related as m=k2=sin2.
Tips
Calling ellipke for numbers that are not symbolic objects invokes the MATLAB
ellipke function. This function accepts only 0 <= x <= 1. To compute the complete
elliptic integrals of the first and second kinds for the values out of this range, use sym
to convert the numbers to symbolic objects, and then call ellipke for those symbolic
objects. Alternatively, use the ellipticK and ellipticE functions to compute the
integrals separately.
For most symbolic (exact) numbers, ellipke returns results using the ellipticK
and ellipticE functions. You can approximate such results with floating-point
numbers using vpa.
If m is a vector or a matrix, then [K,E] = ellipke(m) returns the complete elliptic
integrals of the first and second kinds, evaluated for each element of m.
References
[1] Milne-Thomson, L. M. Elliptic Integrals. Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun,
eds.). New York: Dover, 1972.
4-360
ellipke
See Also
ellipke | ellipticE | ellipticK | vpa
Introduced in R2013a
4-361
4 Functions Alphabetical List
ellipticCE
Complementary complete elliptic integral of the second kind
Syntax
ellipticCE(m)
Description
ellipticCE(m) returns the complementary complete elliptic integral of the second
kind.
Input Arguments
m
Number, symbolic number, variable, expression, or function. This argument also can be a
vector or matrix of numbers, symbolic numbers, variables, expressions, or functions.
Examples
Find Complementary Complete Elliptic Integral of the Second Kind
Compute the complementary complete elliptic integrals of the second kind for these
numbers. Because these numbers are not symbolic objects, you get floating-point results.
s = [ellipticCE(0), ellipticCE(pi/4),...
ellipticCE(1), ellipticCE(pi/2)]
s =
1.0000 1.4828 1.5708 1.7753
Compute the complementary complete elliptic integrals of the second kind for the same
numbers converted to symbolic objects. For most symbolic (exact) numbers, ellipticCE
returns unresolved symbolic calls.
4-362
ellipticCE
s = [ellipticCE(sym(0)), ellipticCE(sym(pi/4)),...
ellipticCE(sym(1)), ellipticCE(sym(pi/2))]
s =
[ 1, ellipticCE(pi/4), pi/2, ellipticCE(pi/2)]
vpa(s, 10)
ans =
[ 1.0, 1.482786927, 1.570796327, 1.775344699]
ans =
[ ellipticCE(pi/6), ellipticCE(pi/4)]
[ ellipticCE(pi/3), ellipticCE(pi/2)]
syms m
diff(ellipticCE(m))
diff(ellipticCE(m^2), m, 2)
ans =
ellipticCE(m)/(2*m - 2) - ellipticCK(m)/(2*m - 2)
ans =
(2*ellipticCE(m^2))/(2*m^2 - 2) -...
(2*ellipticCK(m^2))/(2*m^2 - 2) +...
2*m*(((2*m*ellipticCK(m^2))/(2*m^2 - 2) -...
ellipticCE(m^2)/(m*(m^2 - 1)))/(2*m^2 - 2) +...
4-363
4 Functions Alphabetical List
(2*m*(ellipticCE(m^2)/(2*m^2 - 2) -...
ellipticCK(m^2)/(2*m^2 - 2)))/(2*m^2 - 2) -...
(4*m*ellipticCE(m^2))/(2*m^2 - 2)^2 +...
(4*m*ellipticCK(m^2))/(2*m^2 - 2)^2)
Here, ellipticCK represents the complementary complete elliptic integral of the first
kind.
syms m
fplot(ellipticCE(m))
title('Complementary complete elliptic integral of the second kind')
ylabel('ellipticCE(m)')
grid on
4-364
ellipticCE
More About
Complementary Complete Elliptic Integral of the Second Kind
p 2
p
E ( m) = E | m = 1 - m sin 2 q dq
2
0
4-365
4 Functions Alphabetical List
Note that some definitions use the elliptical modulus k or the modular angle instead of
the parameter m. They are related as m=k2=sin2.
Tips
ellipticCE returns floating-point results for numeric arguments that are not
symbolic objects.
For most symbolic (exact) numbers, ellipticCE returns unresolved symbolic calls.
You can approximate such results with floating-point numbers using vpa.
If m is a vector or a matrix, then ellipticCE(m) returns the complementary
complete elliptic integral of the second kind, evaluated for each element of m.
References
[1] Milne-Thomson, L. M. Elliptic Integrals. Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun,
eds.). New York: Dover, 1972.
See Also
ellipke | ellipticCK | ellipticCPi | ellipticE | ellipticF | ellipticK |
ellipticPi | vpa
Introduced in R2013a
4-366
ellipticCK
ellipticCK
Complementary complete elliptic integral of the first kind
Syntax
ellipticCK(m)
Description
ellipticCK(m) returns the complementary complete elliptic integral of the first kind.
Input Arguments
m
Number, symbolic number, variable, expression, or function. This argument also can be a
vector or matrix of numbers, symbolic numbers, variables, expressions, or functions.
Examples
s =
1.8541 1.6671 1.5708 NaN
Compute the complete elliptic integrals of the first kind for the same numbers converted
to symbolic objects. For most symbolic (exact) numbers, ellipticCK returns unresolved
symbolic calls.
4-367
4 Functions Alphabetical List
s = [ellipticCK(sym(1/2)), ellipticCK(sym(pi/4)),...
ellipticCK(sym(1)), ellipticCK(sym(inf))]
s =
[ ellipticCK(1/2), ellipticCK(pi/4), pi/2, ellipticCK(Inf)]
vpa(s, 10)
ans =
[ 1.854074677, 1.667061338, 1.570796327, NaN]
syms m
diff(ellipticCK(m))
diff(ellipticCK(m^2), m, 2)
ans =
ellipticCE(m)/(2*m*(m - 1)) - ellipticCK(m)/(2*m - 2)
ans =
(2*(ellipticCE(m^2)/(2*m^2 - 2) -...
ellipticCK(m^2)/(2*m^2 - 2)))/(m^2 - 1) -...
(2*ellipticCE(m^2))/(m^2 - 1)^2 -...
(2*ellipticCK(m^2))/(2*m^2 - 2) +...
(8*m^2*ellipticCK(m^2))/(2*m^2 - 2)^2 +...
(2*m*((2*m*ellipticCK(m^2))/(2*m^2 - 2) -...
ellipticCE(m^2)/(m*(m^2 - 1))))/(2*m^2 - 2) -...
ellipticCE(m^2)/(m^2*(m^2 - 1))
Here, ellipticCE represents the complementary complete elliptic integral of the second
kind.
4-368
ellipticCK
ans =
[ ellipticCK(pi/6), ellipticCK(pi/4)]
[ ellipticCK(pi/3), ellipticCK(pi/2)]
syms m
fplot(ellipticCK(m), [0.1, 5])
title('Complementary complete elliptic integral of the first kind')
ylabel('ellipticCK(m)')
grid on
hold off
4-369
4 Functions Alphabetical List
More About
Complementary Complete Elliptic Integral of the First Kind
p 2
p 1
K (m ) = F | m = dq
2 1 - m sin2 q
0
4-370
ellipticCK
Note that some definitions use the elliptical modulus k or the modular angle instead of
the parameter m. They are related as m=k2=sin2.
Tips
ellipticK returns floating-point results for numeric arguments that are not
symbolic objects.
For most symbolic (exact) numbers, ellipticCK returns unresolved symbolic
calls. You can approximate such results with floating-point numbers using the vpa
function.
If m is a vector or a matrix, then ellipticCK(m) returns the complementary
complete elliptic integral of the first kind, evaluated for each element of m.
References
[1] Milne-Thomson, L. M. Elliptic Integrals. Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun,
eds.). New York: Dover, 1972.
See Also
ellipke | ellipticCE | ellipticCPi | ellipticE | ellipticF | ellipticK |
ellipticPi | vpa
Introduced in R2013a
4-371
4 Functions Alphabetical List
ellipticCPi
Complementary complete elliptic integral of the third kind
Syntax
ellipticCPi(n,m)
Description
ellipticCPi(n,m) returns the complementary complete elliptic integral of the third
kind.
Input Arguments
n
Examples
Compute the complementary complete elliptic integrals of the third kind for these
numbers. Because these numbers are not symbolic objects, you get floating-point results.
s = [ellipticCPi(-1, 1/3), ellipticCPi(0, 1/2),...
ellipticCPi(9/10, 1), ellipticCPi(-1, 0)]
s =
1.3703 1.8541 4.9673 Inf
4-372
ellipticCPi
Compute the complementary complete elliptic integrals of the third kind for the
same numbers converted to symbolic objects. For most symbolic (exact) numbers,
ellipticCPi returns unresolved symbolic calls.
s = [ellipticCPi(-1, sym(1/3)), ellipticCPi(sym(0), 1/2),...
ellipticCPi(sym(9/10), 1), ellipticCPi(-1, sym(0))]
s =
[ ellipticCPi(-1, 1/3), ellipticCK(1/2), (pi*10^(1/2))/2, Inf]
Here, ellipticCK represents the complementary complete elliptic integrals of the first
kind.
ans =
[ 1.370337322, 1.854074677, 4.967294133, Inf]
ans =
ellipticCK(m)/(2*n*(n - 1)) -...
ellipticCE(m)/(2*(n - 1)*(m + n - 1)) -...
(ellipticCPi(n, m)*(n^2 + m - 1))/(2*n*(n - 1)*(m + n - 1))
ans =
ellipticCE(m)/(2*m*(m + n - 1)) - ellipticCPi(n, m)/(2*(m + n - 1))
More About
Complementary Complete Elliptic Integral of the Third Kind
4-373
4 Functions Alphabetical List
p 2
p 1
P ( n, m) = P n; | m = dq
0 ( 1 - n sin q )
2 2
1 - m sin 2 q
Note that some definitions use the elliptical modulus k or the modular angle instead of
the parameter m. They are related as m=k2=sin2.
Tips
ellipticCPi returns floating-point results for numeric arguments that are not
symbolic objects.
For most symbolic (exact) numbers, ellipticCPi returns unresolved symbolic calls.
You can approximate such results with floating-point numbers using vpa.
At least one input argument must be a scalar or both arguments must be vectors or
matrices of the same size. If one input argument is a scalar and the other one is a
vector or a matrix, then ellipticCPi expands the scalar into a vector or matrix of
the same size as the other argument with all elements equal to that scalar.
References
[1] Milne-Thomson, L. M. Elliptic Integrals. Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun,
eds.). New York: Dover, 1972.
See Also
ellipke | ellipticCE | ellipticCK | ellipticE | ellipticF | ellipticK |
ellipticPi | vpa
Introduced in R2013a
4-374
ellipticE
ellipticE
Complete and incomplete elliptic integrals of the second kind
Syntax
ellipticE(m)
ellipticE(phi,m)
Description
ellipticE(m) returns the complete elliptic integral of the second kind.
Input Arguments
m
phi
Examples
Find Complete Elliptic Integrals of Second Kind
Compute the complete elliptic integrals of the second kind for these numbers. Because
these numbers are not symbolic objects, you get floating-point results.
4-375
4 Functions Alphabetical List
s = [ellipticE(-10.5), ellipticE(-pi/4),...
ellipticE(0), ellipticE(1)]
s =
3.7096 1.8443 1.5708 1.0000
Compute the complete elliptic integral of the second kind for the same numbers
converted to symbolic objects. For most symbolic (exact) numbers, ellipticE returns
unresolved symbolic calls.
s = [ellipticE(sym(-10.5)), ellipticE(sym(-pi/4)),...
ellipticE(sym(0)), ellipticE(sym(1))]
s =
[ ellipticE(-21/2), ellipticE(-pi/4), pi/2, 1]
vpa(s, 10)
ans =
[ 3.70961391, 1.844349247, 1.570796327, 1.0]
syms m
diff(ellipticE(pi/3, m))
diff(ellipticE(m^2), m, 2)
ans =
ellipticE(pi/3, m)/(2*m) - ellipticF(pi/3, m)/(2*m)
ans =
2*m*((ellipticE(m^2)/(2*m^2) -...
ellipticK(m^2)/(2*m^2))/m - ellipticE(m^2)/m^3 +...
ellipticK(m^2)/m^3 + (ellipticK(m^2)/m +...
ellipticE(m^2)/(m*(m^2 - 1)))/(2*m^2)) +...
ellipticE(m^2)/m^2 - ellipticK(m^2)/m^2
4-376
ellipticE
ans =
[ ellipticE(1/3), 1]
[ ellipticE(1/2), pi/2]
syms m
fplot([ellipticE(pi/4, m) ellipticE(pi/3, m) ellipticE(m)])
4-377
4 Functions Alphabetical List
Alternatives
You can use ellipke to compute elliptic integrals of the first and second kinds in one
function call.
More About
Incomplete Elliptic Integral of the Second Kind
4-378
ellipticE
j
E (j | m ) = 1 - m sin2 q dq
0
Note that some definitions use the elliptical modulus k or the modular angle instead of
the parameter m. They are related as m=k2=sin2.
p 2
p
E ( m) = E | m = 1 - m sin 2 q dq
2
0
Note that some definitions use the elliptical modulus k or the modular angle instead of
the parameter m. They are related as m=k2=sin2.
Tips
ellipticE returns floating-point results for numeric arguments that are not
symbolic objects.
For most symbolic (exact) numbers, ellipticE returns unresolved symbolic calls.
You can approximate such results with floating-point numbers using vpa.
If m is a vector or a matrix, then ellipticE(m) returns the complete elliptic integral
of the second kind, evaluated for each element of m.
At least one input argument must be a scalar or both arguments must be vectors or
matrices of the same size. If one input argument is a scalar and the other one is a
vector or a matrix, then ellipticE expands the scalar into a vector or matrix of the
same size as the other argument with all elements equal to that scalar.
ellipticE(pi/2, m) = ellipticE(m).
References
[1] Milne-Thomson, L. M. Elliptic Integrals. Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun,
eds.). New York: Dover, 1972.
4-379
4 Functions Alphabetical List
See Also
ellipke | ellipticCE | ellipticCK | ellipticCPi | ellipticF | ellipticK |
ellipticPi | vpa
Introduced in R2013a
4-380
ellipticF
ellipticF
Incomplete elliptic integral of the first kind
Description
ellipticF(phi,m) returns the incomplete elliptic integral of the first kind.
Input Arguments
m
phi
Examples
s =
0.6184 0.6486 0.8964 1.5708
4-381
4 Functions Alphabetical List
Compute the incomplete elliptic integrals of the first kind for the same numbers
converted to symbolic objects. For most symbolic (exact) numbers, ellipticF returns
unresolved symbolic calls.
s =
[ ellipticF(pi/3, -21/2), ellipticF(pi/4, -pi), ellipticF(1, -1), pi/6]
vpa(s, 10)
ans =
[ 0.6184459461, 0.6485970495, 0.8963937895, 0.5235987756]
syms m
diff(ellipticF(pi/4, m))
ans =
1/(4*(1 - m/2)^(1/2)*(m - 1)) - ellipticF(pi/4, m)/(2*m) -...
ellipticE(pi/4, m)/(2*m*(m - 1))
syms m
fplot([ellipticF(pi/4, m) ellipticF(pi/3, m) ellipticK(m)])
grid on
4-382
ellipticF
More About
Incomplete Elliptic Integral of the First Kind
j
1
F (j | m ) = dq
0 1 - m sin2 q
Note that some definitions use the elliptical modulus k or the modular angle instead of
the parameter m. They are related as m=k2=sin2.
4-383
4 Functions Alphabetical List
Tips
ellipticF returns floating-point results for numeric arguments that are not
symbolic objects.
For most symbolic (exact) numbers, ellipticF returns unresolved symbolic calls.
You can approximate such results with floating-point numbers using vpa.
At least one input argument must be a scalar or both arguments must be vectors or
matrices of the same size. If one input argument is a scalar and the other one is a
vector or a matrix, ellipticF expands the scalar into a vector or matrix of the same
size as the other argument with all elements equal to that scalar.
ellipticF(pi/2, m) = ellipticK(m).
References
[1] Milne-Thomson, L. M. Elliptic Integrals. Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun,
eds.). New York: Dover, 1972.
See Also
ellipke | ellipticCE | ellipticCK | ellipticCPi | ellipticE | ellipticK |
ellipticPi | vpa
Introduced in R2013a
4-384
ellipticK
ellipticK
Complete elliptic integral of the first kind
Syntax
ellipticK(m)
Description
ellipticK(m) returns the complete elliptic integral of the first kind.
Input Arguments
m
Number, symbolic number, variable, expression, or function. This argument also can be a
vector or matrix of numbers, symbolic numbers, variables, expressions, or functions.
Examples
Find Complete Elliptic Integrals of First Kind
Compute the complete elliptic integrals of the first kind for these numbers. Because these
numbers are not symbolic objects, you get floating-point results.
s = [ellipticK(1/2), ellipticK(pi/4), ellipticK(1), ellipticK(-5.5)]
s =
1.8541 2.2253 Inf 0.9325
Compute the complete elliptic integrals of the first kind for the same numbers converted
to symbolic objects. For most symbolic (exact) numbers, ellipticK returns unresolved
symbolic calls.
s = [ellipticK(sym(1/2)), ellipticK(sym(pi/4)),...
4-385
4 Functions Alphabetical List
ellipticK(sym(1)), ellipticK(sym(-5.5))]
s =
[ ellipticK(1/2), ellipticK(pi/4), Inf, ellipticK(-11/2)]
ans =
[ 1.854074677, 2.225253684, Inf, 0.9324665884]
ans =
- ellipticK(m)/(2*m) - ellipticE(m)/(2*m*(m - 1))
ans =
(2*ellipticE(m^2))/(m^2 - 1)^2 - (2*(ellipticE(m^2)/(2*m^2) -...
ellipticK(m^2)/(2*m^2)))/(m^2 - 1) + ellipticK(m^2)/m^2 +...
(ellipticK(m^2)/m + ellipticE(m^2)/(m*(m^2 - 1)))/m +...
ellipticE(m^2)/(m^2*(m^2 - 1))
ans =
[ ellipticK(-2*pi), ellipticK(-4)]
[ pi/2, Inf]
4-386
ellipticK
syms m
fplot(ellipticK(m))
title('Complete elliptic integral of the first kind')
ylabel('ellipticK(m)')
grid on
Alternatives
You can use ellipke to compute elliptic integrals of the first and second kinds in one
function call.
4-387
4 Functions Alphabetical List
More About
Complete Elliptic Integral of the First Kind
p 2
p 1
K (m ) = F | m = dq
2 1 - m sin2 q
0
Note that some definitions use the elliptical modulus k or the modular angle instead of
the parameter m. They are related as m=k2=sin2.
Tips
ellipticK returns floating-point results for numeric arguments that are not
symbolic objects.
For most symbolic (exact) numbers, ellipticK returns unresolved symbolic calls.
You can approximate such results with floating-point numbers using vpa.
If m is a vector or a matrix, then ellipticK(m) returns the complete elliptic integral
of the first kind, evaluated for each element of m.
References
[1] Milne-Thomson, L. M. Elliptic Integrals. Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun,
eds.). New York: Dover, 1972.
See Also
ellipke | ellipticCE | ellipticCK | ellipticCPi | ellipticE | ellipticF |
ellipticPi | vpa
Introduced in R2013a
4-388
ellipticPi
ellipticPi
Complete and incomplete elliptic integrals of the third kind
Syntax
ellipticPi(n,m)
ellipticPi(n,phi,m)
Description
ellipticPi(n,m) returns the complete elliptic integral of the third kind.
Input Arguments
n
phi
4-389
4 Functions Alphabetical List
Examples
Compute the incomplete elliptic integrals of the third kind for these numbers. Because
these numbers are not symbolic objects, you get floating-point results.
s = [ellipticPi(-2.3, pi/4, 0), ellipticPi(1/3, pi/3, 1/2),...
ellipticPi(-1, 0, 1), ellipticPi(2, pi/6, 2)]
s =
0.5877 1.2850 0 0.7507
Compute the incomplete elliptic integrals of the third kind for the same numbers
converted to symbolic objects. For most symbolic (exact) numbers, ellipticPi returns
unresolved symbolic calls.
s = [ellipticPi(-2.3, sym(pi/4), 0), ellipticPi(sym(1/3), pi/3, 1/2),...
ellipticPi(-1, sym(0), 1), ellipticPi(2, pi/6, sym(2))]
s =
[ ellipticPi(-23/10, pi/4, 0), ellipticPi(1/3, pi/3, 1/2),...
0, (2^(1/2)*3^(1/2))/2 - ellipticE(pi/6, 2)]
Here, ellipticE represents the incomplete elliptic integral of the second kind.
ans =
[ 0.5876852228, 1.285032276, 0, 0.7507322117]
Differentiate these expressions involving the complete elliptic integral of the third kind:
syms n m
diff(ellipticPi(n, m), n)
diff(ellipticPi(n, m), m)
ans =
ellipticK(m)/(2*n*(n - 1)) + ellipticE(m)/(2*(m - n)*(n - 1)) -...
(ellipticPi(n, m)*(- n^2 + m))/(2*n*(m - n)*(n - 1))
ans =
- ellipticPi(n, m)/(2*(m - n)) - ellipticE(m)/(2*(m - n)*(m - 1))
Here, ellipticK and ellipticE represent the complete elliptic integrals of the first
and second kinds.
4-390
ellipticPi
Call ellipticPi for the scalar and the matrix. When one input argument is a matrix,
ellipticPi expands the scalar argument to a matrix of the same size with all its
elements equal to the scalar.
ellipticPi(sym(0), sym([1/3 1; 1/2 0]))
ans =
[ ellipticK(1/3), Inf]
[ ellipticK(1/2), pi/2]
Here, ellipticK represents the complete elliptic integral of the first kind.
More About
Incomplete Elliptic Integral of the Third Kind
j
1
P ( n;j | m ) = ( dq
0 1 - n sin 2 q ) 1 - m sin 2 q
Note that some definitions use the elliptical modulus k or the modular angle instead of
the parameter m. They are related as m=k2=sin2.
p 2
p 1
P ( n, m) = P n; | m = dq
0 ( 1 - n sin q )
2 2
1 - m sin 2 q
Note that some definitions use the elliptical modulus k or the modular angle instead of
the parameter m. They are related as m=k2=sin2.
Tips
ellipticPi returns floating-point results for numeric arguments that are not
symbolic objects.
4-391
4 Functions Alphabetical List
For most symbolic (exact) numbers, ellipticPi returns unresolved symbolic calls.
You can approximate such results with floating-point numbers using vpa.
All non-scalar arguments must have the same size. If one or two input arguments are
non-scalar, then ellipticPi expands the scalars into vectors or matrices of the same
size as the non-scalar arguments, with all elements equal to the corresponding scalar.
ellipticPi(n, pi/2, m) = ellipticPi(n, m).
References
[1] Milne-Thomson, L. M. Elliptic Integrals. Handbook of Mathematical Functions with
Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun,
eds.). New York: Dover, 1972.
See Also
ellipke | ellipticCE | ellipticCK | ellipticCPi | ellipticE | ellipticF |
ellipticK | vpa
Introduced in R2013a
4-392
eq
eq
Define equation
Compatibility
In previous releases, eq in some cases evaluated equations involving only symbolic
numbers and returned logical 1 or 0. To obtain the same results as in previous releases,
wrap equations in isAlways. For example, use isAlways(A == B).
Syntax
A == B
eq(A,B)
Description
A == B creates a symbolic equation. You can use that equation as an argument for such
functions as solve, assume, ezplot, and subs.
eq(A,B) is equivalent to A == B.
Input Arguments
A
4-393
4 Functions Alphabetical List
Examples
syms x
solve(sin(x) == cos(x), x)
ans =
pi/4
syms x y
fimplicit(sin(x^2) == sin(y^2))
4-394
eq
ans =
logical
1
isAlways(sin(x)/cos(x) == tan(x))
ans =
4-395
4 Functions Alphabetical List
logical
1
ans =
33 logical array
1 1 0
1 0 1
1 0 1
If you compare a matrix and a scalar, then == expands the scalar into a matrix of the
same dimensions as the input matrix.
A = sym(hilb(3));
B = sym(1/2);
isAlways(A == B)
ans =
33 logical array
0 1 0
1 0 0
0 0 0
More About
Tips
If both A and B are arrays, then these arrays must have the same dimensions. A == B
returns an array of equations A(i,j,...) == B(i,j,...)
If one input is scalar and the other is an array, then == expands the scalar into an
array of the same dimensions as the input array. In other words, if A is a variable
4-396
eq
(for example, x), and B is an m-by-n matrix, then A is expanded into m-by-n matrix of
elements, each set to x.
See Also
ge | gt | isAlways | le | lt | ne | solve
Introduced in R2012a
4-397
4 Functions Alphabetical List
equationsToMatrix
Convert set of linear equations to matrix form
Syntax
[A,b] = equationsToMatrix(eqns,vars)
[A,b] = equationsToMatrix(eqns)
A = equationsToMatrix(eqns,vars)
A = equationsToMatrix(eqns)
Description
[A,b] = equationsToMatrix(eqns,vars) converts eqns to the matrix form. Here
eqns must be linear equations in vars.
Input Arguments
eqns
4-398
equationsToMatrix
vars
Independent variables of eqns. You can specify vars as a vector. Alternatively, you can
list variables separating them by commas.
Output Arguments
A
Examples
Convert this system of linear equations to the matrix form. To get the coefficient matrix
and the vector of the right sides of equations, assign the result to a vector of two output
arguments:
syms x y z
[A, b] = equationsToMatrix([x + y - 2*z == 0, x + y + z == 1,...
2*y - z + 5 == 0], [x, y, z])
A =
[ 1, 1, -2]
[ 1, 1, 1]
[ 0, 2, -1]
b =
0
1
-5
Convert this system of linear equations to the matrix form. Assigning the result of the
equationsToMatrix call to a single output argument, you get the coefficient matrix. In
this case, equationsToMatrix does not return the vector containing the right sides of
equations:
4-399
4 Functions Alphabetical List
syms x y z
A = equationsToMatrix([x + y - 2*z == 0, x + y + z == 1,...
2*y - z + 5 == 0], [x, y, z])
A =
[ 1, 1, -2]
[ 1, 1, 1]
[ 0, 2, -1]
Convert this linear system of equations to the matrix form without specifying
independent variables. The toolbox uses symvar to identify variables:
syms s t
[A, b] = equationsToMatrix([s - 2*t + 1 == 0, 3*s - t == 10])
A =
[ 1, -2]
[ 3, -1]
b =
-1
10
X =
[ s, t]
X = X.'
X =
s
t
A*X == b
ans =
s - 2*t == -1
3*s - t == 10
4-400
equationsToMatrix
If the system is only linear in some variables, specify those variables explicitly:
syms a s t
[A, b] = equationsToMatrix([s - 2*t + a == 0, 3*s - a*t == 10], [t, s])
A =
[ -2, 1]
[ -a, 3]
b =
-a
10
You also can specify equations and variables all together, without using vectors and
simply separating each equation or variable by a comma. Specify all equations first, and
then specify variables:
syms x y
[A, b] = equationsToMatrix(x + y == 1, x - y + 1, x, y)
A =
[ 1, 1]
[ 1, -1]
b =
1
-1
A =
1
0
-1
b =
1 - x
-x
- x - 1
4-401
4 Functions Alphabetical List
More About
Matrix Representation of a System of Linear Equations
a11 a1n
A= M O M
a
m1 L amn
b
r 1
b= M
b
m
Tips
If you specify equations and variables all together, without dividing them into two
vectors, specify all equations first, and then specify variables. If input arguments are
4-402
equationsToMatrix
not vectors, equationsToMatrix searches for variables starting from the last input
argument. When it finds the first argument that is not a single variable, it assumes
that all remaining arguments are equations, and therefore stops looking for variables.
See Also
linsolve | odeToVectorField | solve | symvar
Introduced in R2012b
4-403
4 Functions Alphabetical List
erf
Error function
Syntax
erf(X)
Description
erf(X) represents the error function of X. If X is a vector or a matrix, erf(X) computes
the error function of each element of X.
Examples
Compute the error function for these numbers. Because these numbers are not symbolic
objects, you get the floating-point results:
A =
0.5205 0.9539 0.9545
Compute the error function for the same numbers converted to symbolic objects. For most
symbolic (exact) numbers, erf returns unresolved symbolic calls:
symA =
[ erf(1/2), erf(141/100), erf(2^(1/2))]
Use vpa to approximate symbolic results with the required number of digits:
4-404
erf
d = digits(10);
vpa(symA)
digits(d)
ans =
[ 0.5204998778, 0.9538524394, 0.9544997361]
syms x
f = sin(x) + x*exp(x);
erf(x)
erf(f)
ans =
erf(x)
ans =
erf(sin(x) + x*exp(x))
ans =
[ 0, 1]
[ erf(1/3), -1]
ans =
erf(1)
-Inf*1i
4-405
4 Functions Alphabetical List
Compute the error function for x = 0, x = , and x = . Use sym to convert 0 and
infinities to symbolic objects. The error function has special values for these parameters:
[erf(sym(0)), erf(sym(Inf)), erf(sym(-Inf))]
ans =
[ 0, 1, -1]
Compute the error function for complex infinities. Use sym to convert complex infinities
to symbolic objects:
[erf(sym(i*Inf)), erf(sym(-i*Inf))]
ans =
[ Inf*1i, -Inf*1i]
ans =
(2*exp(-x^2))/pi^(1/2)
ans =
-(4*x*exp(-x^2))/pi^(1/2)
ans =
exp(-x^2)/pi^(1/2) + x*erf(x)
ans =
x*erf(log(x)) - int((2*exp(-log(x)^2))/pi^(1/2), x)
4-406
erf
Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
4-407
4 Functions Alphabetical List
More About
Error Function
x
2 -t 2
erf ( x) =
p
e dt
0
Tips
Calling erf for a number that is not a symbolic object invokes the MATLAB erf
function. This function accepts real arguments only. If you want to compute the error
function for a complex number, use sym to convert that number to a symbolic object,
and then call erf for that symbolic object.
For most symbolic (exact) numbers, erf returns unresolved symbolic calls. You can
approximate such results with floating-point numbers using vpa.
Algorithms
The toolbox can simplify expressions that contain error functions and their inverses. For
real values x, the toolbox applies these simplification rules:
erfcinv(x) = erfinv(1 - x)
erfinv(-x) = -erfinv(x)
erfcinv(2 - x) = -erfcinv(x)
erf(erfinv(x)) = erfc(erfcinv(x)) = x
4-408
erf
erf(erfcinv(x)) = erfc(erfinv(x)) = 1 - x
References
[1] Gautschi, W. Error Function and Fresnel Integrals. Handbook of Mathematical
Functions with Formulas, Graphs, and Mathematical Tables. (M. Abramowitz
and I. A. Stegun, eds.). New York: Dover, 1972.
See Also
erfc | erfcinv | erfi | erfinv
4-409
4 Functions Alphabetical List
erfc
Complementary error function
Syntax
erfc(X)
erfc(K,X)
Description
erfc(X) represents the complementary error function of X, that is,erfc(X) = 1 -
erf(X).
Examples
Compute the complementary error function for these numbers. Because these numbers
are not symbolic objects, you get the floating-point results:
A = [erfc(1/2), erfc(1.41), erfc(sqrt(2))]
A =
0.4795 0.0461 0.0455
Compute the complementary error function for the same numbers converted to symbolic
objects. For most symbolic (exact) numbers, erfc returns unresolved symbolic calls:
symA =
4-410
erfc
Use vpa to approximate symbolic results with the required number of digits:
d = digits(10);
vpa(symA)
digits(d)
ans =
[ 0.4795001222, 0.04614756064, 0.0455002639]
syms x
f = sin(x) + x*exp(x);
erfc(x)
erfc(f)
ans =
erfc(x)
ans =
erfc(sin(x) + x*exp(x))
Compute the complementary error function for elements of matrix M and vector V:
ans =
[ 1, 0]
[ erfc(1/3), 2]
4-411
4 Functions Alphabetical List
ans =
erfc(1)
1 + Inf*1i
Compute the iterated integral of the complementary error function for the elements of V
and M, and the integer -1:
erfc(-1, M)
erfc(-1, V)
ans =
[ 2/pi^(1/2), 0]
[ (2*exp(-1/9))/pi^(1/2), 0]
ans =
(2*exp(-1))/pi^(1/2)
Inf
ans =
1 0 2
Compute the complementary error function for complex infinities. Use sym to convert
complex infinities to symbolic objects:
[erfc(sym(i*Inf)), erfc(sym(-i*Inf))]
ans =
[ 1 - Inf*1i, 1 + Inf*1i]
4-412
erfc
Compute the first and second derivatives of the complementary error function:
syms x
diff(erfc(x), x)
diff(erfc(x), x, 2)
ans =
-(2*exp(-x^2))/pi^(1/2)
ans =
(4*x*exp(-x^2))/pi^(1/2)
syms x
int(erfc(-1, x), x)
ans =
erf(x)
int(erfc(x), x)
ans =
x*erfc(x) - exp(-x^2)/pi^(1/2)
int(erfc(2, x), x)
ans =
(x^3*erfc(x))/6 - exp(-x^2)/(6*pi^(1/2)) +...
(x*erfc(x))/4 - (x^2*exp(-x^2))/(6*pi^(1/2))
syms x
fplot(erfc(x),[-5,5])
grid on
4-413
4 Functions Alphabetical List
Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
4-414
erfc
Input representing an integer larger than -2, specified as a number, symbolic number,
variable, expression, or function. This arguments can also be a vector or matrix of
numbers, symbolic numbers, variables, expressions, or functions.
More About
Complementary Error Function
2 -t 2
erfc( x) = e dt = 1 - erf ( x)
p x
The following integral is the iterated integral of the complementary error function:
erfc ( k, x ) = erfc ( k - 1, y ) dy
x
Tips
Calling erfc for a number that is not a symbolic object invokes the MATLAB erfc
function. This function accepts real arguments only. If you want to compute the
complementary error function for a complex number, use sym to convert that number
to a symbolic object, and then call erfc for that symbolic object.
For most symbolic (exact) numbers, erfc returns unresolved symbolic calls. You can
approximate such results with floating-point numbers using vpa.
At least one input argument must be a scalar or both arguments must be vectors or
matrices of the same size. If one input argument is a scalar and the other one is a
vector or a matrix, then erfc expands the scalar into a vector or matrix of the same
size as the other argument with all elements equal to that scalar.
4-415
4 Functions Alphabetical List
Algorithms
The toolbox can simplify expressions that contain error functions and their inverses. For
real values x, the toolbox applies these simplification rules:
erfcinv(x) = erfinv(1 - x)
erfinv(-x) = -erfinv(x)
erfcinv(2 - x) = -erfcinv(x)
erf(erfinv(x)) = erfc(erfcinv(x)) = x
erf(erfcinv(x)) = erfc(erfinv(x)) = 1 - x
References
[1] Gautschi, W. Error Function and Fresnel Integrals. Handbook of Mathematical
Functions with Formulas, Graphs, and Mathematical Tables. (M. Abramowitz
and I. A. Stegun, eds.). New York: Dover, 1972.
See Also
erf | erfcinv | erfi | erfinv
Introduced in R2011b
4-416
erfcinv
erfcinv
Inverse complementary error function
Syntax
erfcinv(X)
Description
erfcinv(X) computes the inverse complementary error function of X. If X is a vector or a
matrix, erfcinv(X) computes the inverse complementary error function of each element
of X.
Examples
Compute the inverse complementary error function for these numbers. Because these
numbers are not symbolic objects, you get floating-point results:
A =
0.4769 -0.3013 -0.4769
Compute the inverse complementary error function for the same numbers converted
to symbolic objects. For most symbolic (exact) numbers, erfcinv returns unresolved
symbolic calls:
4-417
4 Functions Alphabetical List
symA =
[ -erfcinv(3/2), erfcinv(133/100), erfcinv(3/2)]
Use vpa to approximate symbolic results with the required number of digits:
d = digits(10);
vpa(symA)
digits(d)
ans =
[ 0.4769362762, -0.3013321461, -0.4769362762]
Compute the inverse complementary error function for complex numbers. Use sym to
convert complex numbers to symbolic objects:
ans =
[ erfcinv(2 + 3i), -erfcinv(1 + 1i)]
Compute the inverse complementary error function for x and sin(x) + x*exp(x). For
most symbolic variables and expressions, erfcinv returns unresolved symbolic calls:
syms x
f = sin(x) + x*exp(x);
erfcinv(x)
erfcinv(f)
ans =
erfcinv(x)
ans =
4-418
erfcinv
erfcinv(sin(x) + x*exp(x))
Compute the inverse complementary error function for elements of matrix M and vector V:
ans =
[ Inf, erfcinv(1 + 1i)]
[ -erfcinv(5/3), 0]
ans =
-Inf
-erfcinv(-Inf)
Compute the inverse complementary error function for x = 0, x = 1, and x = 2. The inverse
complementary error function has special values for these parameters:
ans =
Inf 0 -Inf
Compute the first and second derivatives of the inverse complementary error function:
syms x
4-419
4 Functions Alphabetical List
diff(erfcinv(x), x)
diff(erfcinv(x), x, 2)
ans =
-(pi^(1/2)*exp(erfcinv(x)^2))/2
ans =
(pi*exp(2*erfcinv(x)^2)*erfcinv(x))/2
int(erfcinv(x), x)
ans =
exp(-erfcinv(x)^2)/pi^(1/2)
syms x
fplot(erfcinv(x),[0,2])
grid on
4-420
erfcinv
Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
4-421
4 Functions Alphabetical List
More About
Inverse Complementary Error Function
2 -t 2
erfc( x) = e dt = 1 - erf ( x)
p x
Tips
Calling erfcinv for a number that is not a symbolic object invokes the MATLAB
erfcinv function. This function accepts real arguments only. If you want to compute
the inverse complementary error function for a complex number, use sym to convert
that number to a symbolic object, and then call erfcinv for that symbolic object.
If x<0 or x>2, the MATLAB erfcinv function returns NaN. The symbolic erfcinv
function returns unresolved symbolic calls for such numbers. To call the symbolic
erfcinv function, convert its argument to a symbolic object using sym.
Algorithms
The toolbox can simplify expressions that contain error functions and their inverses. For
real values x, the toolbox applies these simplification rules:
erfcinv(x) = erfinv(1 - x)
erfinv(-x) = -erfinv(x)
erfcinv(2 - x) = -erfcinv(x)
erf(erfinv(x)) = erfc(erfcinv(x)) = x
4-422
erfcinv
erf(erfcinv(x)) = erfc(erfinv(x)) = 1 - x
References
[1] Gautschi, W. Error Function and Fresnel Integrals. Handbook of Mathematical
Functions with Formulas, Graphs, and Mathematical Tables. (M. Abramowitz
and I. A. Stegun, eds.). New York: Dover, 1972.
See Also
erf | erfc | erfi | erfinv
Introduced in R2012a
4-423
4 Functions Alphabetical List
erfi
Imaginary error function
Syntax
erfi(x)
Description
erfi(x) returns the imaginary error function of x. If x is a vector or a matrix, erfi(x)
returns the imaginary error function of each element of x.
Examples
Imaginary Error Function for Floating-Point and Symbolic Numbers
Depending on its arguments, erfi can return floating-point or exact symbolic results.
Compute the imaginary error function for these numbers. Because these numbers are not
symbolic objects, you get floating-point results.
s = [erfi(1/2), erfi(1.41), erfi(sqrt(2))]
s =
0.6150 3.7382 3.7731
Compute the imaginary error function for the same numbers converted to symbolic
objects. For most symbolic (exact) numbers, erfi returns unresolved symbolic calls.
s = [erfi(sym(1/2)), erfi(sym(1.41)), erfi(sqrt(sym(2)))]
s =
[ erfi(1/2), erfi(141/100), erfi(2^(1/2))]
ans =
4-424
erfi
ans =
erfi(x)
ans =
erfi(sin(x) + x*exp(x))
Compute the imaginary error function for elements of matrix M and vector V:
M = sym([0 inf; 1/3 -inf]);
V = sym([1; -i*inf]);
erfi(M)
erfi(V)
ans =
[ 0, Inf]
[ erfi(1/3), -Inf]
ans =
erfi(1)
-1i
4-425
4 Functions Alphabetical List
ans =
[ 0, Inf, -Inf]
Compute the imaginary error function for complex infinities. Use sym to convert complex
infinities to symbolic objects:
[erfi(sym(i*inf)), erfi(sym(-i*inf))]
ans =
[ 1i, -1i]
Compute the first and second derivatives of the imaginary error function:
syms x
diff(erfi(x), x)
diff(erfi(x), x, 2)
ans =
(2*exp(x^2))/pi^(1/2)
ans =
(4*x*exp(x^2))/pi^(1/2)
int(erfi(x), x)
int(erfi(log(x)), x)
ans =
x*erfi(x) - exp(x^2)/pi^(1/2)
ans =
x*erfi(log(x)) - int((2*exp(log(x)^2))/pi^(1/2), x)
4-426
erfi
syms x
fplot(erfi(x),[-2,2])
grid on
Input Arguments
x Input
floating-point number | symbolic number | symbolic variable | symbolic expression |
symbolic function | symbolic vector | symbolic matrix
4-427
4 Functions Alphabetical List
More About
Imaginary Error Function
x
2 t2
erfi ( x ) = - i erf ( ix ) = e dt
p 0
Tips
erfi(0) = 0
erfi(inf) = inf
erfi(-inf) = -inf
erfi(i*inf) = i
erfi(-i*inf) = -i
See Also
erf | erfc | erfcinv | erfinv | vpa
Introduced in R2013a
4-428
erfinv
erfinv
Inverse error function
Syntax
erfinv(X)
Description
erfinv(X) computes the inverse error function of X. If X is a vector or a matrix,
erfinv(X) computes the inverse error function of each element of X.
Examples
Inverse Error Function for Floating-Point and Symbolic Numbers
Depending on its arguments, erfinv can return floating-point or exact symbolic results.
Compute the inverse error function for these numbers. Because these numbers are not
symbolic objects, you get floating-point results:
A = [erfinv(1/2), erfinv(0.33), erfinv(-1/3)]
A =
0.4769 0.3013 -0.3046
Compute the inverse error function for the same numbers converted to symbolic objects.
For most symbolic (exact) numbers, erfinv returns unresolved symbolic calls:
symA = [erfinv(sym(1)/2), erfinv(sym(0.33)), erfinv(sym(-1)/3)]
symA =
[ erfinv(1/2), erfinv(33/100), -erfinv(1/3)]
Use vpa to approximate symbolic results with the required number of digits:
d = digits(10);
vpa(symA)
digits(d)
4-429
4 Functions Alphabetical List
ans =
[ 0.4769362762, 0.3013321461, -0.3045701942]
Compute the inverse error function for complex numbers. Use sym to convert complex
numbers to symbolic objects:
[erfinv(sym(2 + 3*i)), erfinv(sym(1 - i))]
ans =
[ erfinv(2 + 3i), erfinv(1 - 1i)]
Compute the inverse error function for x and sin(x) + x*exp(x). For most symbolic
variables and expressions, erfinv returns unresolved symbolic calls:
syms x
f = sin(x) + x*exp(x);
erfinv(x)
erfinv(f)
ans =
erfinv(x)
ans =
erfinv(sin(x) + x*exp(x))
Compute the inverse error function for elements of matrix M and vector V:
M = sym([0 1 + i; 1/3 1]);
V = sym([-1; inf]);
4-430
erfinv
erfinv(M)
erfinv(V)
ans =
[ 0, erfinv(1 + 1i)]
[ erfinv(1/3), Inf]
ans =
-Inf
erfinv(Inf)
Compute the inverse error function for x = 1, x = 0, and x = 1. The inverse error function
has special values for these parameters:
[erfinv(-1), erfinv(0), erfinv(1)]
ans =
-Inf 0 Inf
Compute the first and second derivatives of the inverse error function:
syms x
diff(erfinv(x), x)
diff(erfinv(x), x, 2)
ans =
(pi^(1/2)*exp(erfinv(x)^2))/2
ans =
(pi*exp(2*erfinv(x)^2)*erfinv(x))/2
ans =
-exp(-erfinv(x)^2)/pi^(1/2)
4-431
4 Functions Alphabetical List
Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
4-432
erfinv
More About
Inverse Error Function
x
2 -t 2
erf ( x) =
p
e dt
0
Tips
Calling erfinv for a number that is not a symbolic object invokes the MATLAB
erfinv function. This function accepts real arguments only. If you want to compute
the inverse error function for a complex number, use sym to convert that number to a
symbolic object, and then call erfinv for that symbolic object.
If x<1 or x>1, the MATLAB erfinv function returns NaN. The symbolic erfinv
function returns unresolved symbolic calls for such numbers. To call the symbolic
erfinv function, convert its argument to a symbolic object using sym.
Algorithms
The toolbox can simplify expressions that contain error functions and their inverses. For
real values x, the toolbox applies these simplification rules:
erfcinv(x) = erfinv(1 - x)
4-433
4 Functions Alphabetical List
erfinv(-x) = -erfinv(x)
erfcinv(2 - x) = -erfcinv(x)
erf(erfinv(x)) = erfc(erfcinv(x)) = x
erf(erfcinv(x)) = erfc(erfinv(x)) = 1 - x
References
[1] Gautschi, W. Error Function and Fresnel Integrals. Handbook of Mathematical
Functions with Formulas, Graphs, and Mathematical Tables. (M. Abramowitz
and I. A. Stegun, eds.). New York: Dover, 1972.
See Also
erf | erfc | erfcinv | erfi
Introduced in R2012a
4-434
euler
euler
Euler numbers and polynomials
Syntax
euler(n)
euler(n,x)
Description
euler(n) returns the nth Euler number.
Examples
Compute the even-indexed Euler numbers with the indices from 0 to 10:
euler(0:2:10)
ans =
1 -1 5 -61...
1385 -50521
Compute the odd-indexed Euler numbers with the indices from 1 to 11:
euler(1:2:11)
ans =
0 0 0 0 0 0
4-435
4 Functions Alphabetical List
Euler Polynomials
For the Euler polynomials, use euler with two input arguments.
Compute the first, second, and third Euler polynomials in variables x, y, and z,
respectively:
syms x y z
euler(1, x)
euler(2, y)
euler(3, z)
ans =
x - 1/2
ans =
y^2 - y
ans =
z^3 - (3*z^2)/2 + 1/4
If the second argument is a number, euler evaluates the polynomial at that number.
Here, the result is a floating-point number because the input arguments are not symbolic
numbers:
euler(2, 1/3)
ans =
-0.2222
To get the exact symbolic result, convert at least one number to a symbolic object:
euler(2, sym(1/3))
ans =
-2/9
4-436
euler
grid on
syms n x
diff(euler(n,x^2), x)
ans =
2*n*x*euler(n - 1, x^2)
4-437
4 Functions Alphabetical List
diff(euler(n,x^2), x, x)
ans =
2*n*euler(n - 1, x^2) + 4*n*x^2*euler(n - 2, x^2)*(n - 1)
ans =
2*(1 - x)^n - (-1)^n*euler(n, x)
expand(euler(n, 2*x))
ans =
(2*2^n*bernoulli(n + 1, x + 1/2))/(n + 1) -...
(2*2^n*bernoulli(n + 1, x))/(n + 1)
Input Arguments
n Index of the Euler number or polynomial
nonnegative integer | symbolic nonnegative integer | symbolic variable | symbolic
expression | symbolic function | symbolic vector | symbolic matrix
x Polynomial variable
symbolic variable | symbolic expression | symbolic function | symbolic vector | symbolic
matrix
4-438
euler
More About
Euler Polynomials
2 ext tn
et + 1
= euler (n, x ) n !
n =0
Euler Numbers
1
euler ( n ) = 2n euler n,
2
Tips
For the other meaning of Eulers number, e=2.71828, call exp(1) to return the
double-precision representation. For the exact representation of Eulers number e, call
exp(sym(1)).
For the Euler-Mascheroni constant, see eulergamma.
See Also
bernoulli | eulergamma
Introduced in R2014a
4-439
4 Functions Alphabetical List
eulergamma
Euler-Mascheroni constant
Syntax
eulergamma
Description
eulergamma represents the Euler-Mascheroni constant. To get a floating-point
approximation with the current precision set by digits, use vpa(eulergamma).
Examples
Represent and Numerically Approximate the Euler-Mascheroni Constant
Represent the Euler-Mascheroni constant using eulergamma, which returns the
symbolic form eulergamma.
eulergamma
ans =
eulergamma
g =
log(eulergamma) + eulergamma^2
gVpa =
-0.21636138917392614801928563244766
4-440
eulergamma
double(eulergamma)
ans =
0.5772
Show that g = -Y (1 ) .
-psi(sym(1))
ans =
eulergamma
Show that g = -G ( x) x =1 .
syms x
-subs(diff(gamma(x)),x,1)
ans =
eulergamma
More About
Euler-Mascheroni Constant
n 1
g = lim - ln ( n )
n k
k=1
Tips
For the value e=2.71828, called Eulers number, use exp(1) to return the double-
precision representation. For the exact representation of Eulers number e, call
exp(sym(1)).
4-441
4 Functions Alphabetical List
For the other meaning of Eulers numbers and for Eulers polynomials, see euler.
See Also
coshint | euler
Introduced in R2014a
4-442
evalin
evalin
Evaluate MuPAD expressions without specifying their arguments
Syntax
result = evalin(symengine,MuPAD_expression)
[result,status] = evalin(symengine,MuPAD_expression)
Description
result = evalin(symengine,MuPAD_expression) evaluates the MuPAD
expression MuPAD_expression, and returns result as a symbolic object. If
MuPAD_expression throws an error in MuPAD, then this syntax throws an error in
MATLAB.
Input Arguments
MuPAD_expression
Output Arguments
result
status
Integer indicating the error status. If MuPAD_expression executes without errors, the
error status is 0.
4-443
4 Functions Alphabetical List
Examples
Compute the discriminant of the following polynomial:
evalin(symengine,'polylib::discrim(a*x^2+b*x+c,x)')
ans =
b^2 - 4*a*c
result =
139 char array
An arithmetical expression is expected.
status =
2
Alternatives
feval lets you evaluate MuPAD expressions with arguments. When using feval, you
must explicitly specify the arguments of the MuPAD expression.
More About
Tips
Results returned by evalin can differ from the results that you get using a MuPAD
notebook directly. The reason is that evalin sets a lower level of evaluation to
achieve better performance.
evalin does not open a MuPAD notebook, and therefore, you cannot use this function
to access MuPAD graphics capabilities.
4-444
evalin
See Also
feval | read | symengine
Introduced in R2008b
4-445
4 Functions Alphabetical List
evaluateMuPADNotebook
Evaluate MuPAD notebook
Syntax
evaluateMuPADNotebook(nb)
evaluateMuPADNotebook(nb,'IgnoreErrors',true)
Description
evaluateMuPADNotebook(nb) evaluates the MuPAD notebook with the handle nb and
returns logical 1 (true) if evaluation runs without errors. If nb is a vector of notebook
handles, then this syntax returns a vector of logical 1s.
Examples
Evaluate Particular Notebook
Execute commands in all input regions of a MuPAD notebook. Results of the evaluation
appear in the output regions of the notebook.
Suppose that your current folder contains a MuPAD notebook named myFile1.mn. Open
this notebook keeping its handle in the variable nb1:
nb1 = mupad('myFile1.mn');
4-446
evaluateMuPADNotebook
Evaluate all input regions in this notebook. If all calculations run without an error, then
evaluateMuPADNotebook returns logical 1 (true):
evaluateMuPADNotebook(nb1)
ans =
1
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
ans =
1
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')
4-447
4 Functions Alphabetical List
nb2 = mupad('myFile2.mn')
nb3 = mupad
nb1 =
myFile1
nb2 =
myFile2
nb3 =
Notebook1
ans =
1
1
1
Identify and evaluate all open MuPAD notebooks skipping evaluations that cause errors.
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-448
evaluateMuPADNotebook
Evaluate all notebooks using 'IgnoreErrors',true to skip any calculations that cause
errors. If all calculations run without an error, then evaluateMuPADNotebook returns
an array of logical 1s (true):
evaluateMuPADNotebook(allNBs,'IgnoreErrors',true)
ans =
1
1
1
Input Arguments
nb Pointer to MuPAD notebook
handle to notebook | vector of handles to notebooks
You can get the list of all open notebooks using the allMuPADNotebooks
function. evaluateMuPADNotebook accepts a vector of handles returned by
allMuPADNotebooks.
4-449
4 Functions Alphabetical List
See Also
allMuPADNotebooks | close | getVar | mupad | mupadNotebookTitle | openmn |
setVar
Introduced in R2013b
4-450
expand
expand
Symbolic expansion of polynomials and elementary functions
Syntax
expand(S)
expand(S,Name,Value)
Description
expand(S) expands the symbolic expression S. expand is often used with polynomials.
It also expands trigonometric, exponential, and logarithmic functions.
Input Arguments
S
'ArithmeticOnly'
If the value is true, expand the arithmetic part of an expression without expanding
trigonometric, hyperbolic, logarithmic, and special functions. This option does not
prevent expansion of powers and roots.
Default: false
4-451
4 Functions Alphabetical List
'IgnoreAnalyticConstraints'
Default: false
Examples
Expand the expression:
syms x
expand((x - 2)*(x - 4))
ans =
x^2 - 6*x + 8
syms x y
expand(cos(x + y))
ans =
cos(x)*cos(y) - sin(x)*sin(y)
syms a b
expand(exp((a + b)^2))
ans =
exp(a^2)*exp(b^2)*exp(2*a*b)
syms t
expand([sin(2*t), cos(2*t)])
ans =
[ 2*cos(t)*sin(t), 2*cos(t)^2 - 1]
4-452
expand
syms x
expand((sin(3*x) - 1)^2)
ans =
2*sin(x) + sin(x)^2 - 8*cos(x)^2*sin(x) - 8*cos(x)^2*sin(x)^2...
+ 16*cos(x)^4*sin(x)^2 + 1
ans =
sin(3*x)^2 - 2*sin(3*x) + 1
Expand this logarithm. By default, the expand function does not expand logarithms
because expanding logarithms is not valid for generic complex values:
syms a b c
expand(log((a*b/c)^2))
ans =
log((a^2*b^2)/c^2)
To apply the simplification rules that let the expand function expand logarithms, use
IgnoreAnalyticConstraints:
ans =
2*log(a) + 2*log(b) - 2*log(c)
More About
Algorithms
log(a) + log(b)=log(ab) for all values of a and b. In particular, the following equality
is valid for all values of a, b, and c:
4-453
4 Functions Alphabetical List
(ab)c=acbc.
log(ab)=blog(a) for all values of a and b. In particular, the following equality is valid
for all values of a, b, and c:
(ab)c=abc.
If f and g are standard mathematical functions and f(g(x))=x for all small positive
numbers, f(g(x))=x is assumed to be valid for all complex x. In particular:
log(ex)=x
asin(sin(x))=x, acos(cos(x))=x, atan(tan(x))=x
asinh(sinh(x))=x, acosh(cosh(x))=x, atanh(tanh(x))=x
Wk(xex)=x for all values of k
See Also
collect | combine | factor | horner | numden | rewrite | simplify |
simplifyFraction
4-454
expint
expint
Exponential integral function
Syntax
expint(x)
expint(n,x)
Description
expint(x) returns the one-argument exponential integral function defined as
-xt
e
expint ( x ) = dt.
t
1
-xt
e
expint ( n, x) = dt.
1 tn
Examples
s =
4-455
4 Functions Alphabetical List
Compute the exponential integrals for the same numbers converted to symbolic objects.
For positive values x, expint(x) returns -ei(-x). For negative values x, it returns -
pi*i - ei(-x).
s =
[ -ei(-1/3), -ei(-1), - pi*1i - ei(2)]
vpa(s, 10)
ans =
[ 0.8288877453, 0.2193839344, - 4.954234356 - 3.141592654i]
s =
[ expint(2, 1/3), 0, -exp(2)/4]
vpa(s, 25)
ans =
[ 0.4402353954575937050522018, 0, -1.847264024732662556807607]
syms x
4-456
expint
expint(0, x)
expint(-1, x)
expint(-2, x)
ans =
exp(-x)/x
ans =
exp(-x)*(1/x + 1/x^2)
ans =
exp(-x)*(1/x + 2/x^2 + 2/x^3)
syms x
diff(expint(x), x)
diff(expint(x), x, 2)
diff(expint(x), x, 3)
ans =
-exp(-x)/x
ans =
exp(-x)/x + exp(-x)/x^2
ans =
- exp(-x)/x - (2*exp(-x))/x^2 - (2*exp(-x))/x^3
syms n x
diff(expint(n, x), x)
diff(expint(n, x), n)
ans =
-expint(n - 1, x)
ans =
- hypergeom([1 - n, 1 - n], [2 - n, 2 - n],...
-x)/(n - 1)^2 - (x^(n - 1)*pi*(psi(n) - ...
log(x) + pi*cot(pi*n)))/(sin(pi*n)*gamma(n))
4-457
4 Functions Alphabetical List
Input Arguments
x Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
n Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
More About
Tips
Calling expint for numbers that are not symbolic objects invokes the MATLAB
expint function. This function accepts one argument only. To compute the two-
argument exponential integral, use sym to convert the numbers to symbolic objects,
and then call expint for those symbolic objects. You can approximate the results with
floating-point numbers using vpa.
The following values of the exponential integral differ from those returned by the
MATLAB expint function: expint(sym(Inf)) = 0, expint(-sym(Inf)) = -
Inf, expint(sym(NaN)) = NaN.
For positive x, expint(x) = -ei(-x). For negative x, expint(x) = -pi*i -
ei(-x).
If one input argument is a scalar and the other argument is a vector or a matrix, then
expint(n,x) expands the scalar into a vector or matrix of the same size as the other
argument with all elements equal to that scalar.
Algorithms
4-458
expint
Both functions ei(x) and expint(1,x) have a logarithmic singularity at the origin
and a branch cut along the negative real axis. The ei function is not continuous when
approached from above or below this branch cut.
The expint function is related to the upper incomplete gamma function igamma as
expint(n,x) = (x^(n-1))*igamma(1-n,x)
See Also
ei | expint | vpa
Introduced in R2013a
4-459
4 Functions Alphabetical List
expm
Matrix exponential
Syntax
R = expm(A)
Description
R = expm(A) computes the matrix exponential of the square matrix A.
Examples
Matrix Exponential
Compute the matrix exponential for the 2-by-2 matrix and simplify the result.
syms x
A = [0 x; -x 0];
simplify(expm(A))
ans =
[ cos(x), sin(x)]
[ -sin(x), cos(x)]
Input Arguments
A Input matrix
square matrix
4-460
expm
Output Arguments
R Resulting matrix
symbolic matrix
More About
Matrix Exponential
1 A2
eA = k! Ak = 1 + A + +
k= 0 2
See Also
eig | funm | jordan | logm | sqrtm
4-461
4 Functions Alphabetical List
ezcontour
Contour plotter
Compatibility
ezcontour is not recommended. Use fcontour instead.
Syntax
ezcontour(f)
ezcontour(f,domain)
ezcontour(...,n)
Description
ezcontour(f) plots the contour lines of f(x,y), where f is a symbolic expression that
represents a mathematical function of two variables, such as x and y.
The function f is plotted over the default domain 2<x<2, 2<y<2. MATLAB
software chooses the computational grid according to the amount of variation that occurs;
if the function f is not defined (singular) for points on the grid, then these points are not
plotted.
ezcontour(f,domain) plots f(x,y) over the specified domain. domain can be either a
4-by-1 vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where, min < x <
max, min < y < max).
If f is a function of the variables u and v (rather than x and y), then the domain endpoints
umin, umax, vmin, and vmax are sorted alphabetically. Thus, ezcontour(u^2 - v^3,
[0,1],[3,6]) plots the contour lines for u2 - v3 over 0 < u < 1, 3 < v < 6.
ezcontour(...,n) plots f over the default domain using an n-by-n grid. The default
value for n is 60.
4-462
ezcontour
Examples
2 2 x 2 2 1 2 2
f ( x, y) = 3(1 - x)2 e- x -( y+1) - 10 - x3 - y5 e- x - y - e-( x +1)) - y .
5 3
ezcontour requires a sym argument that expresses this function using MATLAB syntax
to represent exponents, natural logs, etc. This function is represented by the symbolic
expression
syms x y
f = 3*(1-x)^2*exp(-(x^2)-(y+1)^2)...
- 10*(x/5 - x^3 - y^5)*exp(-x^2-y^2)...
- 1/3*exp(-(x+1)^2 - y^2);
Pass the sym f to ezcontour along with a domain ranging from -3 to 3 and specify a
computational grid of 49-by-49.
ezcontour(f,[-3,3],49)
4-463
4 Functions Alphabetical List
In this particular case, the title is too long to fit at the top of the graph so MATLAB
abbreviates the title.
See Also
contour | fmesh | | fcontour | fplot | fplot3 | fsurf
4-464
ezcontourf
ezcontourf
Filled contour plotter
Compatibility
ezcontourf is not recommended. Use fcontour instead.
Syntax
ezcontourf(f)
ezcontourf(f,domain)
ezcontourf(...,n)
Description
ezcontourf(f) plots the contour lines of f(x,y), where f is a sym that represents a
mathematical function of two variables, such as x and y.
The function f is plotted over the default domain 2<x<2, 2<y<2. MATLAB
software chooses the computational grid according to the amount of variation that occurs;
if the function f is not defined (singular) for points on the grid, then these points are not
plotted.
ezcontourf(f,domain) plots f(x,y) over the specified domain. domain can be either a
4-by-1 vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where, min < x <
max, min < y < max).
If f is a function of the variables u and v (rather than x and y), then the domain endpoints
umin, umax, vmin, and vmax are sorted alphabetically. Thus, ezcontourf(u^2 - v^3,
[0,1],[3,6]) plots the contour lines for u2 - v3 over 0 < u < 1, 3 < v < 6.
ezcontourf(...,n) plots f over the default domain using an n-by-n grid. The default
value for n is 60.
4-465
4 Functions Alphabetical List
Examples
2 2 x 2 2 1 2 2
f ( x, y) = 3(1 - x)2 e- x -( y+1) - 10 - x3 - y5 e- x - y - e-( x +1)) - y .
5 3
ezcontourf requires a sym argument that expresses this function using MATLAB
syntax to represent exponents, natural logs, etc. This function is represented by the
symbolic expression
syms x y
f = 3*(1-x)^2*exp(-(x^2)-(y+1)^2)...
- 10*(x/5 - x^3 - y^5)*exp(-x^2-y^2)...
- 1/3*exp(-(x+1)^2 - y^2);
Pass the sym f to ezcontourf along with a domain ranging from -3 to 3 and specify a
grid of 49-by-49.
ezcontourf(f,[-3,3],49)
4-466
ezcontourf
In this particular case, the title is too long to fit at the top of the graph so MATLAB
abbreviates the title.
See Also
contourf | fmesh | fplot | fcontour | fplot3 | fsurf
4-467
4 Functions Alphabetical List
ezmesh
3-D mesh plotter
Compatibility
ezmesh is not recommended. Use fmesh instead.
Syntax
ezmesh(f)
ezmesh(f, domain)
ezmesh(x,y,z)
ezmesh(x,y,z,[smin,smax,tmin,tmax])
ezmesh(x,y,z,[min,max])
ezmesh(...,n)
ezmesh(...,'circ')
Description
ezmesh(f) creates a graph of f(x,y), where f is a symbolic expression that represents a
mathematical function of two variables, such as x and y.
The function f is plotted over the default domain 2<x<2, 2<y<2. MATLAB
software chooses the computational grid according to the amount of variation that occurs;
if the function f is not defined (singular) for points on the grid, then these points are not
plotted.
ezmesh(f, domain) plots f over the specified domain. domain can be either a 4-by-1
vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where, min < x < max,
min < y < max).
If f is a function of the variables u and v (rather than x and y), then the domain endpoints
umin, umax, vmin, and vmax are sorted alphabetically. Thus, ezmesh(u^2 - v^3,
[0,1],[3,6]) plots u2 - v3 over 0 < u < 1, 3 < v < 6.
4-468
ezmesh
ezmesh(x,y,z) plots the parametric surface x = x(s,t), y = y(s,t), and z = z(s,t) over the
square 2<s<2, 2<t<2.
ezmesh(...,n) plots f over the default domain using an n-by-n grid. The default value
for n is 60.
Examples
2 2
f ( x, y) = xe -x - y ,
with a mesh plot drawn on a 40-by-40 grid. The mesh lines are set to a uniform blue color
by setting the colormap to a single color.
syms x y
ezmesh(x*exp(-x^2-y^2),[-2.5,2.5],40)
colormap([0 0 1])
4-469
4 Functions Alphabetical List
See Also
fcontour | fsurf | mesh | fmesh | fplot | fplot3
4-470
ezmeshc
ezmeshc
Combined mesh and contour plotter
Compatibility
ezmeshc is not recommended. Use fmesh instead.
Syntax
ezmeshc(f)
ezmeshc(f,domain)
ezmeshc(x,y,z)
ezmeshc(x,y,z,[smin,smax,tmin,tmax])
ezmeshc(x,y,z,[min,max])
ezmeshc(...,n)
ezmeshc(...,'circ')
Description
ezmeshc(f) creates a graph of f(x,y), where f is a symbolic expression that represents a
mathematical function of two variables, such as x and y.
The function f is plotted over the default domain 2<x<2, 2<y<2. MATLAB
software chooses the computational grid according to the amount of variation that occurs;
if the function f is not defined (singular) for points on the grid, then these points are not
plotted.
ezmeshc(f,domain) plots f over the specified domain. domain can be either a 4-by-1
vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where, min < x < max,
min < y < max).
If f is a function of the variables u and v (rather than x and y), then the domain endpoints
umin, umax, vmin, and vmax are sorted alphabetically. Thus, ezmeshc(u^2 - v^3,
[0,1],[3,6]) plots u2v3 over 0 < u < 1, 3 < v < 6.
4-471
4 Functions Alphabetical List
ezmeshc(x,y,z) plots the parametric surface x = x(s,t), y = y(s,t), and z = z(s,t) over the
square 2<s<2, 2<t<2.
ezmeshc(...,n) plots f over the default domain using an n-by-n grid. The default value
for n is 60.
Examples
y
f ( x, y) = ,
1 + x + y2
2
over the domain 5 < x < 5, 2 < y < 2. Use the mouse to rotate the axes to better
observe the contour lines (this picture uses a view of azimuth = 65 and elevation = 26).
syms x y
ezmeshc(y/(1 + x^2 + y^2),[-5,5,-2*pi,2*pi])
4-472
ezmeshc
See Also
fcontour | fsurf | meshc | fmesh | fplot | fplot3
4-473
4 Functions Alphabetical List
ezplot
Plot symbolic expression, equation, or function
Compatibility
ezplot is not recommended. Use fplot instead. For implicit plots, use fimplicit.
Syntax
ezplot(f)
ezplot(f,[min,max])
ezplot(f,[xmin,xmax,ymin,ymax])
ezplot(x,y)
ezplot(x,y,[tmin,tmax])
ezplot(f,[min,max],fig)
ezplot(f,[xmin,xmax,ymin,ymax],fig)
ezplot(x,y,[tmin,tmax],fig)
h = ezplot( ___ )
Description
ezplot(f) plots a symbolic expression, equation, or function f. By default, ezplot
plots a univariate expression or function over the range [22] or over a subinterval
of this range. If f is an equation or function of two variables, the default range for both
variables is [22] or over a subinterval of this range.
4-474
ezplot
ezplot(x,y) plots the parametrically defined planar curve x=x(t) and y=y(t) over the
default range 0<=t<=2 or over a subinterval of this range.
ezplot(f,[min,max],fig) plots f over the specified range in the figure with the
figure number or figure handle fig. The title of each plot window contains the word
Figure and the number, for example, Figure 1, Figure 2, and so on. If fig is already
open, ezplot overwrites the content of that figure with the new plot.
h = ezplot( ___ ) returns the plot handle as either a chart line or contour object.
Input Arguments
f
[min,max]
Numbers specifying the plotting range. For a univariate expression or function, the
plotting range applies to that variable. For an equation or function of two variables,
the plotting range applies to both variables. In this case, the range is the same for the
abscissa and the ordinate.
[xmin,xmax,ymin,ymax]
Numbers specifying the plotting range along the abscissa (first two numbers) and the
ordinate (last two numbers).
4-475
4 Functions Alphabetical List
fig
Figure handle or number of the figure window where you want to display a plot.
Default: For figure handle, the current figure handle returned by gcf. For figure
number, if no plot windows are open, then 1. If one plot window is open, then the number
in the title of that window. If more than one plot window is open, then the highest
number in the titles of open windows.
x,y
[tmin,tmax]
Output Arguments
h Chart line or contour line object
scalar
Chart line or contour line object, returned as a scalar. For details, see Chart Line
Properties and Contour Properties.
Examples
syms x
ezplot(erf(x), [-pi, pi])
4-476
ezplot
syms x y
ezplot(x^2 == y^4)
4-477
4 Functions Alphabetical List
syms x y
f(x, y) = sin(x + y)*sin(x*y);
ezplot(f)
4-478
ezplot
syms t
x = t*sin(5*t);
y = t*cos(5*t);
ezplot(x, y)
4-479
4 Functions Alphabetical List
More About
Tips
If you do not specify a plot range, ezplot uses the interval [22] as a starting
point. Then it can choose to display a part of the plot over a subinterval of [22]
where the plot has significant variation. Also, when selecting the plotting range,
ezplot omits extreme values associated with singularities.
ezplot open a plot window and displays a plot there. If any plot windows are already
open, ezplot does not create a new window. Instead, it displays the new plot in the
currently active window. (Typically, it is the window with the highest number.) To
4-480
ezplot
display the new plot in a new plot window or in an existing window other than that
with highest number, use fig.
If f is an equation or function of two variables, then the alphabetically first variable
defines the abscissa (horizontal axis) and the other variable defines the ordinate
(vertical axis). Thus, ezplot(x^2 == a^2,[-3,3,-2,2]) creates the plot of the
equation x2=a2 with 3<=a<=3 along the horizontal axis, and 2<=x<=2 along
the vertical axis.
See Also
fcontour | fmesh | fplot | fplot3 | fsurf | plot
4-481
4 Functions Alphabetical List
ezplot3
3-D parametric curve plotter
Compatibility
ezplot3 is not recommended. Use fplot3 instead.
Syntax
ezplot3(x,y,z)
ezplot3(x,y,z,[tmin,tmax])
ezplot3(...,'animate')
Description
ezplot3(x,y,z) plots the spatial curve x = x(t), y = y(t), and z = z(t) over the default
domain 0<t<2.
ezplot3(x,y,z,[tmin,tmax]) plots the curve x = x(t), y = y(t), and z = z(t) over the
domain tmin < t < tmax.
Examples
syms t
ezplot3(sin(t), cos(t), t,[0,6*pi])
4-482
ezplot3
See Also
fcontour | fsurf | plot3 | fmesh | fplot | fplot3
4-483
4 Functions Alphabetical List
ezpolar
Polar coordinate plotter
Syntax
ezpolar(f)
ezpolar(f, [a, b])
Description
ezpolar(f) plots the polar curve r = f() over the default domain 0<<2.
Examples
syms t
ezpolar(1 + cos(t))
4-484
ezpolar
4-485
4 Functions Alphabetical List
ezsurf
Plot 3-D surface
Compatibility
ezsurf is not recommended. Use fsurf instead.
Syntax
ezsurf(f)
ezsurf(f,[xmin,xmax])
ezsurf(f,[xmin,xmax,ymin,ymax])
ezsurf(x,y,z)
ezsurf(x,y,z,[smin,smax])
ezsurf(x,y,z,[smin,smax,tmin,tmax])
h = ezsurf( ___ )
Description
ezsurf(f) plots a two-variable symbolic expression or function f(x,y) over the range
-2*pi < x < 2*pi, -2*pi < y < 2*pi.
ezsurf(f,[xmin,xmax]) plots f(x,y) over the specified range xmin < x < xmax.
This is the range along the abscissa (horizontal axis).
When determining the range values, ezsurf sorts variables alphabetically. For example,
ezsurf(x^2 - a^3, [0,1,3,6]) plots x^2 - a^3 over 0 < a < 1, 3 < x < 6.
4-486
ezsurf
ezsurf( ___ ,n) specifies the grid. You can specify n after the input arguments in any
of the previous syntaxes. By default, n = 60.
ezsurf( ___ ,'circ') creates the surface plot over a disk centered on the range. You
can specify'circ' after the input arguments in any of the previous syntaxes.
h = ezsurf( ___ ) returns a handle h to the surface plot object. You can use the output
argument h with any of the previous syntaxes.
Examples
Plot Function Over Default Range
Plot the symbolic function f(x,y) = real(atan(x + i*y)) over the default range
-2*pi < x < 2*pi, -2*pi < y < 2*pi.
syms f(x,y)
f(x,y) = real(atan(x + i*y));
ezsurf(f)
4-487
4 Functions Alphabetical List
Plot the symbolic expression x^2 + y^2 over the range -1 < x < 1. Because you do
not specify the range for the y-axis, ezsurf chooses it automatically.
syms x y
ezsurf(x^2 + y^2, [-1, 1])
4-488
ezsurf
4-489
4 Functions Alphabetical List
syms s t
r = 2 + sin(7*s + 5*t);
x = r*cos(s)*sin(t);
y = r*sin(s)*sin(t);
z = r*cos(t);
4-490
ezsurf
4-491
4 Functions Alphabetical List
First, plot the expression sin(x^2 + y^2) over the square range -pi/2 < x < pi/2,
-pi/2 < y < pi/2.
syms x y
ezsurf(sin(x^2 + y^2), [-pi/2, pi/2, -pi/2, pi/2])
4-492
ezsurf
4-493
4 Functions Alphabetical List
h =
EdgeColor: [0 0 0]
LineStyle: '-'
FaceColor: 'flat'
4-494
ezsurf
FaceLighting: 'flat'
FaceAlpha: 1
XData: [6060 double]
YData: [6060 double]
ZData: [6060 double]
CData: [6060 double]
You can use this handle to change properties of the plot. For example, change the color of
the area outline.
h.EdgeColor = 'red'
4-495
4 Functions Alphabetical List
h =
EdgeColor: [1 0 0]
LineStyle: '-'
FaceColor: 'flat'
FaceLighting: 'flat'
FaceAlpha: 1
XData: [6060 double]
YData: [6060 double]
ZData: [6060 double]
CData: [6060 double]
4-496
ezsurf
Input Arguments
f Function to plot
symbolic expression with two variables | symbolic function of two variables
4-497
4 Functions Alphabetical List
n Grid value
integer
Output Arguments
h Surface plot handle
scalar
Surface plot handle, returned as a scalar. It is a unique identifier, which you can use to
query and modify properties of the surface plot.
More About
Tips
ezsurf chooses the computational grid according to the amount of variation that
occurs. If f is singular for some points on the grid, then ezsurf omits these points.
The value at these points is set to NaN.
See Also
fcontour | fmesh | fplot | fplot3 | fsurf | surf
4-498
ezsurfc
ezsurfc
Combined surface and contour plotter
Compatibility
ezsurfc is not recommended. Use fsurf instead.
Syntax
ezsurfc(f)
ezsurfc(f,domain)
ezsurfc(x,y,z)
ezsurfc(x,y,z,[smin,smax,tmin,tmax])
ezsurfc(x,y,z,[min,max])
ezsurfc(...,n)
ezsurfc(...,'circ')
Description
ezsurfc(f) creates a graph of f(x,y), where f is a symbolic expression that represents a
mathematical function of two variables, such as x and y.
The function f is plotted over the default domain 2<x<2, 2<y<2. MATLAB
software chooses the computational grid according to the amount of variation that occurs;
if the function f is not defined (singular) for points on the grid, then these points are not
plotted.
ezsurfc(f,domain) plots f over the specified domain. domain can be either a 4-by-1
vector [xmin, xmax, ymin, ymax] or a 2-by-1 vector [min, max] (where, min < x < max,
min < y < max).
If f is a function of the variables u and v (rather than x and y), then the domain endpoints
umin, umax, vmin, and vmax are sorted alphabetically. Thus, ezsurfc(u^2 - v^3,
[0,1],[3,6]) plots u2v3 over 0<u<1, 3<v<6.
4-499
4 Functions Alphabetical List
ezsurfc(x,y,z) plots the parametric surface x = x(s,t), y = y(s,t), and z = z(s,t) over the
square 2<s<2, 2<t<2.
ezsurfc(...,n) plots f over the default domain using an n-by-n grid. The default value
for n is 60.
Examples
y
f ( x, y) = ,
1 + x + y2
2
over the domain 5 < x < 5, 2 < y < 2, with a computational grid of size 35-by-35. Use
the mouse to rotate the axes to better observe the contour lines (this picture uses a view
of azimuth = -65 and elevation = 26).
syms x y
ezsurfc(y/(1 + x^2 + y^2),[-5,5,-2*pi,2*pi],35)
4-500
ezsurfc
See Also
fcontour | fsurf | surfc | fmesh | fplot | fplot3
4-501
4 Functions Alphabetical List
factor
Factorization
Syntax
F = factor(x)
F = factor(x,vars)
F = factor( ___ ,Name,Value)
Description
F = factor(x) returns all irreducible factors of x in vector F. If x is an integer, factor
returns the prime factorization of x. If x is a symbolic expression, factor returns the
subexpressions that are factors of x.
Examples
F =
2 2 59 283 12329
To factor integers greater than flintmax, convert the integer to a symbolic object using
sym. Then place the number in quotation marks to represent it accurately.
4-502
factor
F = factor(sym('82342925225632328'))
F =
[ 2, 2, 2, 251, 401, 18311, 5584781]
F = factor(sym(-92465))
F =
[ -1, 5, 18493]
n = sym('41758540882408627201');
factor(n)
ans =
[ 479001599, 87178291199]
F = factor(sym(112/81))
F =
[ 2, 2, 2, 2, 7, 1/3, 1/3, 1/3, 1/3]
Factor Polynomials
Factor the polynomial x^6-1.
syms x
F = factor(x^6-1)
F =
[ x - 1, x + 1, x^2 + x + 1, x^2 - x + 1]
4-503
4 Functions Alphabetical List
syms y
F = factor(y^6-x^6)
F =
[ -1, x - y, x + y, x^2 + x*y + y^2, x^2 - x*y + y^2]
syms x y
F = factor(y^2*x^2,x)
F =
[ y^2, x, x]
factor combines all factors without x into the first element. The remaining elements of
F contain irreducible factors that contain x.
syms a b c d
y = -a*b^5*c*d*(a^2 - 1)*(a*d - b*c);
F = factor(y,[b c])
F =
[ -a*d*(a - 1)*(a + 1), b, b, b, b, b, c, a*d - b*c]
factor combines all factors without b or c into the first element of F. The remaining
elements of F contain irreducible factors of y that contain either b or c.
Factor an expression without specifying the factorization mode. By default, factor uses
factorization over rational numbers. In this mode, factor keeps rational numbers in
their exact symbolic form.
syms x
4-504
factor
factor(x^3 + 2, x)
ans =
x^3 + 2
Factor the same expression, but this time use numeric factorization over real numbers.
This mode factors the expression into linear and quadratic irreducible polynomials with
real coefficients and converts all numeric values to floating-point numbers.
ans =
[ x + 1.2599210498948731647672106072782,...
x^2 - 1.2599210498948731647672106072782*x + 1.5874010519681994747517056392723]
Factor this expression using factorization over complex numbers. In this mode, factor
reduces quadratic polynomials to linear expressions with complex coefficients. This mode
converts all numeric values to floating-point numbers.
ans =
[ x + 1.2599210498948731647672106072782,...
x - 0.62996052494743658238360530363911 + 1.0911236359717214035600726141898i,...
x - 0.62996052494743658238360530363911 - 1.0911236359717214035600726141898i]
Factor this expression using the full factorization mode. This mode factors the expression
into linear expressions, reducing quadratic polynomials to linear expressions with
complex coefficients. This mode keeps rational numbers in their exact symbolic form.
ans =
[ x + 2^(1/3),...
x - 2^(1/3)*((3^(1/2)*1i)/2 + 1/2),...
x + 2^(1/3)*((3^(1/2)*1i)/2 - 1/2)]
Approximate the result with floating-point numbers by using vpa. Because the
expression does not contain any symbolic parameters besides the variable x, the result is
the same as in complex factorization mode.
vpa(ans)
ans =
[ x + 1.2599210498948731647672106072782,...
4-505
4 Functions Alphabetical List
x - 0.62996052494743658238360530363911 - 1.0911236359717214035600726141898i,...
x - 0.62996052494743658238360530363911 + 1.0911236359717214035600726141898i]
syms x
s = factor(x^3 + x - 3, x, 'FactorMode','full')
s =
[ x - root(z^3 + z - 3, z, 1),...
x - root(z^3 + z - 3, z, 2),...
x - root(z^3 + z - 3, z, 3)]
vpa(s)
ans =
[ x - 1.2134116627622296341321313773815,...
x + 0.60670583138111481706606568869074 + 1.450612249188441526515442203395i,...
x + 0.60670583138111481706606568869074 - 1.450612249188441526515442203395i]
Input Arguments
x Input to factor
number | symbolic number | symbolic expression | symbolic function
4-506
factor
Output Arguments
F Factors of input
symbolic vector
4-507
4 Functions Alphabetical List
More About
Tips
To factor an integer greater than flintmax, wrap the integer with sym. Then
place the integer in quotation marks to represent it accurately, for example,
sym('465971235659856452').
To factor a negative integer, wrap the integer with sym, for example, sym(-3).
See Also
collect | combine | divisors | expand | horner | numden | rewrite | simplify
| simplifyFraction
4-508
factorial
factorial
Factorial function
Syntax
factorial(n)
factorial(A)
Description
factorial(n) returns the factorial of n.
Input Arguments
n
Examples
Compute the factorial function for these expressions:
syms n
f = factorial(n^2 + 1)
f =
factorial(n^2 + 1)
4-509
4 Functions Alphabetical List
subs(f, n, 3)
ans =
3628800
syms n
diff(factorial(n^2 + n + 1))
ans =
factorial(n^2 + n + 1)*psi(n^2 + n + 2)*(2*n + 1)
syms n
expand(factorial(n^2 + n + 1))
ans =
factorial(n^2 + n)*(n^2 + n + 1)
Compute the limit for the expression involving the factorial function:
syms n
limit(factorial(n)/exp(n), n, inf)
ans =
Inf
Call factorial for the matrix A. The result is a matrix of the factorial functions:
A = sym([1 2; 3 4]);
factorial(A)
ans =
[ 1, 2]
[ 6, 24]
More About
Factorial Function
4-510
factorial
n
n! = k
k=1
Tips
Calling factorial for a number that is not a symbolic object invokes the MATLAB
factorial function.
See Also
beta | gamma | nchoosek | psi
Introduced in R2012a
4-511
4 Functions Alphabetical List
fcontour
Plot contours
Syntax
fcontour(f)
fcontour(f,[min max])
fcontour(f,[xmin xmax ymin ymax])
Description
fcontour(f) plots the contour lines of symbolic expression f(x,y) over the default
interval of x and y, which is [-5 5].
fcontour(f,[min max]) plots f over the interval min < x < max and min < y < max.
fcontour(f,[xmin xmax ymin ymax]) plots f over the interval xmin < x < xmax and
ymin < y < ymax. fcontour uses symvar to order the variables and assign intervals.
fcontour( ___ ,LineSpec) uses LineSpec to set the line style and color. fcontour
doesnt support markers.
fcontour( ___ ,Name,Value) specifies line properties using one or more Name,Value
pair arguments. Use this option with any of the input argument combinations in the
previous syntaxes. Name,Value pair settings apply to all the lines plotted. To set options
for individual plots, use the objects returned by fcontour.
fcontour(ax, ___ ) plots into the axes object ax instead of the current axes object gca.
fc = fcontour( ___ ) returns a function contour object. Use the object to query and
modify properties of a specific contour plot. For details, see Function Contour Properties.
4-512
fcontour
Examples
syms x y
fcontour(sin(x) + cos(y))
colorbar
4-513
4 Functions Alphabetical List
syms f(x,y)
f(x,y) = sin(x) + cos(y);
fcontour(f)
4-514
fcontour
syms x y
f = sin(x) + cos(y);
fcontour(f,[-pi/2 pi/2 0 5])
4-515
4 Functions Alphabetical List
Plot the contours of as blue, dashed lines by specifying the LineSpec input.
Specify a LineWidth of 2. Markers are not supported by fcontour.
syms x y
fcontour(x^2 - y^2,'--b','LineWidth',2)
4-516
fcontour
Divide a figure into two subplots by using subplot. On the first subplot, plot
and by using vector input. On the second subplot, plot the same
expressions by using hold on.
syms x y
subplot(2,1,1)
4-517
4 Functions Alphabetical List
fcontour([sin(x)+cos(y) x-y])
title('Multiple Contour Plots Using Vector Inputs')
subplot(2,1,2)
fcontour(sin(x)+cos(y))
hold on
fcontour(x-y)
title('Multiple Contour Plots Using Hold Command')
hold off
4-518
fcontour
fc =
4-519
4 Functions Alphabetical List
Change the LineWidth to 1 and the LineStyle to a dashed line by using dot notation to
set properties of the object fc. Visualize contours close to 0 and 1 by setting LevelList
to [1 0.9 0.8 0.2 0.1].
4-520
fcontour
fc.LineStyle = '--';
fc.LineWidth = 1;
fc.LevelList = [1 0.9 0.8 0.2 0.1];
colorbar
4-521
4 Functions Alphabetical List
syms x y
f = erf((y+2)^3) - exp(-0.65*((x-2)^2+(y-2)^2));
fcontour(f,'Fill','on')
syms x y
f = sin(x) + cos(y);
4-522
fcontour
fcontour(f,'LevelList',[-1 0 1])
Divide a figure into two using subplot. In the first subplot, plot the contours of
. The corners of the squares do not meet. To fix this issue, increase
'MeshDensity' to 200 in the second subplot. The corners now meet, showing that by
increasing 'MeshDensity' you increase the plot's resolution.
4-523
4 Functions Alphabetical List
syms x y
subplot(2,1,1)
fcontour(sin(x).*sin(y))
title('Default MeshDensity = 71')
subplot(2,1,2)
fcontour(sin(x).*sin(y),'MeshDensity',200)
title('Increased MeshDensity = 200')
4-524
fcontour
Create x-axis labels by using arrayfun to apply texlabel to S. Display these labels by
using the XTickLabel property. Repeat these steps for the y-axis.
syms x y
fcontour(x*sin(y)-y*cos(x), [-2*pi 2*pi])
grid on
title('xsin(y)-ycos(x) for -2\pi < x < 2\pi and -2\pi < y < 2\pi')
xlabel('x')
ylabel('y')
ax = gca;
S = sym(ax.XLim(1):pi/2:ax.XLim(2));
ax.XTick = double(S);
ax.XTickLabel = arrayfun(@texlabel, S, 'UniformOutput', false);
S = sym(ax.YLim(1):pi/2:ax.YLim(2));
ax.YTick = double(S);
ax.YTickLabel = arrayfun(@texlabel, S, 'UniformOutput', false);
4-525
4 Functions Alphabetical List
Create Animations
Create animations by changing the displayed expression using the Function property
of the function handle, and then using drawnow to update the plot. To export to GIF, see
imwrite.
By varying the variable i from /8 to /8, animate the parametric curve isin(x) + icos(y).
syms x y
fc = fcontour(-pi/8.*sin(x)-pi/8.*cos(y));
for i=-pi/8:0.01:pi/8
fc.Function = i.*sin(x)+i.*cos(y);
drawnow
4-526
fcontour
pause(0.05)
end
Input Arguments
f Expression or function to be plotted
symbolic expression | symbolic function
4-527
4 Functions Alphabetical List
Plotting range for x and y, specified as a vector of two numbers. The default range is [-5
5].
Plotting range for x and y, specified as a vector of four numbers. The default range is [-5
5 -5 5].
ax Axes object
axes object
Axes object. If you do not specify an axes object, then the plot function uses the current
axes.
Line style and color, specified as a character vector containing a line style specifier, a
color specifier, or both.
Example: '--r' specifies red dashed lines
These two tables list the line style and color options.
4-528
fcontour
The properties listed here are only a subset. For a complete list, see Function Contour
Properties.
Number of evaluation points per direction, specified as a number. The default is 71.
Because fcontour uses adaptive evaluation, the actual number of evaluation points is
greater.
Example: 30
'off' Do not fill the spaces between contour lines with a color.
'on' Fill the spaces between contour lines with color.
4-529
4 Functions Alphabetical List
Spacing between contour lines, specified as a scalar numeric value. For example,
specify a value of 2 to draw contour lines at increments of 2. By default, LevelStep is
determined by using the ZData values.
4-530
fcontour
'flat' Use a different color for each contour line, determined by its contour value,
the colormap, and the scaling of data values into the colormap. For more information
on color scaling, see caxis.
'none' Do not draw the contour lines.
RGB triplet or character vector of a color name Use the same color for all contour
lines.
An RGB triplet is a three-element row vector whose elements specify the intensities of
the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. This table lists the long and short color name
options and the equivalent RGB triplet values.
Line style, specified as one of the line styles listed in this table.
4-531
4 Functions Alphabetical List
Line width, specified as a positive value in points. If the line has markers, then the line
width also affects the marker edges.
Example: 0.75
Output Arguments
fc One or more function contour objects
scalar | vector
One or more function contour objects, returned as a scalar or a vector. These objects are
unique identifiers, which you can use to query and modify the properties of a specific
contour plot. For details, see Function Contour Properties.
More About
Create Plots on page 2-208
See Also
Functions
fimplicit | fimplicit3 | fmesh | fplot | fplot3 | fsurf
Properties
Function Contour Properties
Introduced in R2016a
4-532
feval
feval
Evaluate MuPAD expressions specifying their arguments
Syntax
result = feval(symengine,F,x1,...,xn)
[result,status] = feval(symengine,F,x1,...,xn)
Description
result = feval(symengine,F,x1,...,xn) evaluates F, which is either a MuPAD
function name or a symbolic object, with arguments x1,...,xn. Here, the returned
value result is a symbolic object. If F with the arguments x1,...,xn throws an error
in MuPAD, then this syntax throws an error in MATLAB.
Input Arguments
F
x1,...,xn
Arguments of F.
Output Arguments
result
4-533
4 Functions Alphabetical List
status
Integer indicating the error status. If F with the arguments x1,...,xn executes without
errors, the error status is 0.
Examples
syms a b c x
p = a*x^2+b*x+c;
feval(symengine,'polylib::discrim', p, x)
ans =
b^2 - 4*a*c
Alternatively, the same calculation based on variables not defined in the MATLAB
workspace is:
ans =
b^2 - 4*a*c
result =
139 char array
An arithmetical expression is expected.
status =
2
Alternatives
evalin lets you evaluate MuPAD expressions without explicitly specifying their
arguments.
4-534
feval
More About
Tips
Results returned by feval can differ from the results that you get using a MuPAD
notebook directly. The reason is that feval sets a lower level of evaluation to achieve
better performance.
feval does not open a MuPAD notebook, and therefore, you cannot use this function
to access MuPAD graphics capabilities.
See Also
evalin | read | symengine
Introduced in R2008b
4-535
4 Functions Alphabetical List
fimplicit
Plot implicit symbolic equation or function
Syntax
fimplicit(f)
fimplicit(f,[min max])
fimplicit(f,[xmin xmax ymin ymax])
Description
fimplicit(f) plots the implicit symbolic equation or function f over the default
interval [-5 5] for x and y.
fimplicit(f,[min max]) plots f over the interval min < x < max and min < y < max.
fimplicit(f,[xmin xmax ymin ymax]) plots f over the interval xmin < x < xmax
and ymin < y < ymax. fimplicit uses symvar to order the variables and assign
intervals.
fimplicit( ___ ,LineSpec) uses LineSpec to set the line style, marker symbol, and
line color.
fimplicit(ax, ___ ) plots into the axes specified by ax instead of the current axes
gca.
4-536
fimplicit
fi = fimplicit( ___ ) returns an implicit function line object. Use the object to query
and modify properties of a specific line. For details, see Implicit Function Line Properties.
Examples
Plot Implicit Symbolic Equation
Plot the hyperbola by using fimplicit. The fimplicit function uses the
default interval of for and .
syms x y
fimplicit(x^2 - y^2 == 1)
4-537
4 Functions Alphabetical List
syms f(x,y)
f(x,y) = x^2 - y^2 - 1;
fimplicit(f)
4-538
fimplicit
syms x y
circle = x^2 + y^2 == 3;
fimplicit(circle, [-4 0 -2 2])
4-539
4 Functions Alphabetical List
You can plot multiple equations either by passing the inputs as a vector or by using hold
on to successively plot on the same figure. If you specify LineSpec and Name-Value
arguments, they apply to all lines. To set options for individual plots, use the function
handles returned by fimplicit.
Divide a figure into two subplots by using subplot. On the first subplot, plot
and using vector input. On the second subplot, plot the same
inputs by using hold on.
syms x y
circle1 = x^2 + y^2 == 1;
4-540
fimplicit
subplot(2,1,1)
fimplicit([circle1 circle2])
title('Multiple Equations Using Vector Input')
subplot(2,1,2)
fimplicit(circle1)
hold on
fimplicit(circle2)
title('Multiple Equations Using hold on Command')
hold off
4-541
4 Functions Alphabetical List
Plot three concentric circles of increasing diameter. For the first line, use a linewidth
of 2. For the second, specify a dashed red line style with circle markers. For the third,
specify a cyan, dash-dot line style with asterisk markers. Display the legend.
syms x y
circle = x^2 + y^2;
fimplicit(circle == 1, 'Linewidth', 2)
hold on
fimplicit(circle == 2, '--or')
fimplicit(circle == 3, '-.*c')
legend('show','Location','best')
hold off
4-542
fimplicit
fi =
4-543
4 Functions Alphabetical List
4-544
fimplicit
fi.LineStyle = '-.';
4-545
4 Functions Alphabetical List
S = sym(ax.XLim(1):pi/2:ax.XLim(2));
ax.XTick = double(S);
ax.XTickLabel = arrayfun(@texlabel, S, 'UniformOutput', false);
S = sym(ax.YLim(1):pi/2:ax.YLim(2));
ax.YTick = double(S);
ax.YTickLabel = arrayfun(@texlabel, S, 'UniformOutput', false);
4-546
fimplicit
Re-evaluation on Zoom
When you zoom into a plot, fimplicit re-evaluates the plot automatically. This re-
evaluation on zoom can reveal hidden detail at smaller scales.
subplot(2,1,1)
fimplicit(eqn)
4-547
4 Functions Alphabetical List
subplot(2,1,2)
fimplicit(eqn)
zoom(2)
Input Arguments
f Implicit equation or function to plot
symbolic equation | symbolic expression | symbolic function
4-548
fimplicit
Plotting range for x and y, specified as a vector of two numbers. The default range is [-5
5].
Plotting range for x and y, specified as a vector of four numbers. The default range is [-5
5 -5 5].
ax Axes object
axes object
Axes object. If you do not specify an axes object, then fimplicit uses the current axes
gca.
Line specification, specified as a character vector with a line style, marker, and color. The
elements of the character vector can appear in any order, and you can omit one or more
options. To show only markers with no connecting lines, specify a marker and omit the
line style.
Example: 'r--o' specifies a red color, a dashed line, and circle markers
4-549
4 Functions Alphabetical List
The function line properties listed here are only a subset. For a complete list, see Implicit
Function Line Properties.
Example: 'Marker','o','MarkerFaceColor','red'
4-550
fimplicit
Number of evaluation points per direction, specified as a number. The default is 151.
An RGB triplet is a three-element row vector whose elements specify the intensities of
the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. This table lists the long and short color name
options and the equivalent RGB triplet values.
Example: 'blue'
Example: [0 0 1]
Line style, specified as one of the line styles listed in this table.
4-551
4 Functions Alphabetical List
Line width, specified as a positive value in points. If the line has markers, then the line
width also affects the marker edges.
Example: 0.75
Marker symbol, specified as one of the values in this table. By default, a line does not
have markers. Add markers at selected points along the line by specifying a marker.
Value Description
'o' Circle
'+' Plus sign
'*' Asterisk
'.' Point
'x' Cross
'square' or 's' Square
'diamond' or 'd' Diamond
'^' Upward-pointing triangle
'v' Downward-pointing triangle
'>' Right-pointing triangle
'<' Left-pointing triangle
'pentagram' or 'p' Five-pointed star (pentagram)
'hexagram' or 'h' Six-pointed star (hexagram)
4-552
fimplicit
Value Description
'none' No markers
An RGB triplet is a three-element row vector whose elements specify the intensities of
the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. This table lists the long and short color name
options and the equivalent RGB triplet values.
4-553
4 Functions Alphabetical List
An RGB triplet is a three-element row vector whose elements specify the intensities of
the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. This table lists the long and short color name
options and the equivalent RGB triplet values.
Output Arguments
fi One or more implicit function line objects
scalar | vector
One or more implicit function line objects, returned as a scalar or a vector. You can use
these objects to query and modify properties of a specific line. For a list of properties, see
Implicit Function Line Properties.
4-554
fimplicit
More About
Create Plots on page 2-208
See Also
Functions
fcontour | fimplicit3 | fmesh | fplot | fplot3 | fsurf
Properties
Implicit Function Line Properties
Introduced in R2016b
4-555
4 Functions Alphabetical List
fimplicit3
Plot 3-D implicit equation or function
Syntax
fimplicit3(f)
fimplicit3(f,[min max])
fimplicit3(f,[xmin xmax ymin ymax zmin zmax])
Description
fimplicit3(f) plots the 3-D implicit equation or function f(x,y,z) over the default
interval [-5 5] for x, y, and z.
fimplicit3(f,[min max]) plots f(x,y,z) over the interval [min max] for x, y, and
z.
fimplicit3(f,[xmin xmax ymin ymax zmin zmax]) plots f(x,y,z) over the
interval [xmin xmax] for x, [ymin ymax] for y, and [zmin zmax] for z. fimplicit3
uses symvar to order the variables and assign intervals.
fimplicit3( ___ ,LineSpec) uses LineSpec to set the line style, marker symbol, and
face color.
fimplicit3(ax, ___ ) plots into the axes with the object ax instead of the current axes
object gca.
4-556
fimplicit3
fi = fimplicit3( ___ ) returns an implicit function surface object. Use the object
to query and modify properties of a specific surface. For details, see Implicit Function
Surface Properties.
Examples
syms x y z
fimplicit3(x^2 + y^2 - z^2)
4-557
4 Functions Alphabetical List
syms f(x,y,z)
f(x,y,z) = x^2 + y^2 - z^2;
fimplicit3(f)
4-558
fimplicit3
syms x y z
f = x^2 + y^2 - z^2;
interval = [-5 5 -5 5 0 5];
fimplicit3(f, interval)
4-559
4 Functions Alphabetical List
Create the x-axis ticks by spanning the x-axis limits at intervals of pi/2. Convert the
axis limits to precise multiples of pi/2 by using round and get the symbolic tick values
in S. Display these ticks by using the XTick property. Create x-axis labels by using
arrayfun to apply texlabel to S. Display these labels by using the XTickLabel
property. Repeat these steps for the y-axis.
4-560
fimplicit3
S = sym(ax.XLim(1):pi/2:ax.XLim(2));
S = sym(round(vpa(S/pi*2))*pi/2);
ax.XTick = double(S);
ax.XTickLabel = arrayfun(@texlabel,S,'UniformOutput',false);
S = sym(ax.YLim(1):pi/2:ax.YLim(2));
S = sym(round(vpa(S/pi*2))*pi/2);
ax.YTick = double(S);
ax.YTickLabel = arrayfun(@texlabel, S, 'UniformOutput', false);
4-561
4 Functions Alphabetical List
Plot the implicit surface with different line styles for different values
of . For , use a dashed line with green dot markers. For , use
a LineWidth of 1 and a green face color. For , turn off the lines by setting
EdgeColor to none.
syms x y z
f = x^2 + y^2 - z^2;
fimplicit3(f,[-5 5 -5 5 -5 -2],'--.','MarkerEdgeColor','g')
hold on
fimplicit3(f,[-5 5 -5 5 -2 2],'LineWidth',1,'FaceColor','g')
4-562
fimplicit3
fimplicit3(f,[-5 5 -5 5 2 5],'EdgeColor','none')
fi =
4-563
4 Functions Alphabetical List
Show only the positive x-axis by setting the XRange property of fi to [0 5]. Remove
the lines by setting the EdgeColor property to 'none'. Visualize the hidden surfaces by
making the plot transparent by setting the FaceAlpha property to 0.8.
4-564
fimplicit3
fi.XRange = [0 5];
fi.EdgeColor = 'none';
fi.FaceAlpha = 0.8;
Divide a figure into two by using subplot. In the first subplot, plot the implicit
surface . The surface has large gaps. Fix this issue by increasing the
4-565
4 Functions Alphabetical List
'MeshDensity' to 40 in the second subplot. fimplicit3 fills the gaps showing that by
increasing 'MeshDensity' you increased the resolution of the plot.
syms x y z
f = sin(1/(x*y*z));
subplot(2,1,1)
fimplicit3(f)
title('Default MeshDensity = 35')
subplot(2,1,2)
fimplicit3(f,'MeshDensity',40)
title('Increased MeshDensity = 40')
4-566
fimplicit3
Input Arguments
f 3-D implicit equation or function to plot
symbolic equation | symbolic expression | symbolic function
Plotting interval for x-, y- and z- axes, specified as a vector of two numbers. The default is
[-5 5].
[xmin xmax ymin ymax zmin zmax] Plotting interval for x-, y- and z- axes
[5 5 5 5 5 5] (default) | vector of six numbers
Plotting interval for x-, y- and z- axes, specified as a vector of six numbers. The default is
[-5 5 -5 5 -5 5].
ax Axes object
axes object
Axes object. If you do not specify an axes object, then fimplicit3 uses the current axes.
Line style, marker symbol, and face color, specified as a character vector. The elements of
the character vector can appear in any order, and you can omit one or more options from
the character vector specifier.
Example: '--or' is a red surface with circle markers and dashed lines
4-567
4 Functions Alphabetical List
Specifier Marker
o Circle
+ Plus sign
* Asterisk
. Point
x Cross
s Square
d Diamond
^ Upward-pointing triangle
v Downward-pointing triangle
> Right-pointing triangle
< Left-pointing triangle
p Pentagram
h Hexagram
Specifier Color
y yellow
m magenta
c cyan
r red
g green
b blue
w white
k black
4-568
fimplicit3
The properties listed here are only a subset. For a complete list, see Implicit Function
Surface Properties.
Number of evaluation points per direction, specified as a number. The default is 35.
Example: 100
An RGB triplet is a three-element row vector whose elements specify the intensities of
the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. This table lists the long and short color name
options and the equivalent RGB triplet values.
4-569
4 Functions Alphabetical List
Line style, specified as one of the line styles listed in this table.
Line width, specified as a positive value in points. If the line has markers, then the line
width also affects the marker edges.
Example: 0.75
Marker symbol, specified as one of the values in this table. By default, a line does not
have markers. Add markers at selected points along the line by specifying a marker.
Value Description
'o' Circle
4-570
fimplicit3
Value Description
'+' Plus sign
'*' Asterisk
'.' Point
'x' Cross
'square' or 's' Square
'diamond' or 'd' Diamond
'^' Upward-pointing triangle
'v' Downward-pointing triangle
'>' Right-pointing triangle
'<' Left-pointing triangle
'pentagram' or 'p' Five-pointed star (pentagram)
'hexagram' or 'h' Six-pointed star (hexagram)
'none' No markers
An RGB triplet is a three-element row vector whose elements specify the intensities of
the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. This table lists the long and short color name
options and the equivalent RGB triplet values.
4-571
4 Functions Alphabetical List
An RGB triplet is a three-element row vector whose elements specify the intensities of
the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. This table lists the long and short color name
options and the equivalent RGB triplet values.
4-572
fimplicit3
Example: 'green'
Output Arguments
fi One or more objects
scalar | vector
One or more objects, returned as a scalar or a vector. The object is an implicit function
surface object. You can use these objects to query and modify properties of a specific line.
For details, see Implicit Function Surface Properties.
More About
Create Plots on page 2-208
See Also
Functions
fcontour | fimplicit | fmesh | fplot | fplot3 | fsurf
Properties
Implicit Function Surface Properties
Introduced in R2016b
4-573
4 Functions Alphabetical List
findDecoupledBlocks
Search for decoupled blocks in systems of equations
Syntax
[eqsBlocks,varsBlocks] = findDecoupledBlocks(eqs,vars)
Description
[eqsBlocks,varsBlocks] = findDecoupledBlocks(eqs,vars) identifies subsets
(blocks) of equations that can be used to define subsets of variables. The number of
variables vars must coincide with the number of equations eqs.
Examples
4-574
findDecoupledBlocks
Create the following system of four differential algebraic equations. Here, the symbolic
function calls x1(t), x2(t), x3(t), and x4(t) represent the state variables of the
system. The system also contains symbolic parameters c1, c2, c3, c4, and functions
f(t,x,y) and g(t,x,y).
syms x1(t) x2(t) x3(t) x4(t)
syms c1 c2 c3 c4
syms f(t,x,y) g(t,x,y)
eqs = [c1*diff(x1(t),t)+c2*diff(x3(t),t)==c3*f(t,x1(t),x3(t));...
c2*diff(x1(t),t)+c1*diff(x3(t),t)==c4*g(t,x3(t),x4(t));...
x1(t)==g(t,x1(t),x3(t));...
x2(t)==f(t,x3(t),x4(t))];
eqsBlocks =
13 cell array
[12 double] [2] [4]
varsBlocks =
13 cell array
[12 double] [4] [2]
ans =
c1*diff(x1(t), t) + c2*diff(x3(t), t) == c3*f(t, x1(t), x3(t))
x1(t) == g(t, x1(t), x3(t))
vars(varsBlocks{1})
ans =
[ x1(t), x3(t)]
After you solve this block for the variables x1(t), x3(t), you can solve the next block of
equations. This block consists of one equation.
eqs(eqsBlocks{2})
ans =
4-575
4 Functions Alphabetical List
vars(varsBlocks{2})
ans =
x4(t)
After you solve the equation from block 2 for the variable x4(t), the remaining
block of equations, eqs(eqsBlocks{3}), defines the remaining variable,
vars(varsBlocks{3}).
eqs(eqsBlocks{3})
vars(varsBlocks{3})
ans =
x2(t) == f(t, x3(t), x4(t))
ans =
x2(t)
Find the permutations that convert the system to a block lower triangular form.
eqsPerm = [eqsBlocks{:}]
varsPerm = [varsBlocks{:}]
eqsPerm =
1 3 2 4
varsPerm =
1 3 4 2
eqs = eqs(eqsPerm)
vars = vars(varsPerm)
eqs =
c1*diff(x1(t), t) + c2*diff(x3(t), t) == c3*f(t, x1(t), x3(t))
x1(t) == g(t, x1(t), x3(t))
c2*diff(x1(t), t) + c1*diff(x3(t), t) == c4*g(t, x3(t), x4(t))
x2(t) == f(t, x3(t), x4(t))
vars =
4-576
findDecoupledBlocks
Find the incidence matrix of the resulting system. The incidence matrix shows that the
system of permuted equations has three diagonal blocks of size 2-by-2, 1-by-1, and 1-
by-1.
incidenceMatrix(eqs, vars)
ans =
1 1 0 0
1 1 0 0
1 1 1 0
0 1 1 1
Use findDecoupledBlocks to convert the system to a lower triangular form. For this
system, findDecoupledBlocks identifies three blocks of equations and corresponding
variables.
[eqsBlocks, varsBlocks] = findDecoupledBlocks(eqs, vars)
eqsBlocks =
13 cell array
[13 double] [12 double] [4]
varsBlocks =
13 cell array
[13 double] [12 double] [2]
4-577
4 Functions Alphabetical List
Identify the variables in the first block. This block consists of three equations in three
variables.
vars(varsBlocks{1})
ans =
[ x1, x3, x5]
Solve the first block of equations for the first block of variables assigning the solutions to
the corresponding variables.
[x1,x3,x5] = solve(eqs(eqsBlocks{1}), vars(varsBlocks{1}))
x1 =
1
x3 =
c2
x5 =
1
Identify the variables in the second block. This block consists of two equations in two
variables.
vars(varsBlocks{2})
ans =
[ x4, x6]
Solve this block of equations assigning the solutions to the corresponding variables.
[x4, x6] = solve(eqs(eqsBlocks{2}), vars(varsBlocks{2}))
x4 =
x3/3 - x1 - c2/3 + 2
x6 =
(2*c2)/3 - (2*x3)/3 + 1
Use subs to evaluate the result for the already known values of variables x1, x3, and x5.
x4 = subs(x4)
x6 = subs(x6)
x4 =
4-578
findDecoupledBlocks
x6 =
1
Identify the variables in the third block. This block consists of one equation in one
variable.
vars(varsBlocks{3})
ans =
x2
x2 = solve(eqs(eqsBlocks{3}), vars(varsBlocks{3}))
x2 =
c2 - x3 - x4 - x5 + 2
Use subs to evaluate the result for the already known values of all other variables of this
system.
x2 = subs(x2)
x2 =
0
Alternatively, you can rewrite this example using the for-loop. This approach lets you
use the example for larger systems of equations.
syms x1 x2 x3 x4 x5 x6 c1 c2 c3
vars_sol = vars;
4-579
4 Functions Alphabetical List
for i = 1:numel(eqsBlocks)
sol = solve(eqs(eqsBlocks{i}), vars(varsBlocks{i}));
vars_sol_per_block = subs(vars(varsBlocks{i}), sol);
for k=1:i-1
vars_sol_per_block = subs(vars_sol_per_block, vars(varsBlocks{k}),...
vars_sol(varsBlocks{k}));
end
vars_sol(varsBlocks{i}) = vars_sol_per_block
end
vars_sol =
[ 1, x2, c2, x4, 1, x6]
vars_sol =
[ 1, x2, c2, 1, 1, 1]
vars_sol =
[ 1, 0, c2, 1, 1, 1]
Input Arguments
eqs System of equations
vector of symbolic equations | vector of symbolic expressions
vars Variables
vector of symbolic variables | vector of symbolic functions | vector of symbolic function
calls
Output Arguments
eqsBlocks Indices defining blocks of equations
cell array
4-580
findDecoupledBlocks
Indices defining blocks of equations, returned as a cell array. Each block of indices
is a row vector of double-precision integer numbers. The ith block of equations
consists of the equations eqs(eqsBlocks{i}) and involves only the variables in
vars(varsBlocks{1:i}).
Indices defining blocks of variables, returned as a cell array. Each block of indices
is a row vector of double-precision integer numbers. The ith block of equations
consists of the equations eqs(eqsBlocks{i}) and involves only the variables in
vars(varsBlocks{1:i}).
More About
Tips
The implemented algorithm requires that for each variable in vars there must be at
least one matching equation in eqs involving this variable. The same equation cannot
also be matched to another variable. If the system does not satisfy this condition, then
findDecoupledBlocks throws an error. In particular, findDecoupledBlocks
requires that length(eqs) = length(vars).
Applying the permutations e = [eqsBlocks{:}] to the vector eqs and
v = [varsBlocks{:}] to the vector vars produces an incidence matrix
incidenceMatrix(eqs(e), vars(v)) that has a block lower triangular sparsity
pattern.
See Also
daeFunction | decic | diag | incidenceMatrix | isLowIndexDAE |
massMatrixForm | odeFunction | reduceDAEIndex | reduceDAEToODE |
reduceDifferentialOrder | reduceRedundancies | tril | triu
Introduced in R2014b
4-581
4 Functions Alphabetical List
finverse
Functional inverse
Syntax
g = finverse(f)
g = finverse(f,var)
Description
g = finverse(f) returns the inverse of function f. Here f is an expression or function
of one symbolic variable, for example, x. Then g is an expression or function, such that
f(g(x)) = x. That is, finverse(f) returns f , provided f exists.
1 1
Input Arguments
f
var
Symbolic variable.
Output Arguments
g
4-582
finverse
Examples
Compute functional inverse for this trigonometric function:
syms x
f(x) = 1/tan(x);
g = finverse(f)
g(x) =
atan(1/x)
ans =
2*v + log(u)
More About
Tips
finverse does not issue a warning when the inverse is not unique.
See Also
compose | syms
4-583
4 Functions Alphabetical List
fix
Round toward zero
Syntax
fix(X)
Description
fix(X) is the matrix of the integer parts of X.
See Also
round | ceil | floor | frac
4-584
floor
floor
Round symbolic matrix toward negative infinity
Syntax
floor(X)
Description
floor(X) is the matrix of the greatest integers less 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 | ceil | fix | frac
4-585
4 Functions Alphabetical List
fmesh
Plot 3-D mesh
Syntax
fmesh(f)
fmesh(f,[min max])
fmesh(f,[xmin xmax ymin ymax])
fmesh(funx,funy,funz)
fmesh(funx,funy,funz,[uvmin uvmax])
fmesh(funx,funy,funz,[umin umax vmin vmax])
Description
fmesh(f) creates a mesh plot of the symbolic expression f(x,y) over the default
interval [-5 5] for x and y.
fmesh(f,[min max]) plots f(x,y) over the interval [min max] for x and y.
fmesh(f,[xmin xmax ymin ymax]) plots f(x,y) over the interval [xmin xmax] for
x and [ymin ymax] for y.
4-586
fmesh
fmesh( ___ ,LineSpec) uses the LineSpec to set the line style, marker symbol, and
plot color.
fmesh( ___ ,Name,Value) specifies surface properties using one or more Name,Value
pair arguments. Use this option with any of the input argument combinations in the
previous syntaxes.
fmesh(ax, ___ ) plots into the axes with the object ax instead of the current axes object
gca.
Examples
Note: For additional examples, follow the fsurf page because fmesh and fsurf share
the same syntax. All examples on the fsurf page apply to fmesh.
syms x y
fmesh(sin(x)+cos(y))
4-587
4 Functions Alphabetical List
Plot a 3-D mesh of the real part of over the default range and
.
syms f(x,y)
f(x,y) = real(atan(x + i*y));
fmesh(f)
4-588
fmesh
syms x y
f = sin(x) + cos(y);
fmesh(f, [-pi pi -5 5])
4-589
4 Functions Alphabetical List
for and . Make the aspect ratio of the axes equal using axis
equal. See the entire mesh by making the mesh partially transparent using alpha.
syms s t
4-590
fmesh
r = 8 + sin(7*s + 5*t);
x = r*cos(s)*sin(t);
y = r*sin(s)*sin(t);
z = r*cos(t);
fmesh(x, y, z, [0 2*pi 0 pi], 'Linewidth', 2)
axis equal
alpha(0.8)
Note: For additional examples, follow the fsurf page because fmesh and fsurf share
the same syntax. All examples on the fsurf page apply to fmesh.
4-591
4 Functions Alphabetical List
Input Arguments
f 3-D expression or function to be plotted
symbolic expression | symbolic function
Plotting interval for x- and y-axes, specified as a vector of two numbers. The default is
[-5 5].
Plotting interval for x- and y-axes, specified as a vector of four numbers. The default is
[-5 5 -5 5].
Plotting interval for u and v axes, specified as a vector of two numbers. The default is
[-5 5].
Plotting interval for u and v, specified as a vector of four numbers. The default is [-5 5
-5 5].
ax Axes object
axes object
Axes object. If you do not specify an axes object, then fmesh uses the current axes.
4-592
fmesh
Line style, marker symbol, and line color, specified as a character vector. The elements of
the character vector can appear in any order, and you can omit one or more options from
the character vector specifier.
Example: '--or' is a red mesh with circle markers
Specifier Marker
o Circle
+ Plus sign
* Asterisk
. Point
x Cross
s Square
d Diamond
^ Upward-pointing triangle
v Downward-pointing triangle
> Right-pointing triangle
< Left-pointing triangle
p Pentagram
h Hexagram
Specifier Color
y yellow
m magenta
c cyan
4-593
4 Functions Alphabetical List
Specifier Color
r red
g green
b blue
w white
k black
Number of evaluation points per direction, specified as a number. The default is 35.
Because fmesh uses adaptive evaluation, the actual number of evaluation points is
greater.
Example: 100
4-594
fmesh
An RGB triplet is a three-element row vector whose elements specify the intensities of
the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. This table lists the long and short color name
options and the equivalent RGB triplet values.
Example: 'blue'
Example: [0 0 1]
Line style, specified as one of the line styles listed in this table.
4-595
4 Functions Alphabetical List
Line width, specified as a positive value in points. If the line has markers, then the line
width also affects the marker edges.
Example: 0.75
Marker symbol, specified as one of the values in this table. By default, a line does not
have markers. Add markers at selected points along the line by specifying a marker.
Value Description
'o' Circle
'+' Plus sign
'*' Asterisk
'.' Point
'x' Cross
'square' or 's' Square
'diamond' or 'd' Diamond
'^' Upward-pointing triangle
'v' Downward-pointing triangle
'>' Right-pointing triangle
'<' Left-pointing triangle
'pentagram' or 'p' Five-pointed star (pentagram)
'hexagram' or 'h' Six-pointed star (hexagram)
'none' No markers
4-596
fmesh
An RGB triplet is a three-element row vector whose elements specify the intensities of
the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. This table lists the long and short color name
options and the equivalent RGB triplet values.
An RGB triplet is a three-element row vector whose elements specify the intensities of
the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. This table lists the long and short color name
options and the equivalent RGB triplet values.
4-597
4 Functions Alphabetical List
Output Arguments
obj One or more objects
scalar | vector
One or more objects, returned as a scalar or a vector. The object is either a function
surface object or parameterized mesh object, depending on the type of plot. You can use
these objects to query and modify properties of a specific line. For details, see Function
Surface Properties and Parameterized Function Surface Properties.
More About
Create Plots on page 2-208
See Also
Functions
fcontour | fimplicit | fimplicit3 | fplot | fplot3 | fsurf
4-598
fmesh
Properties
Function Surface Properties | Parameterized Function Surface Properties
Introduced in R2016a
4-599
4 Functions Alphabetical List
fold
Combine (fold) vector using function
Syntax
fold(fun,v)
fold(fun,v,defaultVal)
Description
fold(fun,v) folds v by using fun. That is, fold calls fun on the first two elements
of v, and then repeatedly calls fun on the result and the next element till the last
element is combined. Programmatically, the fold operation is fold(fun,v) =
fun(fold(fun,v(1:end-1)),v(end)).
Examples
Fold Vector Using Function
Fold a vector of symbolic variables using the power function. The output shows how
fold combines elements of the vector from left to right by using the specified function.
syms a b c d e
fold(@power, [a b c d e])
ans =
(((a^b)^c)^d)^e
4-600
fold
syms x
cond = fold(@or, x == 1:10);
assume(cond)
assumptions
ans =
x == 1 | x == 2 | x == 3 | x == 4 | x == 5 |...
x == 6 | x == 7 | x == 8 | x == 9 | x == 10
When creating a function to sum a vector, specify a default value of 0, such that the
function returns 0 when the vector is empty.
sumVector = @(x) fold(@plus, x, 0);
sumVector([])
ans =
0
Input Arguments
fun Function used to fold vector
function handle
v Vector to fold
vector | symbolic vector | cell vector
4-601
4 Functions Alphabetical List
See Also
prod | sum
Introduced in R2016b
4-602
formula
formula
Mathematical expression defining symbolic function
Syntax
formula(f)
Description
formula(f) returns the mathematical expression that defines f.
Input Arguments
f
Symbolic function.
Examples
Create this symbolic function:
syms x y
f(x, y) = x + y;
ans =
x + y
If you do not specify a mathematical expression for the symbolic function, formula
returns the symbolic function definition as follows:
4-603
4 Functions Alphabetical List
formula(f)
ans =
f(x, y)
See Also
argnames | sym | syms | symvar
Introduced in R2012a
4-604
fortran
fortran
Fortran representation of symbolic expression
Syntax
fortran(S)
fortran(S,'file',fileName)
Description
fortran(S) returns the Fortran code equivalent to the expression S.
Examples
The statements
syms x
f = taylor(log(1+x));
fortran(f)
return
ans =
195 char array
t0 = x-x**2*(1.0D0/2.0D0)+x**3*(1.0D0/3.0D0)-x**4*(1.0D0/4.0D0)+x*
&*5*(1.0D0/5.0D0)
The statements
H = sym(hilb(3));
fortran(H)
return
4-605
4 Functions Alphabetical List
ans =
1236 char array
H(1,1) = 1.0D0
H(1,2) = 1.0D0/2.0D0
H(1,3) = 1.0D0/3.0D0
H(2,1) = 1.0D0/2.0D0
H(2,2) = 1.0D0/3.0D0
H(2,3) = 1.0D0/4.0D0
H(3,1) = 1.0D0/3.0D0
H(3,2) = 1.0D0/4.0D0
H(3,3) = 1.0D0/5.0D0
The statements
syms x
z = exp(-exp(-x));
fortran(diff(z,3),'file','fortrantest')
t7 = exp(-x)
t8 = exp(-t7)
t0 = t8*exp(x*(-2))*(-3)+t8*exp(x*(-3))+t7*t8
Tips
MATLAB is left associative while Fortran is right associative. If ambiguity exists in
an expression, the fortran function must follow MATLAB to create an equivalent
representation. For example, fortran represents a^b^c in MATLAB as (a**b)**c
in Fortran.
See Also
ccode | latex | matlabFunction | pretty
4-606
fourier
fourier
Fourier transform
Syntax
fourier(f)
fourier(f,transVar)
fourier(f,var,transVar)
Description
fourier(f) returns the Fourier transform of f using the default independent variable x
and the default transformation variable w. If f does not contain x, fourier uses symvar.
Examples
syms x y
f = exp(-x^2);
fourier(f, x, y)
ans =
pi^(1/2)*exp(-y^2/4)
4-607
4 Functions Alphabetical List
ans =
pi^(1/2)*exp(-t^2)*exp(-y^2/4)
If you also do not specify the transformation variable, fourier uses the variable w.
fourier(f)
ans =
pi^(1/2)*exp(-t^2)*exp(-w^2/4)
ans =
-pi*dirac(3, w)*2i
syms t0
fourier(heaviside(t - t0), t, w)
ans =
exp(-t0*w*1i)*(pi*dirac(w) - 1i/w)
Compute the Fourier transform of this expression using the default values c = 1, s =
-1 of the Fourier parameters. (For details, see Fourier Transform on page 4-612.)
syms t w
4-608
fourier
pretty(fourier(t*exp(-t^2), t, w))
/ 2 \
| w |
w sqrt(pi) exp| - -- | 1i
\ 4 /
- -------------------------
2
Change the values of the Fourier parameters toc = 1,s = 1 by using sympref. Then
compute the Fourier transform of the same expression again.
sympref('FourierParameters', [1, 1]);
pretty(fourier(t*exp(-t^2), t, w))
/ 2 \
| w |
w sqrt(pi) exp| - -- | 1i
\ 4 /
-------------------------
2
Change the values of the Fourier parameters toc = 1/2,s = 1 by using sympref.
Compute the Fourier transform using these values.
sympref('FourierParameters', [1/(2*sym(pi)), 1]);
pretty(fourier(t*exp(-t^2), t, w))
/ 2 \
| w |
w exp| - -- | 1i
\ 4 /
----------------
4 sqrt(pi)
The preferences set by sympref persist through your current and future MATLAB
sessions. To restore the default values of c and s, set sympref to 'default'.
sympref('FourierParameters','default');
4-609
4 Functions Alphabetical List
syms f(t) w
fourier(diff(f(t), t), t, w)
ans =
w*fourier(f(t), t, w)*1i
syms a b c d w x y z
fourier([exp(x), 1; sin(y), i*z],[w, x; y, z],[a, b; c, d])
ans =
[ 2*pi*exp(x)*dirac(a), 2*pi*dirac(b)]
[ -pi*(dirac(c - 1) - dirac(c + 1))*1i, -2*pi*dirac(1, d)]
When the input arguments are nonscalars, fourier acts on them element-wise. If
fourier is called with both scalar and nonscalar arguments, then fourier expands
the scalar arguments into arrays of the same size as the nonscalar arguments with all
elements of the array equal to the scalar.
syms w x y z a b c d
fourier(x,[x, w; y, z],[a, b; c, d])
ans =
[ pi*dirac(1, a)*2i, 2*pi*x*dirac(b)]
[ 2*pi*x*dirac(c), 2*pi*x*dirac(d)]
Note that nonscalar input arguments must have the same size.
ans =
[ fourier(exp(x), x, a), pi*dirac(1, b)*2i]
4-610
fourier
F =
fourier(f(t), t, w)
ans =
f(t)
Input Arguments
f Input function
symbolic expression | symbolic function | vector of symbolic expressions or functions |
matrix of symbolic expressions or functions
Independent variable, specified as a symbolic variable. This variable is often called the
time variable or the space variable.
If you do not specify the independent variable, fourier uses the variable x by default. If
f does not contain x, then the default variable is determined by symvar.
4-611
4 Functions Alphabetical List
If you do not specify the transformation variable, fourier uses the variable w by default.
If w is the independent variable of f, then the default transformation variable is the
variable v.
More About
Fourier Transform
The Fourier transform of the expression f=f(x) with respect to the variable x at the point
w is defined as follows:
F ( w) = c f ( x) eiswx dx.
-
Here, c and s are parameters of the Fourier transform. The fourier function uses c=1,
s=1.
Tips
References
[1] Oberhettinger F., Tables of Fourier Transforms and Fourier Transforms of
Distributions, Springer, 1990.
See Also
ifourier | ilaplace | iztrans | laplace | sympref | ztrans
4-612
fplot
fplot
Plot symbolic expression or function
Syntax
fplot(f)
fplot(f,[xmin xmax])
fplot(xt,yt)
fplot(xt,yt,[tmin tmax])
Description
fplot(f) plots symbolic input f over the default interval [-5 5].
fplot(xt,yt) plots xt=x(t) and yt=y(t) over the default range of t, which is [5 5].
fplot(xt,yt,[tmin tmax]) plots xt=x(t) and yt=y(t) over the specified range [tmin
tmax].
fplot( ___ ,LineSpec) uses LineSpec to set the line style, marker symbol, and line
color.
fplot( ___ ,Name,Value) specifies line properties using one or more Name,Value
pair arguments. Use this option with any of the input argument combinations in the
previous syntaxes. Name,Value pair settings apply to all the lines plotted. To set options
for individual lines, use the objects returned by fplot.
fplot(ax, ___ ) plots into the axes specified by ax instead of the current axes gca.
4-613
4 Functions Alphabetical List
Examples
syms x
fplot(tan(x))
4-614
fplot
Plot the symbolic function over the default range [-5 5].
syms f(x)
f(x) = cos(x);
fplot(f)
4-615
4 Functions Alphabetical List
syms t
x = cos(3*t);
y = sin(2*t);
fplot(x,y)
4-616
fplot
syms x
fplot(sin(x),[-pi/2 pi/2])
4-617
4 Functions Alphabetical List
Divide a figure into two subplots using subplot. On the first subplot, plot and
using vector input. On the second subplot, plot and using hold on.
syms x
subplot(2,1,1)
4-618
fplot
fplot([sin(x) cos(x)])
title('Multiple Lines Using Vector Inputs')
subplot(2,1,2)
fplot(sin(x))
hold on
fplot(cos(x))
title('Multiple Lines Using hold on Command')
hold off
4-619
4 Functions Alphabetical List
syms x
fplot(sin(x+pi/5),'Linewidth',2)
hold on
fplot(sin(x-pi/5),'--or')
fplot(sin(x),'-.*c')
legend('show','Location','best')
hold off
4-620
fplot
syms x
h = fplot(sin(x))
h =
4-621
4 Functions Alphabetical List
Change the default blue line to a dashed red line by using dot notation to set properties.
Similarly, add 'x' markers and set the marker color to blue.
h.LineStyle = '--';
h.Color = 'r';
h.Marker = 'x';
h.MarkerEdgeColor = 'b';
4-622
fplot
For from to , plot . Add a title and axis labels. Create the x-axis ticks by
spanning the x-axis limits at intervals of pi/2. Display these ticks by using the XTick
property. Create x-axis labels by using arrayfun to apply texlabel to S. Display these
labels by using the XTickLabel property.
syms x
fplot(sin(x),[-2*pi 2*pi])
grid on
4-623
4 Functions Alphabetical List
ax = gca;
S = sym(ax.XLim(1):pi/2:ax.XLim(2));
ax.XTick = double(S);
ax.XTickLabel = arrayfun(@texlabel,S,'UniformOutput',false);
Re-evaluation on Zoom
When you zoom into a plot, fplot re-evaluates the plot automatically. This re-evaluation
on zoom reveals hidden detail at smaller scales.
4-624
fplot
Plot x^3*sin(1/x) for -2 < x < 2 and -0.02 < y < 0.02. Zoom in on the plot
using zoom and redraw the plot using drawnow. Because of re-evaluation on zoom,
fplot reveals smaller-scale detail. Repeat the zoom 6 times to view smaller-scale details.
To play the animation, click the image.
syms x
fplot(x^3*sin(1/x));
axis([-2 2 -0.02 0.02]);
for i=1:6
zoom(1.7)
pause(0.5)
end
4-625
4 Functions Alphabetical List
Create Animations
Create animations by changing the displayed expression using the Function,
XFunction, and YFunction properties and then by using drawnow to update the plot.
To export to GIF, see imwrite.
x = it sin ( it )
y = it cos ( it ) .
syms t
fp = fplot(t, t);
axis([-15 15 -15 15])
for i=0.1:0.05:3
fp.XFunction = i.*t.*sin(i*t);
fp.YFunction = i.*t.*cos(i*t);
drawnow
end
4-626
fplot
Input Arguments
f Expression or function to plot
symbolic expression | symbolic function
Plotting interval for x-coordinates, specified as a vector of two numbers. The default
range is [-5 5].
4-627
4 Functions Alphabetical List
Parametric input for y-axis, specified as a symbolic expression or function. fplot uses
symvar to find the parameter.
Range of values of parameter t, specified as a vector of two numbers. The default range
is [-5 5].
ax Axes object
axes object
Axes object. If you do not specify an axes object, then fplot uses the current axes gca.
Line specification, specified as a character vector with a line style, marker, and color. The
elements of the character vector can appear in any order, and you can omit one or more
options. To show only markers with no connecting lines, specify a marker and omit the
line style.
Example: 'r--o' specifies a red color, a dashed line, and circle markers
4-628
fplot
4-629
4 Functions Alphabetical List
The function line properties listed here are only a subset. For a complete list, see
Function Line Properties.
Example: 'Marker','o','MarkerFaceColor','red'
Number of evaluation points, specified as a number. The default is 23. Because fplot uses
adaptive evaluation, the actual number of evaluation points is greater.
An RGB triplet is a three-element row vector whose elements specify the intensities of
the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. This table lists the long and short color name
options and the equivalent RGB triplet values.
Example: 'blue'
4-630
fplot
Example: [0 0 1]
Line style, specified as one of the line styles listed in this table.
Line width, specified as a positive value in points. If the line has markers, then the line
width also affects the marker edges.
Example: 0.75
Marker symbol, specified as one of the values in this table. By default, a line does not
have markers. Add markers at selected points along the line by specifying a marker.
Value Description
'o' Circle
'+' Plus sign
'*' Asterisk
'.' Point
'x' Cross
4-631
4 Functions Alphabetical List
Value Description
'square' or 's' Square
'diamond' or 'd' Diamond
'^' Upward-pointing triangle
'v' Downward-pointing triangle
'>' Right-pointing triangle
'<' Left-pointing triangle
'pentagram' or 'p' Five-pointed star (pentagram)
'hexagram' or 'h' Six-pointed star (hexagram)
'none' No markers
An RGB triplet is a three-element row vector whose elements specify the intensities of
the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. This table lists the long and short color name
options and the equivalent RGB triplet values.
4-632
fplot
An RGB triplet is a three-element row vector whose elements specify the intensities of
the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. This table lists the long and short color name
options and the equivalent RGB triplet values.
4-633
4 Functions Alphabetical List
Output Arguments
fp One or more function or parameterized line objects
scalar | vector
If you use the fplot(f) syntax or a variation of this syntax, then fplot returns
function line objects.
If you use the fplot(xt,yt) syntax or a variation of this syntax, then fplot
returns parameterized line objects.
You can use these objects to query and modify properties of a specific line. For a list of
properties, see Function Line Properties and Parameterized Function Line Properties.
More About
Create Plots on page 2-208
See Also
Functions
fcontour | fimplicit | fimplicit3 | fmesh | fplot3 | fsurf
Properties
Function Line Properties | Parameterized Function Line Properties
Introduced in R2016a
4-634
fplot3
fplot3
Plot 3-D parametric curve
Syntax
fplot3(xt,yt,zt)
fplot3(xt,yt,zt,[tmin tmax])
Description
fplot3(xt,yt,zt) plots the parametric curve xt = x(t), yt = y(t), and zt = z(t) over the
default interval 5<t<5.
fplot3(xt,yt,zt,[tmin tmax]) plots xt = x(t), yt = y(t), and zt = z(t) over the interval
tmin < t < tmax.
fplot3( ___ ,LineSpec) uses LineSpec to set the line style, marker symbol, and line
color.
fplot3( ___ ,Name,Value) specifies line properties using one or more Name,Value
pair arguments. Use this option with any of the input argument combinations in the
previous syntaxes. Name,Value pair settings apply to all the lines plotted. To set options
for individual lines, use the objects returned by fplot3.
fplot3(ax, ___ ) plots into the axes object ax instead of the current axes gca.
fp = fplot3( ___ ) returns a parameterized function line object. Use the object
to query and modify properties of a specific parameterized line. For details, see
Parameterized Function Line Properties.
4-635
4 Functions Alphabetical List
Examples
syms t
xt = sin(t);
yt = cos(t);
zt = t;
fplot3(xt,yt,zt)
4-636
fplot3
over the parameter range [-10 10] by specifying the fourth argument of fplot3.
syms t
xt = exp(-t/10).*sin(5*t);
4-637
4 Functions Alphabetical List
yt = exp(-t/10).*cos(5*t);
zt = t;
fplot3(xt,yt,zt,[-10 10])
syms t
fplot3(sin(t), cos(t), t, [0 2*pi], 'LineWidth', 2)
4-638
fplot3
hold on
fplot3(sin(t), cos(t), t, [2*pi 4*pi], '--or')
fplot3(sin(t), cos(t), t, [4*pi 6*pi], '-.*c')
4-639
4 Functions Alphabetical List
4-640
fplot3
Divide a figure into two subplots using subplot. On the first subplot, plot two
parameterized lines using vector input. On the second subplot, plot the same lines using
hold on.
syms t
subplot(2,1,1)
fplot3([t -t], t, [t -t])
title('Multiple Lines Using Vector Inputs')
subplot(2,1,2)
fplot3(t, t, t)
hold on
fplot3(-t, t, -t)
title('Multiple Lines Using Hold On Command')
hold off
4-641
4 Functions Alphabetical List
syms t
4-642
fplot3
xt = exp(-abs(t)/10).*sin(5*abs(t));
yt = exp(-abs(t)/10).*cos(5*abs(t));
zt = t;
fp = fplot3(xt,yt,zt)
fp =
4-643
4 Functions Alphabetical List
Change the range of parameter values to [-10 10] and the line color to red by using the
TRange and Color properties of fp respectively.
4-644
fplot3
Add a title and axis labels. Create the x-axis ticks by spanning the x-axis limits at
intervals of pi/2. Display these ticks by using the XTick property. Create x-axis
labels by using arrayfun to apply texlabel to S. Display these labels by using the
XTickLabel property. Repeat these steps for the y-axis.
4-645
4 Functions Alphabetical List
syms t
xt = t;
yt = t/2;
zt = sin(6*t);
fplot3(xt,yt,zt,[-2*pi 2*pi],'MeshDensity',30)
view(52.5,30)
xlabel('x')
ylabel('y')
title('x=t, y=t/2, z=sin(6t) for -2\pi < t < 2\pi')
ax = gca;
S = sym(ax.XLim(1):pi/2:ax.XLim(2));
ax.XTick = double(S);
ax.XTickLabel = arrayfun(@texlabel, S, 'UniformOutput', false);
S = sym(ax.YLim(1):pi/2:ax.YLim(2));
ax.YTick = double(S);
ax.YTickLabel = arrayfun(@texlabel, S, 'UniformOutput', false);
4-646
fplot3
Create Animations
Create animations by changing the displayed expression using the XFunction,
YFunction, and ZFunction properties and then by using drawnow to update the plot.
To export to GIF, see imwrite.
x = t + sin ( 40 t)
y = - t + cos ( 40 t )
z = sin(t + i).
4-647
4 Functions Alphabetical List
Input Arguments
xt Parametric input for x-axis
symbolic expression | symbolic function
4-648
fplot3
Parametric input for x-axis, specified as a symbolic expression or function. fplot3 uses
symvar to find the parameter.
Parametric input for y-axis, specified as a symbolic expression or function. fplot3 uses
symvar to find the parameter.
Parametric input for z-axis, specified as a symbolic expression or function. fplot3 uses
symvar to find the parameter.
Range of values of parameter, specified as a vector of two numbers. The default range is
[-5 5].
ax Axes object
axes object
Axes object. If you do not specify an axes object, then fplot3 uses the current axes.
Line specification, specified as a character vector with a line style, marker, and color. The
elements of the character vector can appear in any order, and you can omit one or more
options. To show only markers with no connecting lines, specify a marker and omit the
line style.
Example: 'r--o' specifies a red color, a dashed line, and circle markers
4-649
4 Functions Alphabetical List
4-650
fplot3
Example: 'Marker','o','MarkerFaceColor','red'
The properties listed here are only a subset. For a complete list, see Parameterized
Function Line Properties.
Number of evaluation points, specified as a number. The default is 23. Because fplot3
uses adaptive evaluation, the actual number of evaluation points is greater.
An RGB triplet is a three-element row vector whose elements specify the intensities of
the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. This table lists the long and short color name
options and the equivalent RGB triplet values.
Example: 'blue'
Example: [0 0 1]
Line style, specified as one of the line styles listed in this table.
4-651
4 Functions Alphabetical List
Line width, specified as a positive value in points. If the line has markers, then the line
width also affects the marker edges.
Example: 0.75
Marker symbol, specified as one of the values in this table. By default, a line does not
have markers. Add markers at selected points along the line by specifying a marker.
Value Description
'o' Circle
'+' Plus sign
'*' Asterisk
'.' Point
'x' Cross
'square' or 's' Square
'diamond' or 'd' Diamond
'^' Upward-pointing triangle
'v' Downward-pointing triangle
'>' Right-pointing triangle
4-652
fplot3
Value Description
'<' Left-pointing triangle
'pentagram' or 'p' Five-pointed star (pentagram)
'hexagram' or 'h' Six-pointed star (hexagram)
'none' No markers
An RGB triplet is a three-element row vector whose elements specify the intensities of
the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. This table lists the long and short color name
options and the equivalent RGB triplet values.
4-653
4 Functions Alphabetical List
An RGB triplet is a three-element row vector whose elements specify the intensities of
the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. This table lists the long and short color name
options and the equivalent RGB triplet values.
Output Arguments
fp One or more parameterized function line objects
scalar | vector
4-654
fplot3
One or more parameterized line objects, returned as a scalar or a vector. You can use
these objects to query and modify properties of a specific parameterized line. For details,
see Parameterized Function Line Properties.
More About
Create Plots on page 2-208
See Also
Functions
fcontour | fimplicit | fimplicit3 | fmesh | fplot | fsurf
Properties
Parameterized Function Line Properties
Introduced in R2016a
4-655
4 Functions Alphabetical List
frac
Symbolic matrix element-wise fractional parts
Syntax
frac(X)
Description
frac(X) is the matrix of the fractional parts of the elements: frac(X) = X - fix(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 | ceil | floor | fix
4-656
fresnelc
fresnelc
Fresnel cosine integral function
Syntax
fresnelc(z)
Description
fresnelc(z) returns the Fresnel cosine integral of z.
Examples
Fresnel Cosine Integral Function for Numeric and Symbolic Input
Arguments
Find the Fresnel cosine integral function for these numbers. Since these are not symbolic
objects, you receive floating-point results.
fresnelc([-2 0.001 1.22+0.31i])
ans =
-0.4883 + 0.0000i 0.0010 + 0.0000i 0.8617 - 0.2524i
Find the Fresnel cosine integral function symbolically by converting the numbers to
symbolic objects:
y = fresnelc(sym([-2 0.001 1.22+0.31i]))
y =
[ -fresnelc(2), fresnelc(1/1000), fresnelc(61/50 + 31i/100)]
4-657
4 Functions Alphabetical List
ans =
0.0000 + 0.0000i 0.5000 + 0.0000i -0.5000 + 0.0000i...
0.0000 + 0.5000i 0.0000 - 0.5000i
ans =
fresnelc(2*x + exp(x))
ans =
[ fresnelc(sin(x)), fresnelc(2i), -fresnelc(7)]
ans =
[ 0, fresnelc(2)]
[ fresnelc(1i), fresnelc(exp(x))]
4-658
fresnelc
syms x
diff(fresnelc(x),x,3)
ans =
- pi*sin((pi*x^2)/2) - x^2*pi^2*cos((pi*x^2)/2)
Find the limit of the Fresnel cosine integral function as x tends to infinity:
4-659
4 Functions Alphabetical List
syms x
limit(fresnelc(x),Inf)
ans =
1/2
ans =
x - (x^5*pi^2)/40
ans =
fresnelc(x)
Input Arguments
z Upper limit on Fresnel cosine integral
numeric value | vector | matrix | multidimensional array | symbolic variable | symbolic
expression | symbolic vector | symbolic matrix | symbolic function
Upper limit on the Fresnel cosine integral, specified as a numeric value, vector, matrix,
or as a multidimensional array, or a symbolic variable, expression, vector, matrix, or
function.
More About
Fresnel Cosine Integral
4-660
fresnelc
z p t2
fresnelc ( z ) = 0 cos dt.
2
Algorithms
fresnelc returns special values for z = 0, z = , and z = i which are 0, 5, and 0.5i.
fresnelc(z) returns symbolic function calls for all other symbolic values of z.
See Also
erf | fresnels
Introduced in R2014a
4-661
4 Functions Alphabetical List
fresnels
Fresnel sine integral function
Syntax
fresnels(z)
Description
fresnels(z) returns the Fresnel sine integral of z.
Examples
Fresnel Sine Integral Function for Numeric and Symbolic Arguments
Find the Fresnel sine integral function for these numbers. Since these are not symbolic
objects, you receive floating-point results.
fresnels([-2 0.001 1.22+0.31i])
ans =
-0.3434 + 0.0000i 0.0000 + 0.0000i 0.7697 + 0.2945i
Find the Fresnel sine integral function symbolically by converting the numbers to
symbolic objects:
y = fresnels(sym([-2 0.001 1.22+0.31i]))
y =
[ -fresnels(2), fresnels(1/1000), fresnels(61/50 + 31i/100)]
4-662
fresnels
ans(x) =
fresnels(2*x + exp(x))
ans =
[ fresnels(sin(x)), fresnels(2i), -fresnels(7)]
ans =
[ 0, fresnels(2)]
[ fresnels(1i), fresnels(exp(x))]
4-663
4 Functions Alphabetical List
syms x
diff(fresnels(x),x,4)
ans =
- 3*x*pi^2*sin((pi*x^2)/2) - x^3*pi^3*cos((pi*x^2)/2)
Find the limit of the Fresnel sine integral function as x tends to infinity:
4-664
fresnels
syms x
limit(fresnels(x),Inf)
ans =
1/2
ans =
(pi*x^3)/6
ans =
fresnels(x)
Input Arguments
z Upper limit on the Fresnel sine integral
numeric value | vector | matrix | multidimensional array | symbolic variable | symbolic
expression | symbolic vector | symbolic matrix | symbolic function
Upper limit on the Fresnel sine integral, specified as a numeric value, vector, matrix, or a
multidimensional array or as a symbolic variable, expression, vector, matrix, or function.
More About
Fresnel Sine Integral
4-665
4 Functions Alphabetical List
z p t2
fresnels( z) =
0
sin
2
dt
Algorithms
See Also
erf | fresnelc
Introduced in R2014a
4-666
fsurf
fsurf
Plot 3-D surface
Syntax
fsurf(f)
fsurf(f,[min max])
fsurf(f,[xmin xmax ymin ymax])
fsurf(funx,funy,funz)
fsurf(funx,funy,funz,[uvmin uvmax])
fsurf(funx,funy,funz,[umin umax vmin vmax])
Description
fsurf(f) creates a surface plot of the symbolic expression f(x,y) over the default
interval [-5 5] for x and y.
fsurf(f,[min max]) plots f(x,y) over the interval [min max] for x and y.
fsurf(f,[xmin xmax ymin ymax]) plots f(x,y) over the interval [xmin xmax] for
x and [ymin ymax] for y.
4-667
4 Functions Alphabetical List
fsurf( ___ ,LineSpec) uses LineSpec to set the line style, marker symbol, and face
color.
fsurf( ___ ,Name,Value) specifies line properties using one or more Name,Value pair
arguments. Use this option with any of the input argument combinations in the previous
syntaxes.
fsurf(ax, ___ ) plots into the axes with the object ax instead of the current axes object
gca.
Examples
syms x y
fsurf(sin(x)+cos(y))
4-668
fsurf
syms f(x,y)
f(x,y) = real(atan(x + i*y));
fsurf(f)
4-669
4 Functions Alphabetical List
syms x y
f = sin(x) + cos(y);
fsurf(f, [-pi pi -5 5])
4-670
fsurf
for and .
4-671
4 Functions Alphabetical List
syms s t
r = 2 + sin(7*s + 5*t);
x = r*cos(s)*sin(t);
y = r*sin(s)*sin(t);
z = r*cos(t);
fsurf(x, y, z, [0 2*pi 0 pi])
camlight
view(46,52)
For and from to , plot the 3-D surface . Add a title and axis
labels.
4-672
fsurf
Create the x-axis ticks by spanning the x-axis limits at intervals of pi/2. Convert the
axis limits to precise multiples of pi/2 by using round and get the symbolic tick values
in S. Display these ticks by using the XTick property. Create x-axis labels by using
arrayfun to apply texlabel to S. Display these labels by using the XTickLabel
property. Repeat these steps for the y-axis.
syms x y
fsurf(y.*sin(x)-x.*cos(y), [-2*pi 2*pi])
title('ysin(x) - xcos(y) for x and y in [-2\pi,2\pi]')
xlabel('x')
ylabel('y')
zlabel('z')
ax = gca;
S = sym(ax.XLim(1):pi/2:ax.XLim(2));
S = sym(round(vpa(S/pi*2))*pi/2);
ax.XTick = double(S);
ax.XTickLabel = arrayfun(@texlabel,S,'UniformOutput',false);
S = sym(ax.YLim(1):pi/2:ax.YLim(2));
S = sym(round(vpa(S/pi*2))*pi/2);
ax.YTick = double(S);
ax.YTickLabel = arrayfun(@texlabel,S,'UniformOutput',false);
4-673
4 Functions Alphabetical List
syms s t
fsurf(s*sin(t),-s*cos(t),t,[-5 5 -5 -2],'--.','MarkerEdgeColor','g')
hold on
fsurf(s*sin(t),-s*cos(t),t,[-5 5 -2 2],'LineWidth',1,'FaceColor','g')
fsurf(s*sin(t),-s*cos(t),t,[-5 5 2 5],'EdgeColor','none')
4-674
fsurf
syms u v
4-675
4 Functions Alphabetical List
x = exp(-abs(u)/10).*sin(5*abs(v));
y = exp(-abs(u)/10).*cos(5*abs(v));
z = u;
fs = fsurf(x,y,z)
fs =
4-676
fsurf
Change the range of u to [-30 30] by using the URange property of fs. Set the the line
color to blue by using the EdgeColor property and specify white, dot markers by using
the Marker and MarkerEdgeColor properties.
4-677
4 Functions Alphabetical List
Plot the planes and using vector input to fsurf. Show both planes by
making them half transparent using FaceAlpha.
syms x y
h = fsurf([x+y x-y]);
4-678
fsurf
h(1).FaceAlpha = 0.5;
h(2).FaceAlpha = 0.5;
title('Planes (x+y) and (x-y) at half transparency')
Divide a figure into two using subplot. In the first subplot, plot the parametric surface
, , and . The surface has a large gap. Fix this
4-679
4 Functions Alphabetical List
issue by increasing the 'MeshDensity' to 40 in the second subplot. fsurf fills the gap
showing that by increasing 'MeshDensity' you increased the plot's resolution.
syms s t
subplot(2,1,1)
fsurf(sin(s), cos(s), t/10.*sin(1./s))
view(-172,25)
title('Default MeshDensity = 35')
subplot(2,1,2)
fsurf(sin(s), cos(s), t/10.*sin(1./s),'MeshDensity',40)
view(-172,25)
title('Increased MeshDensity = 40')
4-680
fsurf
syms x y
f = 3*(1-x)^2*exp(-(x^2)-(y+1)^2)...
- 10*(x/5 - x^3 - y^5)*exp(-x^2-y^2)...
- 1/3*exp(-(x+1)^2 - y^2);
fsurf(f,[-3 3],'ShowContours','on')
4-681
4 Functions Alphabetical List
x = t sin ( s)
y = cos ( s)
i
z = sin .
s
4-682
fsurf
4-683
4 Functions Alphabetical List
syms x y
f = 3*(1-x)^2*exp(-(x^2)-(y+1)^2)...
- 10*(x/5 - x^3 - y^5)*exp(-x^2-y^2)...
- 1/3*exp(-(x+1)^2 - y^2);
h = fsurf(f,[-3 3]);
camlight(110,70)
brighten(0.6)
h.EdgeColor = 'none';
h.AmbientStrength = 0.4;
a = gca;
a.TickLabelInterpreter = 'latex';
a.Box = 'on';
a.BoxStyle = 'full';
xlabel('$x$','Interpreter','latex')
ylabel('$y$','Interpreter','latex')
zlabel('$z$','Interpreter','latex')
title_latex = ['$' latex(f) '$'];
title(title_latex,'Interpreter','latex')
4-684
fsurf
Input Arguments
f 3-D expression or function to be plotted
symbolic expression | symbolic function
Plotting interval for x- and y-axes, specified as a vector of two numbers. The default is
[-5 5].
4-685
4 Functions Alphabetical List
Plotting interval for x- and y-axes, specified as a vector of four numbers. The default is
[-5 5 -5 5].
Plotting interval for u and v axes, specified as a vector of two numbers. The default is
[-5 5].
Plotting interval for u and v, specified as a vector of four numbers. The default is [-5 5
-5 5].
ax Axes object
axes object
Axes object. If you do not specify an axes object, then fsurf uses the current axes.
Line style, marker symbol, and color, specified as a character vector. The elements of the
character vector can appear in any order, and you can omit one or more options from the
character vector specifier.
Example: '--or' is a red surface with circle markers and dashed lines
4-686
fsurf
Specifier Marker
o Circle
+ Plus sign
* Asterisk
. Point
x Cross
s Square
d Diamond
^ Upward-pointing triangle
v Downward-pointing triangle
> Right-pointing triangle
< Left-pointing triangle
p Pentagram
h Hexagram
Specifier Color
y yellow
m magenta
c cyan
r red
g green
b blue
w white
k black
4-687
4 Functions Alphabetical List
Example: 'Marker','o','MarkerFaceColor','red'
The properties listed here are only a subset. For a complete list, see Function Surface
Properties.
Number of evaluation points per direction, specified as a number. The default is 35.
Because fsurf uses adaptive evaluation, the actual number of evaluation points is
greater.
Example: 100
An RGB triplet is a three-element row vector whose elements specify the intensities of
the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. This table lists the long and short color name
options and the equivalent RGB triplet values.
4-688
fsurf
Line style, specified as one of the line styles listed in this table.
Line width, specified as a positive value in points. If the line has markers, then the line
width also affects the marker edges.
Example: 0.75
Marker symbol, specified as one of the values in this table. By default, a line does not
have markers. Add markers at selected points along the line by specifying a marker.
Value Description
'o' Circle
'+' Plus sign
4-689
4 Functions Alphabetical List
Value Description
'*' Asterisk
'.' Point
'x' Cross
'square' or 's' Square
'diamond' or 'd' Diamond
'^' Upward-pointing triangle
'v' Downward-pointing triangle
'>' Right-pointing triangle
'<' Left-pointing triangle
'pentagram' or 'p' Five-pointed star (pentagram)
'hexagram' or 'h' Six-pointed star (hexagram)
'none' No markers
An RGB triplet is a three-element row vector whose elements specify the intensities of
the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. This table lists the long and short color name
options and the equivalent RGB triplet values.
4-690
fsurf
An RGB triplet is a three-element row vector whose elements specify the intensities of
the red, green, and blue components of the color. The intensities must be in the range
[0,1]; for example, [0.4 0.6 0.7]. This table lists the long and short color name
options and the equivalent RGB triplet values.
4-691
4 Functions Alphabetical List
Example: 'green'
Output Arguments
fs One or more objects
scalar | vector
One or more objects, returned as a scalar or a vector. The object is either a function
surface object or parameterized surface object, depending on the type of plot. You can use
these objects to query and modify properties of a specific line. For details, see Function
Surface Properties and Parameterized Function Surface Properties.
More About
Create Plots on page 2-208
See Also
Functions
fcontour | fimplicit | fimplicit3 | fmesh | fplot | fplot3
Properties
Function Surface Properties | Parameterized Function Surface Properties
Introduced in R2016a
4-692
functionalDerivative
functionalDerivative
Functional derivative
Syntax
D = functionalDerivative(f,y)
Description
D = functionalDerivative(f,y) returns the Functional Derivative on page
4-697 of the functional F = f ( x, y ( x) , y ( x) ...) dx with respect to the function
y=y(x), where x represents one or more independent variables. If y is a vector of
symbolic functions, functionalDerivative returns a vector of functional derivatives
with respect to the functions in y, where all functions in y must depend on the same
independent variables.
Examples
Find the functional derivative of the function given by f ( y) = y ( x ) sin ( y ( x) ) with respect
to the function y.
syms y(x)
f = y*sin(y);
D = functionalDerivative(f,y)
D(x) =
sin(y(x)) + cos(y(x))*y(x)
4-693
4 Functions Alphabetical List
dv d 2u
Find the functional derivative of the function given by H ( u, v ) = u2 +v with
dx dx2
respect to the functions u and v.
D(x) =
2*u(x)*diff(v(x), x) + diff(v(x), x, x)
diff(u(x), x, x) - 2*u(x)*diff(u(x), x)
syms m k x(t)
T = sym(1)/2*m*diff(x,t)^2;
V = sym(1)/2*k*x^2;
L = T - V
L(t) =
(m*diff(x(t), t)^2)/2 - (k*x(t)^2)/2
Find the Euler-Lagrange equation by finding the functional derivative of L with respect
to x, and equate it to 0.
eqn = functionalDerivative(L,x) == 0
eqn(t) =
- m*diff(x(t), t, t) - k*x(t) == 0
4-694
functionalDerivative
Solve eqn using dsolve. Obtain the expected form of the solution by assuming mass m
and spring constant k are positive.
assume(m,'positive')
assume(k,'positive')
xSol = dsolve(eqn,x(0) == 0)
xSol =
C5*sin((k^(1/2)*t)/m^(1/2))
assume([k m],'clear')
1 + y 2
f = ,
2 gy
Find the quickest path by minimizing f with respect to the path y. The condition for a
minimum is
df
= 0.
dy
Compute this condition to obtain the differential equation that describes the
Brachistochrone problem. Use simplify to simplify the solution to its expected form.
syms g y(x)
assume(g,'positive')
f = sqrt((1+diff(y)^2)/(2*g*y));
eqn = functionalDerivative(f,y) == 0;
eqn = simplify(eqn)
eqn(x) =
diff(y(x), x)^2 + 2*y(x)*diff(y(x), x, x) == -1
4-695
4 Functions Alphabetical List
This equation is the standard differential equation for the Brachistochrone problem.
Find the equation that describes the minimal surface for a 3-D surface described by the
function u(x,y) by finding the functional derivative of f with respect to u.
syms u(x,y)
f = sqrt(1 + diff(u,x)^2 + diff(u,y)^2);
D = functionalDerivative(f,u)
D(x, y) =
-(diff(u(x, y), y)^2*diff(u(x, y), x, x)...
+ diff(u(x, y), x)^2*diff(u(x, y), y, y)...
- 2*diff(u(x, y), x)*diff(u(x, y), y)*diff(u(x, y), x, y)...
+ diff(u(x, y), x, x)...
+ diff(u(x, y), y, y))/(diff(u(x, y), x)^2...
+ diff(u(x, y), y)^2 + 1)^(3/2)
The solutions to this equation D describe minimal surfaces in 3-D space such as soap
bubbles.
Input Arguments
f Expression to find functional derivative of
symbolic variable | symbolic function | symbolic expression
y Differentiation function
symbolic function | vector of symbolic functions | matrix of symbolic functions |
multidimensional array of symbolic functions
4-696
functionalDerivative
Output Arguments
D Functional derivative
symbolic function | vector of symbolic functions
More About
Functional Derivative
Consider functionals
F ( y) = f ( x, y ( x ), y ( x ), y ( x ),...) dx,
W
dF d d f ( x)
= F ( y + ed y) = d y ( x) dx + boundary terms.
d y de e =0 dy
W
d f ( x)
The expression is the functional derivative of f with respect to y.
dy
See Also
diff | dsolve | int
4-697
4 Functions Alphabetical List
Introduced in R2015a
4-698
funm
funm
General matrix function
Syntax
F = funm(A,f)
Description
F = funm(A,f) computes the function f(A) for the square matrix A. For details, see
Matrix Function on page 4-704.
Examples
Matrix Cube Root
Find matrix B, such that B = A, where A is a 3-by-3 identity matrix.
3
To solve B = A, compute the cube root of the matrix A using the funm function. Create
3
the symbolic function f(x) = x^(1/3) and use it as the second argument for funm. The
cube root of an identity matrix is the identity matrix itself.
A = sym(eye(3))
syms f(x)
f(x) = x^(1/3);
B = funm(A,f)
A =
[ 1, 0, 0]
[ 0, 1, 0]
[ 0, 0, 1]
B =
[ 1, 0, 0]
4-699
4 Functions Alphabetical List
[ 0, 1, 0]
[ 0, 0, 1]
Replace one of the 0 elements of matrix A with 1 and compute the matrix cube root again.
A(1,2) = 1
B = funm(A,f)
A =
[ 1, 1, 0]
[ 0, 1, 0]
[ 0, 0, 1]
B =
[ 1, 1/3, 0]
[ 0, 1, 0]
[ 0, 0, 1]
A =
[ 1, 1, 1]
[ 0, 1, 1]
[ 0, 0, 1]
B =
[ 1, 1/3, 2/9]
[ 0, 1, 1/3]
[ 0, 0, 1]
Verify that B = A.
3
B^3
ans =
[ 1, 1, 1]
[ 0, 1, 1]
[ 0, 0, 1]
4-700
funm
First, create a 3-by-3 matrix A using variable-precision arithmetic with five digit
accuracy. In this example, using variable-precision arithmetic instead of exact symbolic
numbers lets you speed up computations and decrease memory usage. Using only five
digits helps the result to fit on screen.
savedefault = digits(5);
A = vpa(magic(3))
A =
[ 8.0, 1.0, 6.0]
[ 3.0, 5.0, 7.0]
[ 4.0, 9.0, 2.0]
syms f(x)
f(x) = lambertw(x);
To find the Lambert W function (W0 branch) in a matrix sense, callfunm using f(x) as its
second argument.
W0 = funm(A,f)
W0 =
[ 1.5335 + 0.053465i, 0.11432 + 0.47579i, 0.36208 - 0.52925i]
[ 0.21343 + 0.073771i, 1.3849 + 0.65649i, 0.41164 - 0.73026i]
[ 0.26298 - 0.12724i, 0.51074 - 1.1323i, 1.2362 + 1.2595i]
Verify that this result is a solution of the matrix equation A = W0e within the
W0
specified accuracy.
W0*expm(W0)
ans =
[ 8.0, 1.0 - 5.6843e-13i, 6.0 + 1.1369e-13i]
[ 3.0 - 2.2737e-13i, 5.0 - 2.8422e-14i, 7.0 - 4.1211e-13i]
[ 4.0 - 2.2737e-13i, 9.0 - 9.9476e-14i, 2.0 + 1.4779e-12i]
Now, create the symbolic function f(x) representing the branch W-1 of the Lambert W
function.
f(x) = lambertw(-1,x);
4-701
4 Functions Alphabetical List
Wm1 = funm(A,f)
Wm1 =
[ 0.40925 - 4.7154i, 0.54204 + 0.5947i, 0.13764 - 0.80906i]
[ 0.38028 + 0.033194i, 0.65189 - 3.8732i, 0.056763 - 1.0898i]
[ 0.2994 - 0.24756i, - 0.105 - 1.6513i, 0.89453 - 3.0309i]
Verify that this result is the solution of the matrix equation A = Wm1e within the
Wm1
specified accuracy.
Wm1*expm(Wm1)
ans =
[ 8.0 - 8.3844e-13i, 1.0 - 3.979e-13i, 6.0 - 9.0949e-13i]
[ 3.0 - 9.6634e-13i, 5.0 + 1.684e-12i, 7.0 + 4.5475e-13i]
[ 4.0 - 1.3642e-12i, 9.0 + 1.6698e-12i, 2.0 + 1.7053e-13i]
Create this square matrix and find its exponential, logarithm, and square root.
syms x
A = [1 -1; 0 x]
expA = expm(A)
logA = logm(A)
sqrtA = sqrtm(A)
A =
[ 1, -1]
[ 0, x]
expA =
[ exp(1), (exp(1) - exp(x))/(x - 1)]
[ 0, exp(x)]
logA =
[ 0, -log(x)/(x - 1)]
[ 0, log(x)]
sqrtA =
4-702
funm
Find the matrix exponential, logarithm, and square root of A using funm. Use the
symbolic expressions exp(x), log(x), and sqrt(x) as the second argument of funm.
The results are identical.
expA = funm(A,exp(x))
logA = funm(A,log(x))
sqrtA = funm(A,sqrt(x))
expA =
[ exp(1), exp(1)/(x - 1) - exp(x)/(x - 1)]
[ 0, exp(x)]
logA =
[ 0, -log(x)/(x - 1)]
[ 0, log(x)]
sqrtA =
[ 1, 1/(x - 1) - x^(1/2)/(x - 1)]
[ 0, x^(1/2)]
Input Arguments
A Input matrix
square matrix
f Function
symbolic function | symbolic expression
Output Arguments
F Resulting matrix
symbolic matrix
4-703
4 Functions Alphabetical List
More About
Matrix Function
Suppose, f(x), where x is a scalar, has a Taylor series expansion. Then the matrix
function f(A), where A is a matrix, is defined by the Taylor series of f(A), with addition
and multiplication performed in the matrix sense.
d1 L 0
D= M O M
0 L d
n
f ( d1 ) L 0
f ( A) = P M O M P -1
0 L f ( dn )
form of the matrix A. Then, the matrix function f(A) can be computed by using the
following definition on each Jordan block:
f (l ) ( )
f (l ) f (l ) f n-1 ( l )
L
0! 1! 2! (n - 1)!
l 1 0 L 0 0 O O O M
0 O O O M
f ( l )
f M O O O 0 = M O O O
2!
M O O O 1 f (l )
0 M O O O
L L 0 l 1!
0 f (l )
L L 0
0!
4-704
funm
Tips
For compatibility with the MATLAB funm function, funm accepts the following
arguments:
Function handles such as @exp and @sin, as its second input argument.
The options input argument, such as funm(A,f,options).
Additional input arguments of the function f, such as
funm(A,f,options,p1,p2,...)
The exitflag output argument, such as [F,exitflag] = funm(A,f). Here,
exitflag is 1 only if the funm function call errors, for example, if it encounters a
division by zero. Otherwise, exitflag is 0.
For more details and a list of all acceptable function handles, see the MATLAB funm
function.
If the input matrix A is numeric (not a symbolic object) and the second argument f is
a function handle, then the funm call invokes the MATLAB funm function.
See Also
eig | expm | jordan | logm | sqrtm
Introduced in R2014b
4-705
4 Functions Alphabetical List
funtool
Function calculator
Syntax
funtool
Description
funtool is a visual function calculator that manipulates and displays functions of one
variable. At the click of a button, for example, funtool draws a graph representing the
sum, product, difference, or ratio of two functions that you specify. funtool includes a
function memory that allows you to store functions for later retrieval.
4-706
funtool
Text Fields
The top of the control panel contains a group of editable text fields.
4-707
4 Functions Alphabetical List
funtool redraws f and g to reflect any changes you make to the contents of the control
panel's text fields.
Control Buttons
The bottom part of the control panel contains an array of buttons that transform f and
perform other operations.
df/dx Derivative of f
int f Integral of f
simplify f Simplified form of f, if possible
num f Numerator of f
den f Denominator of f
1/f Reciprocal of f
finv Inverse of f
The operators int f and finv can fail if the corresponding symbolic expressions do not
exist in closed form.
The second row of buttons translates and scales f and the domain of f by a constant
factor. To specify the factor, enter its value in the field labeled a= on the calculator
control panel. The operations are
4-708
funtool
The first four buttons of the third row replace f with a combination of f and g.
The first three buttons in the fourth row allow you to store and retrieve functions from
the calculator's function memory.
The other four buttons on the fourth row perform miscellaneous functions:
See Also
fplot | syms
4-709
4 Functions Alphabetical List
gamma
Gamma function
Syntax
gamma(X)
Description
gamma(X) returns the gamma function of a symbolic variable or symbolic expression X.
Examples
Compute the gamma function for these numbers. Because these numbers are not
symbolic objects, you get floating-point results.
A =
0.2466 2.6593 -3.5449 2.6789 1.0000 6.0000
Compute the gamma function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, gamma returns unresolved symbolic calls.
symA =
[ (27*pi*3^(1/2))/(440*gamma(2/3)), gamma(-7/5),...
-2*pi^(1/2), (2*pi*3^(1/2))/(3*gamma(2/3)), 1, 6]
4-710
gamma
vpa(symA)
ans =
[ 0.24658411512650858900694446388517,...
2.6592718728800305399898810505738,...
-3.5449077018110320545963349666823,...
2.6789385347077476336556929409747,...
1.0, 6.0]
syms x
fplot(gamma(x))
grid on
4-711
4 Functions Alphabetical List
Differentiate the gamma function, and then substitute the variable t with the value 1:
syms t
u = diff(gamma(t^3 + 1))
u1 = subs(u, t, 1)
u =
3*t^2*gamma(t^3 + 1)*psi(t^3 + 1)
4-712
gamma
u1 =
3 - 3*eulergamma
vpa(u1)
ans =
1.2683530052954014181804637297528
Compute the limit of the following expression that involves the gamma function:
syms x
limit(x/gamma(x), x, inf)
ans =
0
syms x
simplify(gamma(x)*gamma(1 - x))
ans =
pi/sin(pi*x)
Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
More About
Gamma Function
4-713
4 Functions Alphabetical List
G ( z ) = t z-1e- t dt.
0
See Also
beta | factorial | gammaln | igamma | nchoosek | pochhammer | psi
4-714
gammaln
gammaln
Logarithmic gamma function
Syntax
gammaln(X)
Description
gammaln(X) returns the logarithmic gamma function for each element of X.
Examples
Compute the logarithmic gamma function for these numbers. Because these numbers are
not symbolic objects, you get floating-point results.
A =
1.5241 0.5724 0.3032 -0.0667 0.6931
Compute the logarithmic gamma function for the numbers converted to symbolic objects.
For many symbolic (exact) numbers, gammaln returns results in terms of the gammaln,
log, and gamma functions.
symA =
[ gammaln(1/5), log(pi^(1/2)), gammaln(2/3),...
log(gamma(1/7)/7), log(2)]
4-715
4 Functions Alphabetical List
vpa(symA)
ans =
[ 1.5240638224307845248810564939263,...
0.57236494292470008707171367567653,...
0.30315027514752356867586281737201,...
-0.066740877459477468649396334098109,...
0.69314718055994530941723212145818]
Compute the logarithmic gamma function for positive integer arguments. For such
arguments, the logarithmic gamma function is defined as the natural logarithm of the
gamma function, gammaln(x) = log(gamma(x)).
pos = gammaln(sym([1/4, 1/3, 1, 5, Inf]))
pos =
[ log((pi*2^(1/2))/gamma(3/4)), log((2*pi*3^(1/2))/(3*gamma(2/3))), 0, log(24), Inf]
Compute the logarithmic gamma function for nonpositive integer arguments. For
nonpositive integers, gammaln returns Inf.
nonposint = gammaln(sym([0, -1, -2, -5, -10]))
nonposint =
[ Inf, Inf, Inf, Inf, Inf]
Compute the logarithmic gamma function for complex and negative rational arguments.
For these arguments, gammaln returns unresolved symbolic calls.
complex = gammaln(sym([i, -1 + 2*i , -2/3, -10/3]))
complex =
[ gammaln(1i), gammaln(- 1 + 2i), gammaln(-2/3), gammaln(-10/3)]
4-716
gammaln
ans =
NaN
4-717
4 Functions Alphabetical List
To see the negative values better, plot the same function on the interval from 1 to 2.
fplot(gammaln(x), [1 2])
grid on
syms x
diff(gammaln(x), x)
4-718
gammaln
ans =
psi(x)
Compute the limits of these expressions containing the logarithmic gamma function:
syms x
limit(1/gammaln(x), x, Inf)
ans =
0
ans =
log(2) + pi*1i
Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
More About
Algorithms
gammaln(x) is defined for all complex x except the singular points 0, -1, -2, ... .
For positive real x, gammaln(x) represents the logarithmic gamma function
log(gamma(x)).
For negative real x or for complex x, gammaln(x) = log(gamma(x)) + f(x)2i where f(x)
is some integer valued function. The integer multiples of 2i are chosen such that
gammaln(x) is analytic throughout the complex plane with a branch cut along the
negative real semi axis.
4-719
4 Functions Alphabetical List
See Also
beta | gamma | log | nchoosek | psi
Introduced in R2014a
4-720
gcd
gcd
Greatest common divisor
Syntax
G = gcd(A)
G = gcd(A,B)
[G,C,D] = gcd(A,B,X)
Description
G = gcd(A) finds the greatest common divisor of all elements of A.
[G,C,D] = gcd(A,B,X) finds the greatest common divisor of A and B, and also returns
the Bzout coefficients, C and D, such that G = A*C + B*D, and X does not appear in
the denominator of Cand D. If you do not specify X, then gcd uses the default variable
determined by symvar.
Examples
Find the greatest common divisor of these four integers, specified as elements of a
symbolic vector.
A =
4-721
4 Functions Alphabetical List
ans =
4
A =
[ 4420, -128]
[ 8984, -488]
ans =
4
Find the greatest common divisor of these rational numbers, specified as elements of a
symbolic vector.
ans =
1/12
ans =
5 + 10i
4-722
gcd
Find the greatest common divisors for the elements of these two matrices.
ans =
[ 3, 6]
[ 2, 32]
Find the greatest common divisors for the elements of matrix A and the value 200. Here,
gcd expands 200 into the 2-by-2 matrix with all elements equal to 200.
gcd(A,200)
ans =
[ 1, 2]
[ 2, 8]
syms x
gcd(x^3 - 3*x^2 + 3*x - 1, x^2 - 5*x + 4)
ans =
x - 1
Find the greatest common divisor of these multivariate polynomials. Because there are
more than two polynomials, specify them as elements of a symbolic vector.
syms x y
gcd([x^2*y + x^3, (x + y)^2, x^2 + x*y^2 + x*y + x + y^3 + y])
ans =
4-723
4 Functions Alphabetical List
x + y
Bzout Coefficients
Find the greatest common divisor and the Bzout coefficients of these polynomials.
For multivariate expressions, use the third input argument to specify the polynomial
variable. When computing Bzout coefficients, gcd ensures that the polynomial variable
does not appear in their denominators.
Find the greatest common divisor and the Bzout coefficients of these polynomials with
respect to variable x.
G =
x + y
C =
1/y^2
D =
1/y - x/y^2
Find the greatest common divisor and the Bzout coefficients of the same polynomials
with respect to variable y.
G =
x + y
C =
1/x^2
D =
0
If you do not specify the polynomial variable, then the toolbox uses symvar to determine
the variable.
G =
4-724
gcd
x + y
C =
1/y^2
D =
1/y - x/y^2
Find the greatest common divisor and a pair of Bzout coefficients for 30 and 56.
[G,C,D] = gcd(sym(30),56)
G =
2
C =
-13
D =
7
Rewrite Bzout's identity so that it looks more like the original equation. Do this by
multiplying by 4. Use == to verify that both sides of the equation are equal.
ans =
logical
1
x = C*4
y = D*4
x =
-52
4-725
4 Functions Alphabetical List
y =
28
Input Arguments
A Input value
number | symbolic number | symbolic variable | symbolic expression | symbolic
function | symbolic vector | symbolic matrix
B Input value
number | symbolic number | symbolic variable | symbolic expression | symbolic
function | symbolic vector | symbolic matrix
X Polynomial variable
symbolic variable
Output Arguments
G Greatest common divisor
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
4-726
gcd
More About
Tips
Calling gcd for numbers that are not symbolic objects invokes the MATLAB gcd
function.
The MATLAB gcd function does not accept rational or complex arguments. To find
the greatest common divisor of rational or complex numbers, convert these numbers
to symbolic objects by using sym, and then use gcd.
Nonscalar arguments must be the same size. If one input argument is nonscalar,
then gcd expands the scalar into a vector or matrix of the same size as the nonscalar
argument, with all elements equal to the corresponding scalar.
See Also
lcm
Introduced in R2014b
4-727
4 Functions Alphabetical List
ge
Define greater than or equal to relation
Compatibility
In previous releases, ge in some cases evaluated inequalities involving only symbolic
numbers and returned logical 1 or 0. To obtain the same results as in previous releases,
wrap inequalities in isAlways. For example, use isAlways(A >= B).
Syntax
A >= B
ge(A,B)
Description
A >= B creates a greater than or equal to relation.
Input Arguments
A
4-728
ge
Examples
Use assume and the relational operator >= to set the assumption that x is greater than
or equal to 3:
syms x
assume(x >= 3)
Solve this equation. The solver takes into account the assumption on variable x, and
therefore returns these two solutions.
solve((x - 1)*(x - 2)*(x - 3)*(x - 4) == 0, x)
ans =
3
4
for i = 0:sym(pi/12):sym(pi)
if subs(cond, x, i)
disp(i)
end
end
Use the for loop with step /24 to find angles from 0 to that satisfy that condition:
pi/6
pi/4
pi/3
(5*pi)/12
pi/2
(7*pi)/12
(2*pi)/3
(3*pi)/4
(5*pi)/6
Alternatives
You can also define this relation by combining an equation and a greater than relation.
Thus, A >= B is equivalent to (A > B) | (A == B).
4-729
4 Functions Alphabetical List
More About
Tips
Calling >= or ge for non-symbolic A and B invokes the MATLAB ge function. This
function returns a logical array with elements set to logical 1 (true) where A is
greater than or equal to B; otherwise, it returns logical 0 (false).
If both A and B are arrays, then these arrays must have the same dimensions. A >= B
returns an array of relations A(i,j,...) >= B(i,j,...)
If one input is scalar and the other an array, then the scalar input is expanded into
an array of the same dimensions as the other array. In other words, if A is a variable
(for example, x), and B is an m-by-n matrix, then A is expanded into m-by-n matrix of
elements, each set to x.
The field of complex numbers is not an ordered field. MATLAB projects complex
numbers in relations to a real axis. For example, x >= i becomes x >= 0, and x >=
3 + 2*i becomes x >= 3.
See Also
eq | gt | isAlways | le | lt | ne
Introduced in R2012a
4-730
gegenbauerC
gegenbauerC
Gegenbauer polynomials
Syntax
gegenbauerC(n,a,x)
Description
gegenbauerC(n,a,x) represents the nth-degree Gegenbauer (ultraspherical)
polynomial with parameter a at the point x.
Examples
syms a x
gegenbauerC([0, 1, 2, 3], a, x)
ans =
[ 1, 2*a*x, (2*a^2 + 2*a)*x^2 - a,...
((4*a^3)/3 + 4*a^2 + (8*a)/3)*x^3 + (- 2*a^2 - 2*a)*x]
Find the value of the fifth-degree Gegenbauer polynomial for the parameter a = 1/3
at these points. Because these numbers are not symbolic objects, gegenbauerC returns
floating-point results.
4-731
4 Functions Alphabetical List
ans =
0.1520 0.1911 0.1914 0.0672 -0.1483 -0.2188
Find the value of the fifth-degree Gegenbauer polynomial for the same numbers
converted to symbolic objects. For symbolic numbers, gegenbauerC returns exact
symbolic results.
ans =
[ 26929/177147, 4459/23328, 33908/177147, 49/729, -26264/177147, -7/32]
Find the value of the 500th-degree Gegenbauer polynomial for the parameter 4 at 1/3
and vpa(1/3). Floating-point evaluation is numerically stable.
gegenbauerC(500, 4, 1/3)
gegenbauerC(500, 4, vpa(1/3))
ans =
-1.9161e+05
ans =
-191609.10250897532784888518393655
Now, find the symbolic polynomial C500 = gegenbauerC(500, 4, x), and substitute
x = vpa(1/3) into the result. This approach is numerically unstable.
syms x
C500 = gegenbauerC(500, 4, x);
subs(C500, x, vpa(1/3))
ans =
-8.0178726380235741521208852037291e35
4-732
gegenbauerC
subs(vpa(C500), x, sym(1/3))
ans =
-8.1125412405858470246887213923167e36
syms x y
fplot(gegenbauerC(0:4, 3, x))
axis([-1 1 -10 10])
grid on
ylabel('G_n^3(x)')
title('Gegenbauer polynomials')
legend('G_0^3(x)', 'G_1^3(x)', 'G_2^3(x)', 'G_3^3(x)', 'G_4^3(x)',...
'Location', 'Best')
4-733
4 Functions Alphabetical List
Input Arguments
n Degree of polynomial
nonnegative integer | symbolic variable | symbolic expression | symbolic function |
vector | matrix
4-734
gegenbauerC
a Parameter
number | symbolic number | symbolic variable | symbolic expression | symbolic
function | vector | matrix
x Evaluation point
number | symbolic number | symbolic variable | symbolic expression | symbolic
function | vector | matrix
More About
Gegenbauer Polynomials
2x ( n + a - 1) n + 2a - 2
G ( 0, a, x ) = 1, G (1, a, x) = 2 ax, G ( n, a, x ) = G ( n - 1, a, x ) - G ( n - 2, a, x )
n n
For all real a>-1/2, Gegenbauer polynomials are orthogonal on the interval -1x1
with respect to the weight function
1
a-
(
w ( x) = 1 - x2 ) 2
Chebyshev polynomials of the first and second kinds are a special case of the Gegenbauer
polynomials.
n
T ( n, x) = G ( n, 0, x )
2
U ( n, x) = G ( n,1, x )
4-735
4 Functions Alphabetical List
1
P ( n, x ) = G n, , x
2
Tips
gegenbauerC returns floating-point results for numeric arguments that are not
symbolic objects.
gegenbauerC acts element-wise on nonscalar inputs.
All nonscalar arguments must have the same size. If one or two input arguments are
nonscalar, then gegenbauerC expands the scalars into vectors or matrices of the
same size as the nonscalar arguments, with all elements equal to the corresponding
scalar.
References
[1] Hochstrasser,U.W. Orthogonal Polynomials. Handbook of Mathematical Functions
with Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A.
Stegun, eds.). New York: Dover, 1972.
See Also
chebyshevT | chebyshevU | hermiteH | jacobiP | laguerreL | legendreP
Introduced in R2014b
4-736
getVar
getVar
Get variable from MuPAD notebook
Syntax
MATLABvar = getVar(nb,'MuPADvar')
Description
MATLABvar = getVar(nb,'MuPADvar') assigns the variable MuPADvar in the
MuPAD notebook nb to a symbolic variable MATLABvar in the MATLAB workspace.
Examples
Copy Variable from MuPAD to MATLAB
Copy a variable with a value assigned to it from a MuPAD notebook to the MATLAB
workspace.
Create a new MuPAD notebook and specify a handle mpnb to that notebook:
mpnb = mupad;
In the MuPAD notebook, enter the following command. This command creates the
variable f and assigns the value x^2 to this variable. At this point, the variable and its
value exist only in MuPAD.
f := x^2
Return to the MATLAB Command Window and use the getVar function:
f = getVar(mpnb,'f')
f =
x^2
After you call getVar, the variable f appears in the MATLAB workspace. The value of
the variable f in the MATLAB workspace is x^2.
4-737
4 Functions Alphabetical List
Now, use getVar to copy variables a and b from the same notebook. Although you do not
specify these variables explicitly, and they do not have any values assigned to them, they
exist in MuPAD.
a = getVar(mpnb,'a')
b = getVar(mpnb,'b')
a =
a
b =
b
Copy Variables and Expressions Between MATLAB and MuPAD on page 3-51
Input Arguments
nb Pointer to MuPAD notebook
handle to notebook
Pointer to a MuPAD notebook, specified as a MuPAD notebook handle. You create the
notebook handle when opening a notebook with the mupad or openmn function.
Output Arguments
MATLABvar Variable in MATLAB workspace
symbolic variable
See Also
mupad | openmu | setVar
4-738
getVar
Introduced in R2008b
4-739
4 Functions Alphabetical List
gradient
Gradient vector of scalar function
Syntax
gradient(f,v)
Description
gradient(f,v) finds the gradient vector of the scalar function f with respect to vector
v in Cartesian coordinates.
If you do not specify v, then gradient(f) finds the gradient vector of the scalar function
f with respect to a vector constructed from all symbolic variables found in f. The order of
variables in this vector is defined by symvar.
Examples
Find the gradient vector of f(x, y, z) with respect to vector [x, y, z]. The gradient
is a vector with these components.
syms x y z
f = 2*y*z*sin(x) + 3*x*sin(z)*cos(y);
gradient(f, [x, y, z])
ans =
3*cos(y)*sin(z) + 2*y*z*cos(x)
2*z*sin(x) - 3*x*sin(y)*sin(z)
2*y*sin(x) + 3*x*cos(y)*cos(z)
4-740
gradient
Find the gradient vector of f(x, y) with respect to vector [x, y]. The gradient is
vector g with these components.
syms x y
f = -(sin(x) + sin(y))^2;
g = gradient(f, [x, y])
g =
-2*cos(x)*(sin(x) + sin(y))
-2*cos(y)*(sin(x) + sin(y))
Now plot the vector field defined by these components. MATLAB provides the quiver
plotting function for this task. The function does not accept symbolic arguments. First,
replace symbolic variables in expressions for components of g with numeric values. Then
use quiver:
[X, Y] = meshgrid(-1:.1:1,-1:.1:1);
G1 = subs(g(1), [x y], {X,Y});
G2 = subs(g(2), [x y], {X,Y});
quiver(X, Y, G1, G2)
4-741
4 Functions Alphabetical List
Input Arguments
f Scalar function
symbolic expression | symbolic function
4-742
gradient
Vector with respect to which you find gradient vector, specified as a symbolic vector. By
default, v is a vector constructed from all symbolic variables found in f. The order of
variables in this vector is defined by symvar.
More About
Gradient Vector
The gradient vector of f(x) with respect to the vector x is the vector of the first partial
derivatives of f.
f f f
f = , , ,
x1 x2 xn
See Also
curl | diff | divergence | hessian | jacobian | laplacian | potential |
quiver | vectorPotential
Introduced in R2011b
4-743
4 Functions Alphabetical List
gt
Define greater than relation
Compatibility
In previous releases, gt in some cases evaluated inequalities involving only symbolic
numbers and returned logical 1 or 0. To obtain the same results as in previous releases,
wrap inequalities in isAlways. For example, use isAlways(A > B).
Syntax
A > B
gt(A,B)
Description
A > B creates a greater than relation.
Input Arguments
A
Examples
Use assume and the relational operator > to set the assumption that x is greater than 3:
4-744
gt
syms x
assume(x > 3)
Solve this equation. The solver takes into account the assumption on variable x, and
therefore returns this solution.
solve((x - 1)*(x - 2)*(x - 3)*(x - 4) == 0, x)
ans =
4
syms x
cond = abs(sin(x)) + abs(cos(x)) > 7/5;
for i = 0:sym(pi/24):sym(pi)
if subs(cond, x, i)
disp(i)
end
end
Use the for loop with step /24 to find angles from 0 to that satisfy that condition:
(5*pi)/24
pi/4
(7*pi)/24
(17*pi)/24
(3*pi)/4
(19*pi)/24
More About
Tips
Calling > or gt for non-symbolic A and B invokes the MATLAB gt function. This
function returns a logical array with elements set to logical 1 (true) where A is
greater than B; otherwise, it returns logical 0 (false).
If both A and B are arrays, then these arrays must have the same dimensions. A > B
returns an array of relations A(i,j,...) > B(i,j,...)
If one input is scalar and the other an array, then the scalar input is expanded into
an array of the same dimensions as the other array. In other words, if A is a variable
4-745
4 Functions Alphabetical List
(for example, x), and B is an m-by-n matrix, then A is expanded into m-by-n matrix of
elements, each set to x.
The field of complex numbers is not an ordered field. MATLAB projects complex
numbers in relations to a real axis. For example, x > i becomes x > 0, and x > 3
+ 2*i becomes x > 3.
See Also
eq | ge | isAlways | le | lt | ne
Introduced in R2012a
4-746
harmonic
harmonic
Harmonic function (harmonic number)
Syntax
harmonic(x)
Description
harmonic(x) returns the harmonic function of x. For integer values of x, harmonic(x)
generates harmonic numbers.
Examples
harmonic(sym(1:10))
ans =
[ 1, 3/2, 11/6, 25/12, 137/60, 49/20, 363/140, 761/280, 7129/2520, 7381/2520]
harmonic([2 i 13/3])
ans =
1.5000 + 0.0000i 0.6719 + 1.0767i 2.1545 + 0.0000i
Find the harmonic function symbolically by converting the numbers to symbolic objects.
4-747
4 Functions Alphabetical List
y = harmonic(sym([2 i 13/3]))
y =
[ 3/2, harmonic(1i), 8571/1820 - (pi*3^(1/2))/6 - (3*log(3))/2]
If the denominator of x is 2, 3, 4, or 6, and |x| < 500, then the result is expressed in
terms of pi and log.
vpa(y)
ans =
[ 1.5, 0.67186598552400983787839057280431...
+ 1.07667404746858117413405079475i,...
2.1545225442213858782694336751358]
For |x| > 1000, harmonic returns the function call as it is. Use vpa to force harmonic
to evaluate the function call.
harmonic(sym(1001))
vpa(harmonic(sym(1001)))
ans =
harmonic(1001)
ans =
7.4864698615493459116575172053329
ans =
0 1 Inf Inf NaN
syms f(x)
f(x) = exp(x) + tan(x);
4-748
harmonic
y = harmonic(f)
y(x) =
harmonic(exp(x) + tan(x))
syms x
V = [x sin(x) 3*i];
M = [exp(i*x) 2; -6 Inf];
harmonic(V)
harmonic(M)
ans =
[ harmonic(x), harmonic(sin(x)), harmonic(3i)]
ans =
[ harmonic(exp(x*1i)), 3/2]
[ Inf, Inf]
syms x
fplot(harmonic(x),[-5,5]), grid on
4-749
4 Functions Alphabetical List
ans =
2*psi(1, x^2 + 2) + 4*x^2*psi(2, x^2 + 2)
4-750
harmonic
syms x
limit(harmonic(x),Inf)
limit((x+1)*harmonic(x),-1)
ans =
Inf
ans =
-1
syms x
taylor(harmonic(x))
ans =
(pi^6*x^5)/945 - zeta(5)*x^4 + (pi^4*x^3)/90...
- zeta(3)*x^2 + (pi^2*x)/6
syms x
expand(harmonic(2*x+3))
ans =
harmonic(x + 1/2)/2 + log(2) + harmonic(x)/2 - 1/(2*(x + 1/2))...
+ 1/(2*x + 1) + 1/(2*x + 2) + 1/(2*x + 3)
Input Arguments
x Input
number | vector | matrix | multidimensional array | symbolic variable | symbolic
expression | symbolic function | symbolic vector | symbolic matrix | symbolic N-D array
4-751
4 Functions Alphabetical List
More About
Harmonic Function
x 1
harmonic ( x) = S
k=1 k
It is also defined as
harmonic ( x) = Y ( x + 1 ) + g
Algorithms
The harmonic function is defined for all complex arguments z except for negative integers
-1, -2,... where a singularity occurs.
1
expand expands harmonic using the equations harmonic ( x + 1) = harmonic ( x ) + ,
x
1
+ p cot ( p x ) , and the Gauss multiplication formula for
harmonic ( - x ) = harmonic ( x) -
x
harmonic(kx), where k is an integer.
-1
harmonic = - 2 ln ( 2 )
2
4-752
harmonic
2 3 3
harmonic - = - ln ( 3 ) - p
3 2 6
1 3 3
harmonic - = - ln ( 3 ) + p
3 2 6
-3 p
harmonic = -3 ln ( 2 ) -
4 2
-1 p
harmonic = - 3 ln ( 2 ) +
4 2
-5 3 3
harmonic = -2 ln ( 2 ) - ln ( 3 ) - p
6 2 2
-1 3 3
harmonic = - 2 ln ( 2 ) - ln ( 3 ) + p
6 2 2
harmonic ( 0 ) = 0
1
harmonic = 2 - 2 ln ( 2 )
2
1 3 3
harmonic = 3 - ln ( 3 ) - p
3 2 6
2 3 3 3
harmonic = - ln ( 3 ) + p
3 2 2 6
1 p
harmonic = 4 - 3 ln ( 2 ) -
4 2
4-753
4 Functions Alphabetical List
3 4 p
harmonic = - 3 ln ( 2 ) +
4 3 2
1 3 3
harmonic = 6 - 2 ln ( 2 ) - ln ( 3 ) - p
6 2 2
5 6 3 3
harmonic = - 2 ln ( 2 ) - ln ( 3 ) + p
6 5 2 2
harmonic (1 ) = 1
harmonic ( ) =
harmonic ( - ) = NaN
See Also
beta | factorial | gamma | gammaln | nchoosek | zeta
Introduced in R2014a
4-754
has
has
Check if expression contains particular subexpression
Syntax
has(expr,subexpr)
Description
has(expr,subexpr) returns logical 1 (true) if expr contains subexpr. Otherwise, it
returns logical 0 (false).
Examples
Check If Expression Contains Particular Subexpression
Use the has function to check if an expression contains a particular variable or
subexpression.
ans =
logical
1
has(x + y, z)
ans =
logical
4-755
4 Functions Alphabetical List
Check if x + y + z contains the following subexpressions. Note that has finds the
subexpression x + z even though the terms x and z do not appear next to each other in
the expression.
has(x + y + z, x + y)
has(x + y + z, y + z)
has(x + y + z, x + z)
ans =
logical
1
ans =
logical
1
ans =
logical
1
ans =
logical
0
Expand the expression and then call has to check if the result contains x^2. Because
expand((x + 1)^2) transforms the original expression to x^2 + 2*x + 1, the has
function finds the subexpression x^2 and returns logical 1.
has(expand((x + 1)^2), x^2)
ans =
logical
1
4-756
has
If an expression contains one or more of the specified subexpressions, has returns logical
1.
syms x
has(sin(x) + cos(x) + x^2, [tan(x), cot(x), sin(x), exp(x)])
ans =
logical
1
If an expression does not contain any of the specified subexpressions, has returns logical
0.
syms x
has(sin(x) + cos(x) + x^2, [tan(x), cot(x), exp(x)])
ans =
logical
0
syms x y
M = [sin(x)*sin(y), cos(x*y) + 1; cos(x)*tan(x), 2*sin(x)^2]
M =
[ sin(x)*sin(y), cos(x*y) + 1]
[ cos(x)*tan(x), 2*sin(x)^2]
Use has to check which elements of M contain sin(x). The result is a matrix of the
same size as M, with 1s and 0s as its elements. For the elements of M containing the
specified expression, has returns logical 1s. For the elements that do not contain that
subexpression, has returns logical 0s.
T = has(M, sin(x))
T =
22 logical array
4-757
4 Functions Alphabetical List
1 0
0 1
Return only the elements that contain sin(x) and replace all other elements with 0 by
multiplying M by T elementwise.
M.*T
ans =
[ sin(x)*sin(y), 0]
[ 0, 2*sin(x)^2]
any(has(M(:), sin(x)))
ans =
logical
1
any(has(M(:), cos(y)))
ans =
logical
0
syms x y z
T = has([x + 1, cos(y) + 1, y + z, 2*x*cos(y)], [x, cos(y)])
T =
14 logical array
1 1 0 1
Return only the elements of the original vector that contain x or cos(y) or both, and
replace all other elements with 0 by multiplying the original vector by T elementwise.
[x + 1, cos(y) + 1, y + z, 2*x*cos(y)].*T
ans =
4-758
has
[ x + 1, cos(y) + 1, 0, 2*x*cos(y)]
syms x
f(x) = sin(x) + cos(x);
formula(f)
ans =
cos(x) + sin(x)
Check if f and f(x) contain sin(x). In both cases has checks if the expression sin(x)
+ cos(x) contains sin(x).
has(f, sin(x))
has(f(x), sin(x))
ans =
logical
1
ans =
logical
1
Check if f(x^2) contains f. For these arguments, has returns logical 0 (false) because
it does not check if the expression f(x^2) contains the letter f. This call is equivalent to
has(f(x^2), formula(f)), which, in turn, resolves to has(cos(x^2) + sin(x^2),
cos(x) + sin(x)).
has(f(x^2), f)
ans =
logical
4-759
4 Functions Alphabetical List
syms x
f = int(tan(x^7), x);
has(f, 'int')
ans =
logical
1
Check if the solution to a differential equation contains calls to either sin or cos by
specifying the second argument as {'sin','cos'}. The has function returns logical 0
(false), which means the solution does not contain calls to either sin or cos.
syms y(x) a
sol = dsolve(diff(y,x) == a*y);
has(sol, {'sin' 'cos'})
ans =
logical
0
Input Arguments
expr Expression to test
symbolic expression | symbolic function | symbolic equation | symbolic inequality |
symbolic vector | symbolic matrix | symbolic array
4-760
has
More About
Tips
has does not transform or simplify expressions. This is why it does not find
subexpressions like x^2 in expressions like (x + 1)^2. However, in some cases has
might find that an expression or subexpression can be represented in a form other
than its original form. For example, has finds that the expression -x - 1 can be
represented as -(x + 1). Thus, the call has(-x - 1, x + 1) returns 1.
If expr is an empty symbolic array, has returns an empty logical array of the same
size as expr.
See Also
subexpr | subs | times
Introduced in R2015b
4-761
4 Functions Alphabetical List
heaviside
Heaviside step function
Syntax
heaviside(x)
Description
heaviside(x) returns the value 0 for x < 0, 1 for x > 0, and 1/2 for x = 0.
Examples
heaviside(sym(-3))
ans =
0
heaviside(sym(3))
ans =
1
4-762
heaviside
heaviside(sym(0))
ans =
1/2
heaviside(0)
ans =
0.5000
syms x
assume(x < 0)
heaviside(x)
ans =
0
syms x clear
syms x
fplot(heaviside(x), [-2, 2])
4-763
4 Functions Alphabetical List
4-764
heaviside
syms x
heaviside(sym([-1 0; 1/2 x]))
ans =
[ 0, 1/2]
[ 1, heaviside(x)]
4-765
4 Functions Alphabetical List
Find the first derivative of the Heaviside function. The first derivative of the Heaviside
function is the Dirac delta function.
syms x
diff(heaviside(x), x)
ans =
dirac(x)
syms x
int(exp(-x)*heaviside(x), x, -Inf, Inf)
ans =
1
heaviside(sym(0))
ans =
1/2
Other common values for the Heaviside function at the origin are 0 and 1. To change
the value of heaviside at the origin, use the 'HeavisideAtOrigin' preference of
sympref. Store the previous parameter value returned by sympref, so that you can
restore it later.
oldparam = sympref('HeavisideAtOrigin',1);
heaviside(sym(0))
ans =
1
4-766
heaviside
The preferences set by sympref persist throughout your current and future MATLAB
sessions. To restore the previous value of heaviside at the origin, use the value stored
in oldparam.
sympref('HeavisideAtOrigin',oldparam);
Alternatively, you can restore the default value of 'HeavisideAtOrigin' by using the
'default' setting.
sympref('HeavisideAtOrigin','default');
Input Arguments
x Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
See Also
dirac | sympref
4-767
4 Functions Alphabetical List
hermiteForm
Hermite form of matrix
Syntax
H = hermiteForm(A)
[U,H] = hermiteForm(A)
___ = hermiteForm(A,var)
Description
H = hermiteForm(A) returns the Hermite normal form of a matrix A. The elements
of A must be integers or polynomials in a variable determined by symvar(A,1). The
Hermite form H is an upper triangular matrix.
You can use the input argument var in any of the previous syntaxes.
Examples
A = sym(invhilb(5))
4-768
hermiteForm
H = hermiteForm(A)
A =
[ 25, -300, 1050, -1400, 630]
[ -300, 4800, -18900, 26880, -12600]
[ 1050, -18900, 79380, -117600, 56700]
[ -1400, 26880, -117600, 179200, -88200]
[ 630, -12600, 56700, -88200, 44100]
H =
[ 5, 0, -210, -280, 630]
[ 0, 60, 0, 0, 0]
[ 0, 0, 420, 0, 0]
[ 0, 0, 0, 840, 0]
[ 0, 0, 0, 0, 2520]
syms x
A = [x^2 + 3, (2*x - 1)^2; (x + 2)^2, 3*x^2 + 5]
A =
[ x^2 + 3, (2*x - 1)^2]
[ (x + 2)^2, 3*x^2 + 5]
H =
[ 1, (4*x^3)/49 + (47*x^2)/49 - (76*x)/49 + 20/49]
[ 0, x^4 + 12*x^3 - 13*x^2 - 12*x - 11]
syms x y
A = [2/x + y, x^2 - y^2; 3*sin(x) + y, x]
A =
[ y + 2/x, x^2 - y^2]
4-769
4 Functions Alphabetical List
[ y + 3*sin(x), x]
Find the Hermite form of this matrix. If you do not specify the polynomial variable,
hermiteForm uses symvar(A,1) and thus determines that the polynomial variable is x.
Because 3*sin(x) + y is not a polynomial in x, hermiteForm throws an error.
H = hermiteForm(A)
Find the Hermite form of A specifying that all elements of A are polynomials in the
variable y.
H = hermiteForm(A,y)
H =
[ 1, (x*y^2)/(3*x*sin(x) - 2) + (x*(x - x^2))/(3*x*sin(x) - 2)]
[ 0, 3*y^2*sin(x) - 3*x^2*sin(x) + y^3 + y*(- x^2 + x) + 2]
U =
[ 13, 9, 7]
[ 6, 4, 3]
[ 20, 15, 12]
H =
[ 3, 0, 30]
[ 0, 12, 0]
[ 0, 0, 60]
ans =
33 logical array
1 1 1
4-770
hermiteForm
1 1 1
1 1 1
Find the Hermite form and the corresponding transformation matrix for a matrix of
polynomials.
syms x y
A = [2*(x - y), 3*(x^2 - y^2);
4*(x^3 - y^3), 5*(x^4 - y^4)];
[U,H] = hermiteForm(A,x)
U =
[ 1/2, 0]
[ 2*x^2 + 2*x*y + 2*y^2, -1]
H =
[ x - y, (3*x^2)/2 - (3*y^2)/2]
[ 0, x^4 + 6*x^3*y - 6*x*y^3 - y^4]
isAlways(H == U*A)
ans =
22 logical array
1 1
1 1
A =
9 -36 30
-36 192 -180
30 -180 180
4-771
4 Functions Alphabetical List
syms x
hermiteForm(A,x)
ans =
1 0 0
0 1 0
0 0 1
ans =
3 0 30
0 12 0
0 0 60
Input Arguments
A Input matrix
symbolic matrix
Input matrix, specified as a symbolic matrix, the elements of which are integers or
univariate polynomials. If the elements of A contain more than one variable, use the
var argument to specify a polynomial variable, and treat all other variables as symbolic
parameters. If A is multivariate, and you do not specify var, then hermiteForm uses
symvar(A,1) to determine a polynomial variable.
Output Arguments
H Hermite normal form of input matrix
symbolic matrix
Hermite normal form of input matrix, returned as a symbolic matrix. The Hermite form
of a matrix is an upper triangular matrix.
4-772
hermiteForm
U Transformation matrix
unimodular symbolic matrix
More About
Hermite Normal Form
For any square n-by-n matrix A with integer coefficients, there exists an n-by-n matrix H
and an n-by-n unimodular matrix U, such that A*U = H, where H is the Hermite normal
form of A. A unimodular matrix is a real square matrix, such that its determinant equals
1 or -1. If A is a matrix of polynomials, then the determinant of U is a constant.
hermiteForm returns the Hermite normal form of a nonsingular integer square matrix
H jj H jj
A as an upper triangular matrix H, such that H jj 0 and - < Hij for j > i . If
2 2
A is not a square matrix or a singular matrix, the matrix H is simply an upper triangular
matrix.
See Also
jordan | smithForm
Introduced in R2015b
4-773
4 Functions Alphabetical List
hermiteH
Hermite polynomials
Syntax
hermiteH(n,x)
Description
hermiteH(n,x) represents the nth-degree Hermite polynomial at the point x.
Examples
syms x
hermiteH([0, 1, 2, 3, 4], x)
ans =
[ 1, 2*x, 4*x^2 - 2, 8*x^3 - 12*x, 16*x^4 - 48*x^2 + 12]
Find the value of the fifth-degree Hermite polynomial at these points. Because these
numbers are not symbolic objects, hermiteH returns floating-point results.
4-774
hermiteH
ans =
19.2634 34.2058 41.0000 36.8066 30.0938
Find the value of the fifth-degree Hermite polynomial for the same numbers converted to
symbolic objects. For symbolic numbers, hermiteH returns exact symbolic results.
ans =
[ 4681/243, 8312/243, 41, 8944/243, 963/32]
syms x y
fplot(hermiteH(0:4,x))
axis([-2 2 -30 30])
grid on
ylabel('H_n(x)')
legend('H_0(x)', 'H_1(x)', 'H_2(x)', 'H_3(x)', 'H_4(x)', 'Location', 'Best')
title('Hermite polynomials')
4-775
4 Functions Alphabetical List
Input Arguments
n Degree of polynomial
nonnegative integer | symbolic variable | symbolic expression | symbolic function |
vector | matrix
4-776
hermiteH
x Evaluation point
number | symbolic number | symbolic variable | symbolic expression | symbolic
function | vector | matrix
More About
Hermite Polynomials
H ( 0, x) = 1, H (1, x) = 2 x, H ( n, x ) = 2 xH ( n - 1, x) - 2 ( n - 1 ) H ( n - 2, x )
Hermite polynomials are orthogonal on the real line with respect to the weight function
2
w ( x ) = e- x
Tips
hermiteH returns floating-point results for numeric arguments that are not symbolic
objects.
hermiteH acts element-wise on nonscalar inputs.
At least one input argument must be a scalar or both arguments must be vectors or
matrices of the same size. If one input argument is a scalar and the other one is a
vector or a matrix, then hermiteH expands the scalar into a vector or matrix of the
same size as the other argument with all elements equal to that scalar.
References
[1] Hochstrasser,U.W. Orthogonal Polynomials. Handbook of Mathematical Functions
with Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A.
Stegun, eds.). New York: Dover, 1972.
See Also
chebyshevT | chebyshevU | gegenbauerC | jacobiP | laguerreL | legendreP
4-777
4 Functions Alphabetical List
Introduced in R2014b
4-778
hessian
hessian
Hessian matrix of scalar function
Syntax
hessian(f,v)
Description
hessian(f,v) finds the Hessian matrix of the scalar function f with respect to vector v
in Cartesian coordinates.
If you do not specify v, then hessian(f) finds the Hessian matrix of the scalar function
f with respect to a vector constructed from all symbolic variables found in f. The order of
variables in this vector is defined by symvar.
Examples
Find Hessian Matrix of Scalar Function
Find the Hessian matrix of a function by using hessian. Then find the Hessian matrix
of the same function as the Jacobian of the gradient of the function.
ans =
[ 0, 1, 2]
[ 1, 0, 0]
[ 2, 0, 0]
Alternatively, compute the Hessian matrix of this function as the Jacobian of the
gradient of that function:
4-779
4 Functions Alphabetical List
jacobian(gradient(f))
ans =
[ 0, 1, 2]
[ 1, 0, 0]
[ 2, 0, 0]
Input Arguments
f Scalar function
symbolic expression | symbolic function
Vector with respect to which you find Hessian matrix, specified as a symbolic vector.
By default, v is a vector constructed from all symbolic variables found in f. The order of
variables in this vector is defined by symvar.
More About
Hessian Matrix
The Hessian matrix of f(x) is the square matrix of the second partial derivatives of f(x).
2f 2 f 2 f
L
x1
2 x1 x2 x1 xn
2
f 2 f 2 f
L
H ( f ) = x2 x1 x22 x2 xn
M M O M
2f 2 f 2 f
L
xn x1 xn x2 xn2
4-780
hessian
See Also
curl | diff | divergence | gradient | jacobian | laplacian | potential |
vectorPotential
Introduced in R2011b
4-781
4 Functions Alphabetical List
horner
Horner nested polynomial representation
Syntax
horner(P)
Description
Suppose P is a matrix of symbolic polynomials. horner(P) transforms each element of P
into its Horner, or nested, representation.
Examples
Find nested polynomial representation of the polynomial:
syms x
horner(x^3 - 6*x^2 + 11*x - 6)
ans =
x*(x*(x - 6) + 11) - 6
Find nested polynomial representation for the polynomials that form a vector:
syms x y
horner([x^2 + x; y^3 - 2*y])
ans =
x*(x + 1)
y*(y^2 - 2)
See Also
collect | combine | expand | factor | numden | rewrite | simplify |
simplifyFraction
4-782
horzcat
horzcat
Concatenate symbolic arrays horizontally
Syntax
horzcat(A1,...,AN)
[A1 ... AN]
Description
horzcat(A1,...,AN) horizontally concatenates the symbolic arrays A1,...,AN.
For vectors and matrices, all inputs must have the same number of rows. For
multidimensional arrays, horzcat concatenates inputs along the second dimension. The
remaining dimensions must match.
Examples
A = sym('a%d%d',[2 2])
B = sym('b%d%d',[2 2])
A =
[ a11, a12]
[ a21, a22]
B =
[ b11, b12]
[ b21, b22]
Concatenate A and B.
horzcat(A,B)
4-783
4 Functions Alphabetical List
ans =
[ a11, a12, b11, b12]
[ a21, a22, b21, b22]
ans =
[ a11, a12, b11, b12]
[ a21, a22, b21, b22]
ans =
[ c11, c12, a1, b11, b12, b13]
[ c21, c22, a2, b21, b22, b23]
[ c31, c32, a3, b31, b32, b33]
ans =
[ c11, c12, a1, b11, b12, b13]
[ c21, c22, a2, b21, b22, b23]
[ c31, c32, a3, b31, b32, b33]
A(:,:,1) =
[ a11, a12, a13]
[ a21, a22, a23]
4-784
horzcat
A(:,:,2) =
[ -a11, -a12, -a13]
[ -a21, -a22, -a23]
B(:,:,1) =
[ b11, b12]
[ b21, b22]
B(:,:,2) =
[ -b11, -b12]
[ -b21, -b22]
ans(:,:,1) =
[ a11, a12, a13, b11, b12]
[ a21, a22, a23, b21, b22]
ans(:,:,2) =
[ -a11, -a12, -a13, -b11, -b12]
[ -a21, -a22, -a23, -b21, -b22]
ans(:,:,1) =
[ a11, a12, a13, b11, b12]
[ a21, a22, a23, b21, b22]
ans(:,:,2) =
[ -a11, -a12, -a13, -b11, -b12]
[ -a21, -a22, -a23, -b21, -b22]
Input Arguments
A1,...,AN Input arrays
symbolic variable | symbolic vector | symbolic matrix | symbolic multidimensional array
See Also
cat | vertcat
4-785
4 Functions Alphabetical List
4-786
hypergeom
hypergeom
Hypergeometric function
Syntax
hypergeom(a,b,z)
Description
hypergeom(a,b,z) represents the generalized hypergeometric function.
Examples
Compute the hypergeometric function for these numbers. Because these numbers are not
symbolic objects, you get floating-point results.
A =
-1.2174 - 0.8330i
1.2091 + 0.0000i
-0.2028 + 0.2405i
Compute the hypergeometric function for the numbers converted to symbolic objects. For
most symbolic (exact) numbers, hypergeom returns unresolved symbolic calls.
4-787
4 Functions Alphabetical List
symA =
hypergeom([1, 2], 5/2, 2)
hypergeom(1/3, [2, 3], pi)
hypergeom([1/2, 1], 1/3, 3i)
Use vpa to approximate symbolic results with the required number of digits:
vpa(symA,10)
ans =
- 1.21741893 - 0.8330405509i
1.209063189
- 0.2027516975 + 0.2405013423i
Special Values
The hypergeometric function has special values for some parameters:
syms a b c d x
hypergeom([], [], x)
hypergeom([a, b, c, d], [a, b, c, d], x)
hypergeom(a, [], x)
ans =
exp(x)
ans =
exp(x)
ans =
1/(1 - x)^a
syms a b c d
hypergeom([a, b], [c, d], 0)
ans =
1
If, after canceling identical parameters, the list of upper parameters contains 0, the
resulting hypergeometric function is constant with the value 1:
4-788
hypergeom
ans =
1
If, after canceling identical parameters, the upper parameters contain a negative integer
larger than the largest negative integer in the lower parameters, the hypergeometric
function is a polynomial. If all parameters as well as the argument x are numeric, a
corresponding explicit value is returned:
hypergeom([(-4), -2 , 3], [-3, 1, 4], x*pi*sqrt(2))
ans =
(6*pi^2*x^2)/5 - 2*2^(1/2)*pi*x + 1
Hypergeometric functions also reduce to other special functions for some parameters:
hypergeom([1], [a], x)
hypergeom([a], [a, b], x)
ans =
(exp(x/2)*whittakerM(1 - a/2, a/2 - 1/2, -x))/(-x)^(a/2)
ans =
x^(1/2 - b/2)*gamma(b)*besseli(b - 1, 2*x^(1/2))
ans =
(a*b*hypergeom([a + 1, b + 1], [c + 1, d + 1], x))/(c*d*x)...
- hypergeom([a, b], [c, d], x)/x^2
ans =
4-789
4 Functions Alphabetical List
Input Arguments
a Upper parameters of hypergeometric function
number | vector | symbolic number | symbolic variable | symbolic expression | symbolic
function | symbolic vector
More About
Generalized Hypergeometric Function
( a1 ) ( a2 ) ( a p ) k
k z
p Fq ( a; b; z) = k k
( b1 ) ( b2 ) ( bq ) k !
k= 0 k k k
4-790
hypergeom
1 k
0 Fq ( ; b; z ) = (b ) (b ) (b ) zk!
k =0 1 k 2 k q k
k
p F0 ( a;; z) = ( a1 )k (a2 )k ( ap )k zk!
k= 0
k
0 F0 ( ;; z ) = zk! = ez
k= 0
Pochhammer Symbol
( )
( x )n = G x + n
(
G x )
Tips
For most exact arguments, the hypergeometric function returns a symbolic function
call. If an upper parameter coincides with a lower parameter, these values cancel and
are removed from the parameter lists.
If, after cancellation of identical parameters, the upper parameters contain a negative
integer larger than the largest negative integer in the lower parameters, then
pFq(a;b;z) is a polynomial in z.
pFp(a;a;z)=0F0(;;z) = ez.
pFq(a;b;z)=1
if the list of upper parameters a contains more 0s than the list of
lower parameters b.
pFq(a;b;0)=1.
Algorithms
The series
4-791
4 Functions Alphabetical List
( a1 ) ( a2 ) ( a p ) k
k z
p Fq ( a; b; z) = k k
k= 0 ( 1 ) k ( 2 ) k ( q ) k
b b b k!
pFq(a;b;z)is symmetric with respect to the parameters, that is, it does not depend on the
order of the arrangement a1, a2, in a or b1, b2, in b.
If at least one upper parameter equals n=0,-1,-2,, the function turns into a
polynomial of degree n. If the previous condition for the lower parameters b is relaxed,
and there is some lower parameter equal to m=0,-1,-2,, then the function pFq(a;b;z)
also reduces to a polynomial in z provided n > m. It is undefined if m>n or if no upper
parameter is a nonpositive integer (resulting in division by 0 in one of the series
coefficients). The case m=n is handled by the following rule.
. If for r values of the upper parameters, there are r values of the lower parameters equal
to them (that is, a = [a1,,ap - r, c1,,cr], b = [b1,,bq - r, c1,,cr]), then the order (p, q) of
the function pFq(a;b;z) is reduced to (p - r, q - r):
This rule applies even if any of the ci is zero or a negative integer. For details, see Luke,
Y.L. "The Special Functions and Their Approximations", vol. 1, p. 42.
d (d + b - 1) - z(d + a) U ( z ) = 0 , d = z ,
z
4-792
hypergeom
p
(d + ai )
i =1
and
q
(d + b j ),
j =1
respectively. Thus, the order of this differential equation is max(p, q+1) and the
hypergeometric function is only one of its solutions. If p<q+1, this differential equation
has a regular singularity at z=0 and an irregular singularity at z=. If p=q+1, the
points z=0, z=1, and z= are regular singularities, thus explaining the convergence
properties of the hypergeometric series.
References
[1] Oberhettinger, F. Hypergeometric Functions. Handbook of Mathematical Functions
with Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A.
Stegun, eds.). New York: Dover, 1972.
[2] Luke, Y.L. "The Special Functions and Their Approximations", Vol. 1, Academic
Press, New York, 1969.
[3] Prudnikov, A.P., Yu.A. Brychkov, and O.I. Marichev, "Integrals and Series", Vol. 3:
More Special Functions, Gordon and Breach, 1990.
See Also
kummerU | whittakerM | whittakerW
4-793
4 Functions Alphabetical List
ifourier
Inverse Fourier transform
Syntax
ifourier(F)
ifourier(F,transVar)
ifourier(F,var,transVar)
Description
ifourier(F) returns the inverse Fourier transform of F using the default independent
variable w for the default transformation variable x. If F does not contain w, ifourier
uses symvar.
Examples
syms x y
F = sqrt(sym(pi))*exp(-y^2/4);
ifourier(F, y, x)
ans =
exp(-x^2)
4-794
ifourier
syms a w t real
F = exp(-w^2/(4*a^2));
ifourier(F, t)
ans =
exp(-a^2*t^2)/(2*pi^(1/2)*(1/(4*a^2))^(1/2))
If you also do not specify the transformation variable, ifourier uses the variable x:
ifourier(F)
ans =
exp(-a^2*x^2)/(2*pi^(1/2)*(1/(4*a^2))^(1/2))
syms a w t clear
syms t w
ifourier(dirac(w), w, t)
ans =
1/(2*pi)
ifourier(2*exp(-abs(w)) - 1, w, t)
ans =
-(2*pi*dirac(t) - 4/(t^2 + 1))/(2*pi)
ifourier(exp(-w)*heaviside(w), w, t)
ans =
4-795
4 Functions Alphabetical List
-1/(2*pi*(- 1 + t*1i))
Compute the inverse Fourier transform of this expression using the default values c =
1, s = -1 of the Fourier parameters. (For details, see Inverse Fourier Transform on
page 4-798.)
syms t w
ifourier(-(sqrt(sym(pi))*w*exp(-w^2/4)*i)/2, w, t)
ans =
t*exp(-t^2)
Change the values of the Fourier parameters toc = 1,s = 1 by using sympref. Then
compute the inverse Fourier transform of the same expression again.
ans =
-t*exp(-t^2)
Change the values of the Fourier parameters toc = 1/2,s = 1 by using sympref.
Compute the inverse Fourier transform using these values.
ans =
-2*t*pi*exp(-t^2)
The preferences set by sympref persist through your current and future MATLAB
sessions. To restore the default values of c and s, set sympref to 'default'.
sympref('FourierParameters','default');
4-796
ifourier
syms a b c d w x y z
ifourier([exp(x), 1; sin(y), i*z],[w, x; y, z],[a, b; c, d])
ans =
[ exp(x)*dirac(a), dirac(b)]
[ (dirac(c - 1)*1i)/2 - (dirac(c + 1)*1i)/2, dirac(1, d)]
When the input arguments are nonscalars, ifourier acts on them element-wise. If
ifourier is called with both scalar and nonscalar arguments, then ifourier expands
the scalar arguments into arrays of the same size as the nonscalar arguments with all
elements of the array equal to the scalar.
syms w x y z a b c d
ifourier(x,[x, w; y, z],[a, b; c, d])
ans =
[ -dirac(1, a)*1i, x*dirac(b)]
[ x*dirac(c), x*dirac(d)]
Note that nonscalar input arguments must have the same size.
ans =
[ fourier(exp(x), x, -a)/(2*pi), -dirac(1, b)*1i]
syms F(w) t
f = ifourier(F, w, t)
f =
fourier(F(w), w, -t)/(2*pi)
4-797
4 Functions Alphabetical List
Input Arguments
F Input function
symbolic expression | symbolic function | vector of symbolic expressions or functions |
matrix of symbolic expressions or functions
Independent variable, specified as a symbolic variable. This variable is often called the
frequency variable.
If you do not specify the independent variable, ifourier uses the variable w by default.
If F does not contain w, then the default variable is determined by symvar.
If you do not specify the transformation variable, ifourier uses the variable x by
default. If x is the independent variable of F, then the default transformation variable is
the variable t.
More About
Inverse Fourier Transform
The inverse Fourier transform of the expression F=F(w) with respect to the variable w
at the point x is defined as follows:
s
f (x) = F ( w ) e-iswx dw.
2p c
-
4-798
ifourier
Here, c and s are parameters of the inverse Fourier transform. The ifourier function
uses c=1, s=1.
Tips
1
ifourier ( F, w, t ) = fourier ( F, w, -t )
2p
References
[1] Oberhettinger, F. Tables of Fourier Transforms and Fourier Transforms of
Distributions, Springer, 1990.
See Also
fourier | ilaplace | iztrans | laplace | sympref | ztrans
4-799
4 Functions Alphabetical List
igamma
Incomplete gamma function
Syntax
igamma(nu,z)
Description
igamma(nu,z) returns the incomplete gamma function.
igamma uses the definition of the upper incomplete gamma function. The MATLAB
gammainc function uses the definition of the lower incomplete gamma function,
gammainc(z, nu) = 1 - igamma(nu, z)/gamma(nu). The order of input arguments
differs between these functions.
Examples
Compute the incomplete gamma function for these numbers. Because these numbers are
not symbolic objects, you get floating-point results.
A =
0.2194 1.6601 1.1979 0
Compute the incomplete gamma function for the numbers converted to symbolic objects:
4-800
igamma
symA =
[ -ei(-1), exp(-2^(1/2))*(2*2^(1/2) + 4), igamma(pi, exp(1)), 0]
vpa(symA)
ans =
[ 0.21938393439552027367716377546012,...
1.6601049038903044104826564373576,...
1.1979302081330828196865548471769,...
0]
Compute the lower incomplete gamma function for these arguments using the MATLAB
gammainc function:
ans =
1.1456 + 1.9842i 0.5089 + 0.8815i 0.0000 + 0.0000i 0.7175 + 0.0000i
Compute the lower incomplete gamma function for the same arguments using igamma:
1 - igamma(1/3, A)/gamma(1/3)
ans =
1.1456 + 1.9842i 0.5089 + 0.8815i 0.0000 + 0.0000i 0.7175 + 0.0000i
If one or both arguments are complex numbers, use igamma to compute the lower
incomplete gamma function. gammainc does not accept complex arguments.
1 - igamma(1/2, i)/gamma(1/2)
ans =
0.9693 + 0.4741i
4-801
4 Functions Alphabetical List
Input Arguments
nu Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
z Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
More About
Upper Incomplete Gamma Function
G (h, z ) = th -1e- t dt
z
z
g (h ,z ) = th -1 e-t dt
0
Tips
The MATLAB gammainc function does not accept complex arguments. For complex
arguments, use igamma.
4-802
igamma
See Also
ei | erfc | factorial | gamma | gammainc | int
Introduced in R2014a
4-803
4 Functions Alphabetical List
ilaplace
Inverse Laplace transform
Syntax
ilaplace(F)
ilaplace(F,transVar)
ilaplace(F,var,transVar)
Description
ilaplace(F) returns the inverse Laplace transform of F using the default independent
variable s for the default transformation variable t. If F does not contain s, ilaplace
uses symvar.
Input Arguments
F
var
Symbolic variable representing the independent variable. This variable is often called the
complex frequency variable.
Default: The variable s. If F does not contain s, then the default variable is determined
by symvar.
4-804
ilaplace
transVar
Examples
Compute the inverse Laplace transform of this expression with respect to y at the
transformation variable x:
syms x y
F = 1/y^2;
ilaplace(F, y, x)
ans =
x
Compute the inverse Laplace transform of this expression calling the ilaplace function
with one argument. If you do not specify the independent variable, ilaplace uses the
variable s.
syms a s x
F = 1/(s - a)^2;
ilaplace(F, x)
ans =
x*exp(a*x)
If you also do not specify the transformation variable, ilaplace uses the variable t:
ilaplace(F)
ans =
t*exp(a*t)
Compute the following inverse Laplace transforms that involve the Dirac and Heaviside
functions:
syms s t
ilaplace(1, s, t)
4-805
4 Functions Alphabetical List
ans =
dirac(t)
ans =
heaviside(t - 2)*sin(t - 2) - exp(-t)/3 +...
(exp(t/2)*(cos((3^(1/2)*t)/2) + 3^(1/2)*sin((3^(1/2)*t)/2)))/3
f =
ilaplace(F(s), s, t)
ans =
F(s)
Find the inverse Laplace transform of this matrix. Use matrices of the same size to
specify the independent variables and transformation variables.
syms a b c d w x y z
ilaplace([exp(x), 1; sin(y), i*z],[w, x; y, z],[a, b; c, d])
ans =
[ exp(x)*dirac(a), dirac(b)]
[ ilaplace(sin(y), y, c), dirac(1, d)*1i]
When the input arguments are nonscalars, ilaplace acts on them element-wise. If
ilaplace is called with both scalar and nonscalar arguments, then ilaplace expands
the scalar arguments into arrays of the same size as the nonscalar arguments with all
elements of the array equal to the scalar.
syms w x y z a b c d
ilaplace(x,[x, w; y, z],[a, b; c, d])
ans =
[ dirac(1, a), x*dirac(b)]
[ x*dirac(c), x*dirac(d)]
4-806
ilaplace
Note that nonscalar input arguments must have the same size.
When the first argument is a symbolic function, the second argument must be a scalar.
syms f1(x) f2(x) a b
f1(x) = exp(x);
f2(x) = x;
ilaplace([f1, f2],x,[a, b])
ans =
[ ilaplace(exp(x), x, a), dirac(1, b)]
More About
Inverse Laplace Transform
The inverse Laplace transform is defined by a contour integral in the complex plane:
c+i
1
f (t ) = F ( s) e st ds.
2p i
c-i
Tips
See Also
fourier | ifourier | iztrans | laplace | ztrans
4-807
4 Functions Alphabetical List
imag
Imaginary part of complex number
Syntax
imag(z)
imag(A)
Description
Input Arguments
z
Examples
Find the imaginary parts of these numbers. Because these numbers are not symbolic
objects, you get floating-point results.
ans =
1.5000 74.2032 4.5747
4-808
imag
ans =
[ 3/2, -6/5, sinh(5)]
imag(2*exp(1 + sym(i)))
ans =
2*exp(1)*sin(1)
In general, imag cannot extract the entire imaginary parts from symbolic expressions
containing variables. However, imag can rewrite and sometimes simplify the input
expression:
syms a x y
imag(a + 2)
imag(x + y*i)
ans =
imag(a)
ans =
imag(x) + real(y)
If you assign numeric values to these variables or if you specify that these variables are
real, imag can extract the imaginary part of the expression:
syms a
a = 5 + 3*i;
imag(a + 2)
ans =
3
syms x y real
imag(x + y*i)
ans =
y
4-809
4 Functions Alphabetical List
syms x y clear
syms x
A = [-1 + sym(i), sinh(x); exp(10 + sym(7)*i), exp(sym(pi)*i)];
imag(A)
ans =
[ 1, imag(sinh(x))]
[ exp(10)*sin(7), 0]
Alternatives
You can compute the imaginary part of z via the conjugate: imag(z)= (z -
conj(z))/2i.
More About
Tips
Calling imag for a number that is not a symbolic object invokes the MATLAB imag
function.
See Also
conj | in | real | sign | signIm
4-810
in
in
Numeric type of symbolic input
Compatibility
In previous releases, in(x,type) returned logical 1 if x belonged to type and 0
otherwise. To obtain the same results as in previous releases, wrap such expressions in
isAlways. For example, use isAlways(in(sym(5),'integer')).
Syntax
in(x,type)
Description
in(x,type) expresses the logical condition that x is of the specified type.
Examples
Express Condition on Symbolic Variable or Expression
The syntax in(x,type) expresses the condition that x is of the specified type. Express
the condition that x is of type Real.
syms x
cond = in(x,'real')
cond =
in(x, 'real')
Evaluate the condition using isAlways. Because isAlways cannot determine the
condition, it issues a warning and returns logical 0 (false).
isAlways(cond)
4-811
4 Functions Alphabetical List
ans =
logical
0
Assume the condition cond is true using assume, and evaluate the condition again. The
isAlways function returns logical 1 (true) indicating that the condition is true.
assume(cond)
isAlways(cond)
ans =
logical
1
syms x clear
Solve the equation sin(x) == 0 using solve. Set the option ReturnConditions to
true to return conditions on the solution. The solve function uses in to express the
conditions.
syms x
[solx, params, conds] = solve(sin(x) == 0,'ReturnConditions',true)
solx =
pi*k
params =
k
conds =
in(k, 'integer')
The solution is pi*k with parameter k under the condition in(k,'integer'). You can
use this condition to set an assumption for further computations. Under the assumption,
solve returns only integer values of k.
4-812
in
assume(conds)
k = solve(solx > 0, solx < 5*pi, params)
k =
1
2
3
4
ans =
pi
2*pi
3*pi
4*pi
M =
[ 61/50, 1i, x]
[ sin(y), 3*x, 0]
[ Inf, 3^(1/2), 22/7]
Use isAlways to test if the elements of M are rational numbers. The in function acts on
M element-by-element. Note that isAlways returns logical 0 (false) for statements that
cannot be decided and issues a warning for those statements.
in(M,'rational')
ans =
[ in(61/50, 'rational'), in(1i, 'rational'), in(x, 'rational')]
[ in(sin(y), 'rational'), in(3*x, 'rational'), in(0, 'rational')]
4-813
4 Functions Alphabetical List
isAlways(in(M,'rational'))
Input Arguments
x Input
symbolic number | symbolic vector | symbolic matrix | symbolic multidimensional array
| symbolic expression | symbolic function
See Also
assume | assumeAlso | false | imag | isalways | isequal | isequaln |
isfinite | isinf | piecewise | real | true
Introduced in R2014b
4-814
incidenceMatrix
incidenceMatrix
Find incidence matrix of system of equations
Syntax
A = incidenceMatrix(eqs,vars)
Description
A = incidenceMatrix(eqs,vars) for m equations eqs and n variables vars returns
an m-by-n matrix A. Here, A(i,j) = 1 if eqs(i) contains vars(j) or any derivative of
vars(j). All other elements of A are 0s.
Examples
Incidence Matrix
Find the incidence matrix of a system of five equations in five variables.
Create the following symbolic vector eqs containing five symbolic differential equations.
Create the vector of variables. Here, c1 and c3 are symbolic parameters (not variables)
of the system.
vars = [y1(t), y2(t), y3(t), y4(t), y5(t)];
Find the incidence matrix A for the equations eqs and with respect to the variables vars.
A = incidenceMatrix(eqs, vars)
4-815
4 Functions Alphabetical List
A =
1 1 0 0 0
1 1 1 0 0
0 1 1 1 0
0 0 1 1 1
0 0 0 1 1
Input Arguments
eqs Equations
vector of symbolic equations | vector of symbolic expressions
vars Variables
vector of symbolic variables | vector of symbolic functions | vector of symbolic function
calls
Output Arguments
A Incidence matrix
matrix of double-precision values
See Also
daeFunction | decic | findDecoupledBlocks | isLowIndexDAE |
massMatrixForm | odeFunction | reduceDAEIndex | reduceDAEToODE |
reduceDifferentialOrder | reduceRedundancies | spy
Introduced in R2014b
4-816
int
int
Definite and indefinite integrals
Syntax
int(expr,var)
int(expr,var,a,b)
int( ___ ,Name,Value)
Description
int(expr,var) computes the indefinite integral of expr with respect to the symbolic
scalar variable var. Specifying the variable var is optional. If you do not specify it, int
uses the default variable determined by symvar. If expr is a constant, then the default
variable is x.
int(expr,var,a,b) computes the definite integral of expr with respect to var from a
to b. If you do not specify it, int uses the default variable determined by symvar. If expr
is a constant, then the default variable is x.
int( ___ ,Name,Value) uses additional options specified by one or more Name,Value
pair arguments.
Examples
syms x
int(-2*x/(1 + x^2)^2)
4-817
4 Functions Alphabetical List
ans =
1/(x^2 + 1)
syms x z
int(x/(1 + z^2), x)
int(x/(1 + z^2), z)
ans =
x^2/(2*(z^2 + 1))
ans =
x*atan(z)
If you do not specify the integration variable, int uses the variable returned by symvar.
For this expression, symvar returns x:
symvar(x/(1 + z^2), 1)
ans =
x
syms x
int(x*log(1 + x), 0, 1)
ans =
1/4
Integrate this expression from sin(t) to 1 specifying the integration range as a vector:
syms x t
int(2*x, [sin(t), 1])
ans =
cos(t)^2
4-818
int
syms a x t z
int([exp(t), exp(a*t); sin(t), cos(t)])
ans =
[ exp(t), exp(a*t)/a]
[ -cos(t), sin(t)]
Apply IgnoreAnalyticConstraints
Compute this indefinite integral. By default, int uses strict mathematical rules. These
rules do not let int rewrite asin(sin(x)) and acos(cos(x)) as x.
syms x
int(acos(sin(x)), x)
ans =
x*acos(sin(x)) + (x^2*sign(cos(x)))/2
ans =
-(x*(x - pi))/2
syms x t
int(x^t, x)
By default, int returns the integral as a piecewise object where every branch
corresponds to a particular value (or a range of values) of the symbolic parameter t:
ans =
piecewise(t == -1, log(x), t ~= -1, x^(t + 1)/(t + 1))
4-819
4 Functions Alphabetical List
With this option, int ignores the special case t=-1 and returns only the branch where
t<>1:
ans =
x^(t + 1)/(t + 1)
ans =
NaN
However, the Cauchy principal value of the integral exists. Use PrincipalValue to
compute the Cauchy principal value of the integral:
int(1/(x - 1), x, 0, 2, 'PrincipalValue', true)
ans =
0
ans =
int(sin(sinh(x)), x)
If int cannot compute a closed form of an indefinite integral, try to approximate the
expression around some point using taylor, and then compute the integral. For
example, approximate the expression around x = 0:
int(taylor(F, x, 'ExpansionPoint', 0, 'Order', 10), x)
ans =
4-820
int
F =
int(cos(x)/(x^2 + 1)^(1/2), x, 0, 10)
If int cannot compute a closed form of a definite integral, try approximating that
integral numerically using vpa. For example, approximate F with five significant digits:
vpa(F, 5)
ans =
0.37571
Input Arguments
expr Integrand
symbolic expression | symbolic function | symbolic vector | symbolic matrix | symbolic
number
Integration variable, specified as a symbolic variable. If you do not specify this variable,
int uses the default variable determined by symvar(expr,1). If expr is a constant,
then the default variable is x.
a Lower bound
number | symbolic number | symbolic variable | symbolic expression | symbolic
function
4-821
4 Functions Alphabetical List
b Upper bound
number | symbolic number | symbolic variable | symbolic expression | symbolic
function
Note that using this option can lead to wrong or incomplete results.
Indicator for ignoring special cases, specified as true or false. If the value is true and
integration requires case analysis, ignore cases that require one or more parameters to
be elements of a comparatively small set, such as a fixed finite set or a set of integers.
Indicator for returning principal value, specified as true or false. If the value is true,
compute the Cauchy principal value of the integral.
4-822
int
More About
Tips
For indefinite integrals, use series expansions. Use this method to approximate an
integral around a particular value of the variable.
For definite integrals, use numeric approximations.
Results returned by int do not include integration constants.
For indefinite integrals, int implicitly assumes that the integration variable var is
real. For definite integrals, int restricts the integration variable var to the specified
integration interval. If one or both integration bounds a and b are not numeric, int
assumes that a <= b unless you explicitly specify otherwise.
Algorithms
log(a) + log(b)=log(ab) for all values of a and b. In particular, the following equality
is valid for all values of a, b, and c:
(ab)c=acbc.
log(ab)=blog(a) for all values of a and b. In particular, the following equality is valid
for all values of a, b, and c:
(ab)c=abc.
If f and g are standard mathematical functions and f(g(x))=x for all small positive
numbers, then f(g(x))=x is assumed to be valid for all complex values x. In particular:
log(ex)=x
4-823
4 Functions Alphabetical List
See Also
diff | functionalDerivative | symprod | symsum | symvar | vpaintegral
4-824
int8int16int32int64
int8int16int32int64
Convert symbolic matrix to signed integers
Syntax
int8(S)
int16(S)
int32(S)
int64(S)
Description
int8(S) converts a symbolic matrix S to a matrix of signed 8-bit integers.
Note The output of int8, int16, int32, and int64 does not have data type symbolic.
4-825
4 Functions Alphabetical List
See Also
sym | vpa | single | uint8 | double | uint16 | uint32 | uint64
4-826
inv
inv
Compute symbolic matrix inverse
Syntax
R = inv(A)
Description
R = inv(A) returns inverse of the symbolic matrix A.
Examples
Compute the inverse of the following matrix of symbolic numbers:
A = sym([2,-1,0;-1,2,-1;0,-1,2]);
inv(A)
ans =
[ 3/4, 1/2, 1/4]
[ 1/2, 1, 1/2]
[ 1/4, 1/2, 3/4]
ans =
[ d/(a*d - b*c), -b/(a*d - b*c)]
[ -c/(a*d - b*c), a/(a*d - b*c)]
ans =
4-827
4 Functions Alphabetical List
See Also
eig | det | rank
4-828
isAlways
isAlways
Check whether equation or inequality holds for all values of its variables
Compatibility
isAlways issues a warning when returning false for undecidable inputs. To suppress the
warning, set the Unknown option to false as isAlways(cond,'Unknown','false').
For details, see Handle Output for Undecidable Conditions on page 4-830.
Syntax
isAlways(cond)
isAlways(cond,Name,Value)
Description
isAlways(cond) checks if the condition cond is valid for all possible values of the
symbolic variables in cond. When verifying cond, the isAlways function considers all
assumptions on the variables in cond. If the condition holds, isAlways returns logical 1
(true). Otherwise it returns logical 0 (false).
Examples
Test Conditions
Check if this inequality is valid for all values of x.
syms x
isAlways(abs(x) >= 0)
ans =
4-829
4 Functions Alphabetical List
logical
1
isAlways returns logical 1 (true) indicating that the inequality abs(x) >= 0 is valid
for all values of x.
ans =
logical
1
isAlways returns logical 1 (true) indicating that the inequality is valid for all values of
x.
ans =
logical
1
Check if both conditions are valid. To check if several conditions are valid, combine them
using the logical operator and or its shortcut &.
isAlways(sin(x)^2 + cos(x)^2 == 1 & abs(x) > 2*abs(x))
ans =
logical
0
4-830
isAlways
isAlways(2*x >= x)
To change this default behavior, use Unknown. For example, specify Unknown as false
to suppress the warning and make isAlways return logical 0 (false) if it cannot
determine the validity of the condition.
isAlways(2*x >= x,'Unknown','false')
ans =
logical
0
Instead of false, you can also specify error to return an error, and true to return
logical 1 (true).
ans =
logical
1
Input Arguments
cond Condition to check
symbolic condition | vector of symbolic conditions | matrix of symbolic conditions |
multidimensional array of symbolic conditions
4-831
4 Functions Alphabetical List
More About
Use Assumptions on Symbolic Variables on page 1-27
Clear Assumptions and Reset the Symbolic Engine on page 3-66
See Also
assume | assumeAlso | assumptions | in | isequal | isequaln | isfinite |
isinf | isnan | piecewise | sym | syms
Introduced in R2012a
4-832
isequal
isequal
Test equality of symbolic inputs
Syntax
isequal(a,b)
isequal(a1,a2,...,aN)
Description
isequal(a,b) returns logical 1 (true) if A and B are the same size and their contents
are of equal value. Otherwise, isequal returns logical 0 (false). isequal does not
consider NaN (not a number) values equal. isequal recursively compares the contents
of symbolic data structures and the properties of objects. If all contents in the respective
locations are equal, isequal returns logical 1 (true).
Examples
Test if 2 and 5 are equal. Because you are comparing doubles, the MATLAB isequal
function is called. isequal returns 0 (false) as expected.
isequal(2,5)
ans =
logical
4-833
4 Functions Alphabetical List
Test if the solution of the equation cos(x) == -1 is pi. The isequal function returns
1 (true) meaning the solution is equal to pi.
syms x
sol = solve(cos(x) == -1, x);
isequal(sol,sym(pi))
ans =
logical
1
usingIsEqual =
logical
0
usingLogical =
logical
1
ans =
logical
1
4-834
isequal
Test if solutions of the quadratic equation found by solve are equal to the expected
solutions. isequal function returns 1 (true) meaning the inputs are equal.
syms a b c x
eqn = a*x^2 + b*x + c;
Sol = solve(eqn, x);
testSol = [-(b+(b^2-4*a*c)^(1/2))/(2*a); -(b-(b^2-4*a*c)^(1/2))/(2*a)];
isequal(Sol,testSol)
ans =
logical
1
The Hilbert matrix is a special matrix that is difficult to invert accurately. If the inverse
is accurately computed, then multiplying the inverse by the original Hilbert matrix
returns the identity matrix.
Use this condition to symbolically test if the inverse of hilb(20) is correctly calculated.
isequal returns 1 (true) meaning that the product of the inverse and the original
Hilbert matrix is equal to the identity matrix.
H = sym(hilb(20));
prod = H*inv(H);
eye20 = sym(eye(20));
isequal(prod,eye20)
ans =
logical
1
ans =
logical
0
4-835
4 Functions Alphabetical List
Input Arguments
a,b Inputs to compare
numbers | vectors | matrices | multidimensional arrays | symbolic numbers | symbolic
variables | symbolic vectors | symbolic matrices | symbolic multidimensional arrays |
symbolic functions | symbolic expressions
More About
Tips
When your inputs are not symbolic objects, the MATLAB isequal function is
called. If one of the arguments is symbolic, then all other arguments are converted to
symbolic objects before comparison, and the symbolic isequal function is called.
See Also
in | isAlways | isequaln | isfinite | isinf | isnan | logical
4-836
isequaln
isequaln
Test symbolic objects for equality, treating NaN values as equal
Syntax
isequaln(A,B)
isequaln(A1,A2,...,An)
Description
isequaln(A,B) returns logical 1 (true) if A and B are the same size and their contents
are of equal value. Otherwise, isequaln returns logical 0 (false). All NaN (not a number)
values are considered to be equal to each other. isequaln recursively compares the
contents of symbolic data structures and the properties of objects. If all contents in the
respective locations are equal, isequaln returns logical 1 (true).
Examples
Compare Two Expressions
Use isequaln to compare these two expressions:
syms x
isequaln(abs(x), x)
ans =
logical
0
ans =
4-837
4 Functions Alphabetical List
logical
1
ans =
logical
0
ans =
logical
1
Input Arguments
A,B Inputs to compare
symbolic numbers | symbolic variables | symbolic expressions | symbolic functions |
symbolic vectors | symbolic matrices
4-838
isequaln
More About
Tips
Calling isequaln for arguments that are not symbolic objects invokes the MATLAB
isequaln function. If one of the arguments is symbolic, then all other arguments are
converted to symbolic objects before comparison.
See Also
in | isAlways | isequal | isequaln | isfinite | isinf | isnan
Introduced in R2013a
4-839
4 Functions Alphabetical List
isfinite
Check whether symbolic array elements are finite
Syntax
isfinite(A)
Description
isfinite(A) returns an array of the same size as A containing logical 1s (true) where
the elements of A are finite, and logical 0s (false) where they are not. For a complex
number, isfinite returns 1 if both the real and imaginary parts of that number are
finite. Otherwise, it returns 0.
Examples
ans =
23 logical array
1 0 0
1 0 0
4-840
isfinite
cot(V)
isfinite(cot(V))
ans =
[ Inf, Inf, Inf, Inf]
ans =
14 logical array
0 0 0 0
Nevertheless, the cotangents of the approximated values are finite due to the round-off
errors:
isfinite(cot(V_approx))
ans =
14 logical array
1 1 1 1
Input Arguments
A Input value
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic array | symbolic vector | symbolic matrix
More About
Tips
For any A, exactly one of the three quantities isfinite(A), isinf(A), or isnan(A)
is 1 for each element.
Elements of A are recognized as finite if they are
4-841
4 Functions Alphabetical List
See Also
in | isAlways | isequal | isequaln | isinf | isnan
Introduced in R2013b
4-842
isinf
isinf
Check whether symbolic array elements are infinite
Syntax
isinf(A)
Description
isinf(A) returns an array of the same size as A containing logical 1s (true) where
the elements of A are infinite, and logical 0s (false) where they are not. For a complex
number, isinf returns 1 if the real or imaginary part of that number is infinite or both
real and imaginary parts are infinite. Otherwise, it returns 0.
Examples
ans =
23 logical array
0 0 1
0 1 0
4-843
4 Functions Alphabetical List
cot(V)
isinf(cot(V))
ans =
[ Inf, Inf, Inf, Inf]
ans =
14 logical array
1 1 1 1
Nevertheless, the cotangents of the approximated values are not infinite due to the
round-off errors:
isinf(cot(V_approx))
ans =
14 logical array
0 0 0 0
Input Arguments
A Input value
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic array | symbolic vector | symbolic matrix
More About
Tips
For any A, exactly one of the three quantities isfinite(A), isinf(A), or isnan(A)
is 1 for each element.
The elements of A are recognized as infinite if they are
4-844
isinf
See Also
in | isAlways | isequal | isequaln | isfinite | isnan
Introduced in R2013b
4-845
4 Functions Alphabetical List
isLowIndexDAE
Check if differential index of system of equations is lower than 2
Syntax
isLowIndexDAE(eqs,vars)
Description
isLowIndexDAE(eqs,vars) checks if the system eqs of first-order semilinear
differential algebraic equations (DAEs) has a low differential index. If the differential
index of the system is 0 or 1, then isLowIndexDAE returns logical 1 (true). If the
differential index of eqs is higher than 1, then isLowIndexDAE returns logical 0 (false).
The number of equations eqs must match the number of variables vars.
Examples
Create the following system of two differential algebraic equations. Here, x(t) and y(t)
are the state variables of the system. Specify the equations and variables as two symbolic
vectors: equations as a vector of symbolic equations, and variables as a vector of symbolic
function calls.
Use isLowIndexDAE to check the differential order of the system. The differential order
of this system is 1. For systems of index 0 and 1, isLowIndexDAE returns 1 (true).
isLowIndexDAE(eqs, vars)
4-846
isLowIndexDAE
ans =
logical
1
Create the following system of two differential algebraic equations. Here, x(t), y(t),
and z(t) are the state variables of the system. Specify the equations and variables as
two symbolic vectors: equations as a vector of symbolic equations, and variables as a
vector of symbolic function calls.
Use isLowIndexDAE to check the differential index of the system. For this system
isLowIndexDAE returns 0 (false). This means that the differential index of the system
is 2 or higher.
isLowIndexDAE(eqs, vars)
ans =
logical
0
Use reduceDAEIndex to rewrite the system so that the differential index is 1. Calling
this function with four output arguments also shows the differential index of the original
system. The new system has one additional state variable, Dyt(t).
newEqs =
diff(x(t), t) - z(t) - x(t)
Dyt(t) - f(t)
x(t) - y(t)
diff(x(t), t) - Dyt(t)
newVars =
x(t)
4-847
4 Functions Alphabetical List
y(t)
z(t)
Dyt(t)
oldIndex =
2
isLowIndexDAE(newEqs, newVars)
ans =
logical
1
Input Arguments
eqs System of first-order semilinear differential algebraic equations
vector of symbolic equations | vector of symbolic expressions
State variables, specified as a vector of symbolic functions or function calls, such as x(t).
Example: [x(t),y(t)]
See Also
daeFunction | decic | findDecoupledBlocks | incidenceMatrix |
massMatrixForm | odeFunction | reduceDAEIndex | reduceDAEToODE |
reduceDifferentialOrder | reduceRedundancies
Introduced in R2014b
4-848
isnan
isnan
Check whether symbolic array elements are NaNs
Syntax
isnan(A)
Description
isnan(A) returns an array of the same size as A containing logical 1s (true) where the
elements of A are symbolic NaNs, and logical 0s (false) where they are not.
Examples
ans =
23 logical array
0 1 0
0 0 1
Input Arguments
A Input value
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic array | symbolic vector | symbolic matrix
4-849
4 Functions Alphabetical List
More About
Tips
For any A, exactly one of the three quantities isfinite(A), isinf(A), or isnan(A)
is 1 for each element.
Symbolic expressions and functions containing NaN evaluate to NaN. For example,
sym(NaN + i) returns symbolic NaN.
See Also
isAlways | isequal | isequaln | isfinite | isinf
Introduced in R2013b
4-850
iztrans
iztrans
Inverse Z-transform
Syntax
iztrans(F)
iztrans(F,transVar)
iztrans(F,var,transVar)
Description
iztrans(F) returns the inverse Z-transform of F using the default independent variable
z and the default transformation variable n. If F does not contain z, ifourier uses
symvar.
Input Arguments
F
var
Symbolic variable representing the independent variable. This variable is often called the
complex frequency variable.
Default: The variable z. If F does not contain z, then the default variable is determined
by symvar.
4-851
4 Functions Alphabetical List
transVar
Examples
Compute the inverse Z-transform of this expression with respect to the independent
variable x for the transformation variable k:
syms k x
F = 2*x/(x - 2)^2;
iztrans(F, x, k)
ans =
2^k + 2^k*(k - 1)
Compute the inverse Z-transform of this expression calling the iztrans function with
one argument. If you do not specify the independent variable, iztrans uses the variable
z.
syms z a k
F = exp(a/z);
iztrans(F, k)
ans =
a^k/factorial(k)
If you also do not specify the transformation variable, iztrans uses the variable n:
iztrans(F)
ans =
a^n/factorial(n)
Compute the inverse Z-transforms of these expressions. The results involve the
Kroneckers delta function.
syms n z
iztrans(1/z, z, n)
4-852
iztrans
ans =
kroneckerDelta(n - 1, 0)
ans =
kroneckerDelta(n - 2, 0) + 3*kroneckerDelta(n - 3, 0) +...
6*kroneckerDelta(n - 4, 0) + 5*kroneckerDelta(n - 5, 0)
f =
iztrans(F(z), z, n)
ans =
F(z)
Find the inverse Z-transform of this matrix. Use matrices of the same size to specify the
independent variables and transformation variables.
syms a b c d w x y z
iztrans([exp(x), 1; sin(y), i*z],[w, x; y, z],[a, b; c, d])
ans =
[ exp(x)*kroneckerDelta(a, 0), kroneckerDelta(b, 0)]
[ iztrans(sin(y), y, c), iztrans(z, z, d)*1i]
When the input arguments are nonscalars, iztrans acts on them element-wise. If
iztrans is called with both scalar and nonscalar arguments, then iztrans expands
the scalar arguments into arrays of the same size as the nonscalar arguments with all
elements of the array equal to the scalar.
syms w x y z a b c d
iztrans(x,[x, w; y, z],[a, b; c, d])
ans =
[ iztrans(x, x, a), x*kroneckerDelta(b, 0)]
[ x*kroneckerDelta(c, 0), x*kroneckerDelta(d, 0)]
4-853
4 Functions Alphabetical List
Note that nonscalar input arguments must have the same size.
When the first argument is a symbolic function, the second argument must be a scalar.
syms f1(x) f2(x) a b
f1(x) = exp(x);
f2(x) = x;
iztrans([f1, f2],x,[a, b])
ans =
[ iztrans(exp(x), x, a), iztrans(x, x, b)]
More About
Inverse Z-Transform
If R is a positive number, such that the function F(z) is analytic on and outside the circle
|z|=R, then the inverse Z-transform is defined as follows:
1
f (n ) = F ( z) zn -1dz, n = 0, 1, 2 ...
2p i
z =R
Tips
See Also
fourier | ifourier | ilaplace | kroneckerDelta | laplace | ztrans
4-854
jacobian
jacobian
Jacobian matrix
Syntax
jacobian(f,v)
Description
jacobian(f,v) computes the Jacobian matrix of f with respect to v. The (i,j) element of
f ( i )
the result is .
v ( j )
Examples
Jacobian of Vector Function
The Jacobian of a vector function is a matrix of the partial derivatives of that function.
Compute the Jacobian matrix of [x*y*z, y^2, x + z] with respect to [x, y, z].
syms x y z
jacobian([x*y*z, y^2, x + z], [x, y, z])
ans =
[ y*z, x*z, x*y]
[ 0, 2*y, 0]
[ 1, 0, 1]
Now, compute the Jacobian of [x*y*z, y^2, x + z] with respect to [x; y; z].
jacobian([x*y*z, y^2, x + z], [x; y; z])
4-855
4 Functions Alphabetical List
Compute the Jacobian of 2*x + 3*y + 4*z with respect to [x, y, z].
syms x y z
jacobian(2*x + 3*y + 4*z, [x, y, z])
ans =
[ 2, 3, 4]
ans =
2
3
4
ans =
2*x*y
sin(y)
ans =
[ 2*x*y, sin(y)]
Input Arguments
f Scalar or vector function
symbolic expression | symbolic function | symbolic vector
4-856
jacobian
Vector of variables with respect to which you compute Jacobian, specified as a symbolic
variable or vector of symbolic variables. If v is a scalar, then the result is equal to
the transpose of diff(f,v). If v is an empty symbolic object, such as sym([]), then
jacobian returns an empty symbolic object.
More About
Jacobian Matrix
f1 f1
x L
1 xn
J ( x1 , xn ) = M O M
fn L
f n
x1 xn
See Also
curl | diff | divergence | gradient | hessian | laplacian | potential |
vectorPotential
4-857
4 Functions Alphabetical List
jacobiP
Jacobi polynomials
Syntax
jacobiP(n,a,b,x)
Description
jacobiP(n,a,b,x) returns the nth degree Jacobi polynomial with parameters a and b
at x.
Examples
jacobiP(2,0.5,-3,6)
ans =
7.3438
syms n a b x
jacobiP(n,a,b,x)
ans =
jacobiP(n, a, b, x)
If the degree of the Jacobi polynomial is not specified, jacobiP cannot find the
polynomial and returns the function call.
Specify the degree of the Jacobi polynomial as 1 to return the form of the polynomial.
4-858
jacobiP
J = jacobiP(1,a,b,x)
J =
a/2 - b/2 + x*(a/2 + b/2 + 1)
To find the numeric value of a Jacobi polynomial, call jacobiP with the numeric values
directly. Do not substitute into the symbolic polynomial because the result can be
inaccurate due to round-off. Test this by using subs to substitute into the symbolic
polynomial, and compare the result with a numeric call.
ans =
101573673381249394050.64541318209
ans =
0.032559931334979678350422392588404
When subs is used to substitute into the symbolic polynomial, the numeric result is
subject to round-off error. The direct numerical call to jacobiP is accurate.
syms x
jacobiP([1 2],3,1,x)
ans =
[ 3*x + 1, 7*x^2 + (7*x)/2 - 1/2]
a = [1 2;3 1];
b = [2 2;1 3];
J = jacobiP(1,a,b,x)
4-859
4 Functions Alphabetical List
J =
[ (5*x)/2 - 1/2, 3*x]
[ 3*x + 1, 3*x - 1]
jacobiP acts element-wise on a and b to return a matrix of the same size as a and b.
syms x
fplot(jacobiP(1:3,3,3,x))
axis([-1 1 -2 2])
grid on
ylabel('P_n^{(\alpha,\beta)}(x)')
title('Zeros of Jacobi polynomials of degree=1,2,3 with a=3 and b=3');
legend('1','2','3','Location','best')
4-860
jacobiP
Prove P(3,a,b,x) and P(5,a,b,x) are orthogonal with respect to the weight function
(1 - x )a ( 1 - x )b by integrating their product over the interval [-1,1], where a = 3.5
and b = 7.2.
syms x
4-861
4 Functions Alphabetical List
a = 3.5;
b = 7.2;
P3 = jacobiP(3, a, b, x);
P5 = jacobiP(5, a, b, x);
w = (1-x)^a*(1+x)^b;
int(P3*P5*w, x, -1, 1)
ans =
0
Input Arguments
n Degree of Jacobi polynomial
nonnegative integer | vector of nonnegative integers | matrix of nonnegative integers
| multidimensional array of nonnegative integers | symbolic nonnegative integer |
symbolic variable | symbolic vector | symbolic matrix | symbolic function | symbolic
expression | symbolic multidimensional array
a Input
number | vector | matrix | multidimensional array | symbolic number | symbolic
vector | symbolic matrix | symbolic function | symbolic expression | symbolic
multidimensional array
b Input
number | vector | matrix | multidimensional array | symbolic number | symbolic
vector | symbolic matrix | symbolic function | symbolic expression | symbolic
multidimensional array
x Evaluation point
number | vector | matrix | multidimensional array | symbolic number | symbolic
vector | symbolic matrix | symbolic function | symbolic expression | symbolic
multidimensional array
4-862
jacobiP
More About
Jacobi Polynomials
( )
2 ncn c2n -2 P ( n, a, b, x) = c2n -1 c2n -2 c2 n x + a2 - b 2 P ( n - 1, a, b, x)
- 2 ( n - 1 + a) ( n - 1 + b ) c2 n P ( n - 2, a, b, x) ,
where
cn = n + a + b
P ( 0, a, b, x ) = 1
a-b a+b
P (1, a, b, x ) = + 1 + x.
2 2
For fixed real a>-1 and b>-1, the Jacobi polynomials are orthogonal on the interval
[-1,1] with respect to the weight function w ( x) = (1 - x ) ( 1 + x) b .
a
For a=0 and b=0, the Jacobi polynomials P(n,0,0,x) reduce to the Legendre polynomials
P(n, x).
The relation between Jacobi polynomials P(n,a,b,x) and Chebyshev polynomials of the
first kind T(n,x) is
2 2n ( n !)
2
1 1
T ( n, x) = P n, - , - , x .
( 2 n) ! 2 2
The relation between Jacobi polynomials P(n,a,b,x) and Chebyshev polynomials of the
second kind U(n,x) is
2 2n n ! ( n + 1 ) ! 1 1
U ( n, x) = P n, , , x .
( 2n + 1 ) ! 2 2
4-863
4 Functions Alphabetical List
The relation between Jacobi poynomials P(n,a,b,x) and Gegenbauer polynomials G(n,a,x)
is
1
G a + G (n + 2a )
2 1 1
G ( n, a, x ) = P n, a - , a - , x .
1 2 2
G ( 2a ) G n + a +
2
See Also
chebyshevT | chebyshevU | gegenbauerC | hermiteH | hypergeom | laguerreL |
legendreP
Introduced in R2014b
4-864
jordan
jordan
Jordan form of matrix
Syntax
J = jordan(A)
[V,J] = jordan(A)
Description
J = jordan(A) computes the Jordan canonical form (also called Jordan normal form)
of a symbolic or numeric matrix A. The Jordan form of a numeric matrix is extremely
sensitive to numerical errors. To compute Jordan form of a matrix, represent the
elements of the matrix by integers or ratios of small integers, if possible.
[V,J] = jordan(A) computes the Jordan form J and the similarity transform V. The
matrix V contains the generalized eigenvectors of A as columns, and V\A*V = J.
Examples
Compute the Jordan form and the similarity transform for this numeric matrix. Verify
that the resulting matrix V satisfies the condition V\A*V = J:
A = [1 -3 -2; -1 1 -1; 2 4 5]
[V, J] = jordan(A)
V\A*V
A =
1 -3 -2
-1 1 -1
2 4 5
V =
-1 1 -1
-1 0 0
2 0 1
4-865
4 Functions Alphabetical List
J =
2 1 0
0 2 0
0 0 3
ans =
2 1 0
0 2 0
0 0 3
See Also
charpoly | inv | eig | hermiteForm | smithForm
4-866
kroneckerDelta
kroneckerDelta
Kronecker delta function
Syntax
kroneckerDelta(m)
kroneckerDelta(m,n)
Description
kroneckerDelta(m) returns 1 if m == 0 and 0 if m ~= 0.
Examples
Note: For kroneckerDelta with numeric inputs, use the eq function instead.
Set symbolic variable m equal to symbolic variable n and test their equality using
kroneckerDelta.
syms m n
m = n;
kroneckerDelta(m,n)
ans =
1
4-867
4 Functions Alphabetical List
syms p q
kroneckerDelta(p,q)
ans =
kroneckerDelta(p - q, 0)
kroneckerDelta cannot decide if p == q and returns the function call with the
undecidable input. Note that kroneckerDelta(p, q) is equal to kroneckerDelta(p
- q, 0).
To force a logical result for undecidable inputs, use isAlways. The isAlways function
issues a warning and returns logical 0 (false) for undecidable inputs. Set the Unknown
option to false to suppress the warning.
ans =
logical
0
m = 0;
kroneckerDelta(m)
syms m
m = sym(0);
kroneckerDelta(m)
ans =
1
4-868
kroneckerDelta
V = 1:4
syms m
m = sym(3)
sol = kroneckerDelta(V,m)
V =
1 2 3 4
m =
3
sol =
[ 0, 0, 1, 0]
kroneckerDelta acts on V element-wise to return a vector, sol, which is the same size
as V. The third element of sol is 1 indicating that the third element of V equals m.
syms m
A = [m m+1 m+2;m-2 m-1 m]
B = [m m+3 m+2;m-1 m-1 m+1]
A =
[ m, m + 1, m + 2]
[ m - 2, m - 1, m]
B =
[ m, m + 3, m + 2]
[ m - 1, m - 1, m + 1]
sol = kroneckerDelta(A,B)
sol =
[ 1, 0, 1]
4-869
4 Functions Alphabetical List
[ 0, 1, 0]
kroneckerDelta acts on A and B element-wise to return the matrix sol which is the
same size as A and B. The elements of sol that are 1 indicate that the corresponding
elements of A and B are equal. The elements of sol that are 0 indicate that the
corresponding elements of A and B are not equal.
syms z n
sol = iztrans(1/(z-1), z, n)
sol =
1 - kroneckerDelta(n, 0)
Use this output as input to ztrans to return the initial input expression.
ztrans(sol, n, z)
ans =
z/(z - 1) - 1
b = [0 1 1];
a = [1 -0.5 0.3];
k = -20:20;
x = double(kroneckerDelta(sym(k)));
y = filter(b,a,x);
plot(k,y)
4-870
kroneckerDelta
Input Arguments
m Input
number | vector | matrix | multidimensional array | symbolic number | symbolic vector
| symbolic matrix | symbolic function | symbolic multidimensional array
4-871
4 Functions Alphabetical List
n Input
number | vector | matrix | multidimensional array | symbolic number | symbolic vector
| symbolic matrix | symbolic function | symbolic multidimensional array
More About
Kronecker Delta Function
0 if m n
d ( m, n ) =
1 if m = n
Tips
See Also
iztrans | ztrans
Introduced in R2014b
4-872
kummerU
kummerU
Confluent hypergeometric Kummer U function
Syntax
kummerU(a,b,z)
Description
kummerU(a,b,z) computes the value of confluent hypergeometric function, U(a,b,z).
If the real parts of z and a are positive values, then the integral representations of the
Kummer U function is as follows:
1 b-a -1
U ( a, b, z ) = e-zt ta -1 (1 + t ) dt
G (a )
0
Examples
Solve this equation. The solver returns the results in terms of the Kummer U function
and another hypergeometric function.
syms t z y(z)
dsolve(z^3*diff(y,2) + (z^2 + t)*diff(y) + z*y)
ans =
(C4*hypergeom(1i/2, 1 + 1i, t/(2*z^2)))/z^1i +...
(C3*kummerU(1i/2, 1 + 1i, t/(2*z^2)))/z^1i
4-873
4 Functions Alphabetical List
Compute the Kummer U function for these numbers. Because these numbers are not
symbolic objects, you get floating-point results.
A = [kummerU(-1/3, 2.5, 2)
kummerU(1/3, 2, pi)
kummerU(1/2, 1/3, 3*i)]
A =
0.8234 + 0.0000i
0.7284 + 0.0000i
0.4434 - 0.3204i
Compute the Kummer U function for the numbers converted to symbolic objects. For
most symbolic (exact) numbers, kummerU returns unresolved symbolic calls.
symA =
kummerU(-1/3, 5/2, 2)
kummerU(1/3, 2, pi)
kummerU(1/2, 1/3, 3i)
Use vpa to approximate symbolic results with the required number of digits.
vpa(symA,10)
ans =
0.8233667846
0.7284037305
0.4434362538 - 0.3204327531i
4-874
kummerU
syms a b z
[kummerU(-1, b, z)
kummerU(-2, b, z)
kummerU(-3, b, z)]
ans =
z - b
b - 2*z*(b + 1) + b^2 + z^2
6*z*(b^2/2 + (3*b)/2 + 1) - 2*b - 6*z^2*(b/2 + 1) - 3*b^2 - b^3 + z^3
ans =
(z^(1/2 - a)*exp(z/2)*besselk(a - 1/2, z/2))/pi^(1/2)
ans =
z^(1 - b)*exp(z)*igamma(b - 1, z)
kummerU(a, a, z)
ans =
exp(z)*igamma(1 - a, z)
ans =
1
4-875
4 Functions Alphabetical List
diff(kummerU(a, b, z), z)
ans =
(a*kummerU(a + 1, b, z)*(a - b + 1))/z - (a*kummerU(a, b, z))/z
ans =
((b - 2)/(a - 1) - 1)*kummerU(a, b, z) +...
(kummerU(a + 1, b, z)*(a - a*b + a^2))/(a - 1) -...
(z*kummerU(a, b, z))/(a - 1)
ans =
4/(3*pi^(1/2))
Input Arguments
a Parameter of Kummer U function
number | vector | symbolic number | symbolic variable | symbolic expression | symbolic
function | symbolic vector
4-876
kummerU
More About
Confluent Hypergeometric Function (Kummer U Function)
The confluent hypergeometric function (Kummer U function) is one of the solutions of the
differential equation
2
z y + ( b - z) y - ay = 0
2 z
z
1
Wa,b ( z ) = e- z 2
zb+1 2
U b - a + , 2b + 1, z
2
Tips
kummerU returns floating-point results for numeric arguments that are not symbolic
objects.
kummerU acts element-wise on nonscalar inputs.
All nonscalar arguments must have the same size. If one or two input arguments are
nonscalar, then kummerU expands the scalars into vectors or matrices of the same size
as the nonscalar arguments, with all elements equal to the corresponding scalar.
References
[1] Slater,L.J. Confluent Hypergeometric Functions. Handbook of Mathematical
Functions with Formulas, Graphs, and Mathematical Tables. (M. Abramowitz
and I. A. Stegun, eds.). New York: Dover, 1972.
See Also
hypergeom | whittakerM | whittakerW
Introduced in R2014b
4-877
4 Functions Alphabetical List
laguerreL
Generalized Laguerre Function and Laguerre Polynomials
Syntax
laguerreL(n,x)
laguerreL(n,a,x)
Description
laguerreL(n,x) returns the Laguerre polynomial of degree n if n is a nonnegative
integer. When n is not a nonnegative integer, laguerreL returns the Laguerre function.
For details, see Generalized Laguerre Function on page 4-883.
Examples
laguerreL(3,4.3)
ans =
2.5838
Find the Laguerre polynomial for symbolic inputs. Specify degree n as 3 to return the
explicit form of the polynomial.
syms x
4-878
laguerreL
laguerreL(3,x)
ans =
- x^3/6 + (3*x^2)/2 - 3*x + 1
If the degree of the Laguerre polynomial n is not specified, laguerreL cannot find the
polynomial. When laguerreL cannot find the polynomial, it returns the function call.
syms n x
laguerreL(n,x)
ans =
laguerreL(n, x)
syms a x
laguerreL(2,a,x)
ans =
(3*a)/2 - x*(a + 2) + a^2/2 + x^2/2 + 1
laguerreL(-2.7,3,2)
ans =
0.2488
syms x
laguerreL(-5/2, -3/2, x)
4-879
4 Functions Alphabetical List
syms x
laguerreL([1 2],x)
ans =
[ 1 - x, x^2/2 - 2*x + 1]
syms a
n = [2 3; 1 2];
xM = [x^2 11/7; -3.2 -x];
laguerreL(n,a,xM)
ans =
[ a^2/2 - a*x^2 + (3*a)/2 + x^4/2 - 2*x^2 + 1,...
a^3/6 + (3*a^2)/14 - (253*a)/294 - 676/1029]
[ a + 21/5,...
a^2/2 + a*x + (3*a)/2 + x^2/2 + 2*x + 1]
laguerreL acts element-wise on n and x to return a matrix of the same size as n and x.
syms x
expr = laguerreL(3,2,x);
limit(expr,x,Inf)
ans =
4-880
laguerreL
-Inf
Use diff to find the third derivative of the generalized Laguerre polynomial
laguerreL(n,a,x).
syms n a
expr = laguerreL(n,a,x);
diff(expr,x,3)
ans =
-laguerreL(n - 3, a + 3, x)
syms a x
expr = laguerreL(2,a,x);
taylor(expr,x)
ans =
(3*a)/2 - x*(a + 2) + a^2/2 + x^2/2 + 1
syms x
fplot(laguerreL(1:4, x))
axis([-2 10 -10 10])
grid on
ylabel('L_n(x)')
title('Laguerre polynomials of orders 1 through 4')
legend('1','2','3','4','Location','best')
4-881
4 Functions Alphabetical List
Input Arguments
n Degree of polynomial
number | vector | matrix | multidimensional array | symbolic number | symbolic vector
| symbolic matrix | symbolic function | symbolic multidimensional array
x Input
number | vector | matrix | multidimensional array | symbolic number | symbolic vector
| symbolic matrix | symbolic function | symbolic multidimensional array
4-882
laguerreL
a Input
number | vector | matrix | multidimensional array | symbolic number | symbolic vector
| symbolic matrix | symbolic function | symbolic multidimensional array
More About
Generalized Laguerre Function
n + a
laguerreL ( n, a, x ) = 1 F1 ( - n; a + 1; x ) .
a
For nonnegative integer values of n, the function returns the generalized Laguerre
polynomials that are orthogonal with respect to the scalar product
f 1, f 2 = e -x x a f 1 ( x ) f 2 ( x) dx.
0
In particular,
0 if n m
laguerreL ( n, a, x) ,laguerreL ( m, a, x) = G ( a + n + 1)
if n = m.
n!
Algorithms
The generalized Laguerre function is not defined for all values of parameters n
and a because certain restrictions on the parameters exist in the definition of the
hypergeometric functions. If the generalized Laguerre function is not defined for a
4-883
4 Functions Alphabetical List
particular pair of n and a, the laguerreL function returns an error message. See
Return Generalized Laguerre Function on page 4-879.
The calls laguerreL(n,x) and laguerreL(n,0,x) are equivalent.
If n is a nonnegative integer, the laguerreL function returns the explicit form of the
corresponding Laguerre polynomial.
n + a
The special values laguerreL ( n, a,0 ) = are implemented for arbitrary values of
a
n and a.
If n is a negative integer and a is a numerical noninteger value satisfying a-n, then
laguerreL returns 0.
If n is a negative integer and a is an integer satisfying a < -n, the function returns an
explicit expression defined by the reflection rule
a
laguerreL ( n, a, x ) = ( - 1) ex laguerreL ( - n - a - 1, a, - x )
If all arguments are numerical and at least one argument is a floating-point number,
then laguerreL(x) returns a floating-point number. For all other arguments,
laguerreL(n,a,x) returns a symbolic function call.
See Also
chebyshevT | chebyshevU | gegenbauerC | hermiteH | hypergeom | jacobiP |
legendreP
Introduced in R2014b
4-884
lambertw
lambertw
Lambert W function
Syntax
lambertw(x)
lambertw(k,x)
Description
lambertw(x) is the Lambert W function of x, which returns the principal branch of the
Lambert W function. Therefore, the syntax is equivalent to lambertw(0,x).
Examples
syms x W
solve(x == W*exp(W), W)
ans =
lambertw(0, x)
Verify that various branches of the Lambert W function are valid solutions of the
equation x = W*e :
W
k = -2:2
4-885
4 Functions Alphabetical List
syms x
isAlways(x - subs(W*exp(W), W, lambertw(k,x)) == 0)
k =
-2 -1 0 1 2
ans =
15 logical array
1 1 1 1 1
Compute the Lambert W functions for these numbers. Because these numbers are not
symbolic objects, you get floating-point results.
A = [0 -1/exp(1); pi i];
lambertw(A)
lambertw(-1, A)
ans =
0.0000 + 0.0000i -1.0000 + 0.0000i
1.0737 + 0.0000i 0.3747 + 0.5764i
ans =
-Inf + 0.0000i -1.0000 + 0.0000i
-0.3910 - 4.6281i -1.0896 - 2.7664i
Compute the Lambert W functions for the numbers converted to symbolic objects. For
most symbolic (exact) numbers, lambertw returns unresolved symbolic calls.
A = [0 -1/exp(sym(1)); pi i];
W0 = lambertw(A)
Wmin1 = lambertw(-1, A)
W0 =
[ 0, -1]
[ lambertw(0, pi), lambertw(0, 1i)]
Wmin1 =
[ -Inf, -1]
4-886
lambertw
Use vpa to approximate symbolic results with the required number of digits:
vpa(W0, 10)
vpa(Wmin1, 5)
ans =
[ 0, -1.0]
[ 1.073658195, 0.3746990207 + 0.576412723i]
ans =
[ -Inf, -1.0]
[ - 0.39097 - 4.6281i, - 1.0896 - 2.7664i]
Create the combined mesh and contour plot of the real value of the Lambert W function
on the complex plane.
syms x y real
fmesh(real(lambertw(x + i*y)), [-100, 100, -100, 100], 'ShowContours', 'on')
4-887
4 Functions Alphabetical List
Now, plot the imaginary value of the Lambert W function on the complex plane. This
function has a branch cut along the negative real axis. For better perspective, create the
mesh and contour plots separately.
4-888
lambertw
4-889
4 Functions Alphabetical List
Plot the absolute value of the Lambert W function on the complex plane.
4-890
lambertw
syms x y clear
Plot the principal branch . Add the branch . Adjust the axes limits and add
the title.
syms x
4-891
4 Functions Alphabetical List
fplot(lambertw(x))
hold on
fplot(lambertw(-1, x))
axis([-0.5, 4, -4, 2])
title('Lambert W function, two main branches')
Input Arguments
x Argument of Lambert W function
number | symbolic number | symbolic variable | symbolic expression | symbolic
function | vector | matrix
4-892
lambertw
More About
Lambert W Function
The Lambert W function W(x) represents the solutions y of the equation ye y = x for any
complex number x.
For real x where - e-1 < x < 0 , the equation has exactly two real solutions. The
larger solution is represented by y = lambertW(x) and the smaller solution by y =
lambertW(-1,x).
For x = - e-1 , the equation has exactly one real solution y = -1 = lambertW(0, -exp(-1))
= lambertW(-1, -exp(-1)).
Algorithms
The equation x = w(x)ew(x) has infinitely many solutions on the complex plane.
These solutions are represented by w = lambertw(k,x) with the branch index k
ranging over the integers.
For all real x 0, the equation x = w(x)ew(x) has exactly one real solution. It is
represented by w = lambertw(x) or, equivalently, w = lambertw(0,x).
4-893
4 Functions Alphabetical List
For all real x in the range -1/e < x < 0, there are exactly two distinct real
solutions. The larger one is represented by w = lambertw(x), and the smaller one is
represented by w = lambertw(-1,x).
For w = -1/e, there is exactly one real solution lambertw(0, -exp(-1)) =
lambertw(-1, -exp(-1)) = -1.
lambertw(k,x) returns real values only if k = 0 or k = -1. For k <> {0, -1},
lambertw(k,x) is always complex.
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, lambertw 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] Corless, R.M, G.H. Gonnet, D.E.G. Hare, D.J. Jeffrey, and D.E. Knuth On the
Lambert W Function Advances in Computational Mathematics, vol.5, pp. 329
359, 1996.
[2] Corless, R.M, G.H. Gonnet, D.E.G. Hare, and D.J. Jeffrey Lamberts W Function in
Maple The Maple Technical Newsletter (MapleTech), vol.9, pp. 1222, 1993.
See Also
Functions
wrightOmega
4-894
laplace
laplace
Laplace transform
Syntax
laplace(f)
laplace(f,transVar)
laplace(f,var,transVar)
Description
laplace(f) returns the Laplace transform of f using the default independent variable
t and the default transformation variable s. If f does not contain t, laplace uses
symvar.
Input Arguments
f
var
Symbolic variable representing the independent variable. This variable is often called the
time variable.
Default: The variable t. If f does not contain t, then the default variable is determined
by symvar.
4-895
4 Functions Alphabetical List
transVar
Examples
Compute the Laplace transform of this expression with respect to the variable x for the
transformation variable y:
syms x y
f = 1/sqrt(x);
laplace(f, x, y)
ans =
pi^(1/2)/y^(1/2)
Compute the Laplace transform of this expression calling the laplace function with one
argument. If you do not specify the independent variable, laplace uses the variable t.
syms a t y
f = exp(-a*t);
laplace(f, y)
ans =
1/(a + y)
If you also do not specify the transformation variable, laplace uses the variable s:
laplace(f)
ans =
1/(a + s)
Compute the following Laplace transforms that involve the Dirac and Heaviside
functions:
syms t s
laplace(dirac(t - 3), t, s)
ans =
4-896
laplace
exp(-3*s)
laplace(heaviside(t - pi), t, s)
ans =
exp(-pi*s)/s
syms f(t) s
F = laplace(f, t, s)
F =
laplace(f(t), t, s)
ilaplace(F, s, t)
ans =
f(t)
The Laplace transform of a function is related to the Laplace transform of its derivative:
syms f(t) s
laplace(diff(f(t), t), t, s)
ans =
s*laplace(f(t), t, s) - f(0)
Find the Laplace transform of this matrix. Use matrices of the same size to specify the
independent variables and transformation variables.
syms a b c d w x y z
laplace([exp(x), 1; sin(y), i*z],[w, x; y, z],[a, b; c, d])
ans =
[ exp(x)/a, 1/b]
[ 1/(c^2 + 1), 1i/d^2]
When the input arguments are nonscalars, laplace acts on them element-wise. If
laplace is called with both scalar and nonscalar arguments, then laplace expands
the scalar arguments into arrays of the same size as the nonscalar arguments with all
elements of the array equal to the scalar.
4-897
4 Functions Alphabetical List
syms w x y z a b c d
laplace(x,[x, w; y, z],[a, b; c, d])
ans =
[ 1/a^2, x/b]
[ x/c, x/d]
Note that nonscalar input arguments must have the same size.
When the first argument is a symbolic function, the second argument must be a scalar.
syms f1(x) f2(x) a b
f1(x) = exp(x);
f2(x) = x;
laplace([f1, f2],x,[a, b])
ans =
[ 1/(a - 1), 1/b^2]
More About
Laplace Transform
- st
F( s) = f (t ) e dt.
0
Tips
See Also
fourier | ifourier | ilaplace | iztrans | ztrans
4-898
laplacian
laplacian
Laplacian of scalar function
Syntax
laplacian(f,x)
laplacian(f)
Description
laplacian(f,x) computes the Laplacian of the scalar function or functional expression
f with respect to the vector x in Cartesian coordinates.
Input Arguments
f
Default: Vector constructed from all symbolic variables found in f. The order of
variables in this vector is defined by symvar.
Examples
Compute the Laplacian of this symbolic expression. By default, laplacian computes
the Laplacian of an expression with respect to a vector of all variables found in that
expression. The order of variables is defined by symvar.
4-899
4 Functions Alphabetical List
syms x y t
laplacian(1/x^3 + y^2 - log(t))
ans =
1/t^2 + 12/x^5 + 2
Compute the Laplacian of this function with respect to the vector [x, y, z]:
L = laplacian(f, [x y z])
L(x, y, z) =
6*z + 2/x^3 + 2
Alternatives
The Laplacian of a scalar function or functional expression is the divergence of the
gradient of that function or expression:
D f = (f )
Therefore, you can compute the Laplacian using the divergence and gradient
functions:
syms f(x, y)
divergence(gradient(f(x, y)), [x y])
More About
Laplacian of Scalar Function
The Laplacian of the scalar function or functional expression f with respect to the vector
X=(X1,...,Xn) is the sum of the second derivatives of f with respect to X1,...,Xn:
n
2 f
Df = x2i
i =1 i
4-900
laplacian
Tips
See Also
curl | diff | divergence | gradient | hessian | jacobian | potential |
vectorPotential
Introduced in R2012a
4-901
4 Functions Alphabetical List
latex
LaTeX form of symbolic expression
Syntax
latex(S)
Description
latex(S) returns the LaTeX form of the symbolic expression S.
Examples
LaTeX Form of Symbolic Expression
Find the LaTeX form of the symbolic expressions x^2 + 1/x and sin(pi*x) + alpha.
syms x phi
latex(x^2 + 1/x)
latex(sin(pi*x) + phi)
ans =
117 char array
\frac{1}{x} + x^2
ans =
141 char array
\mathrm{phi} + \sin\!\left(\pi\, x\right)
4-902
latex
M =
[ 1/3, x]
[ exp(x), x^2]
latexM =
\left(\begin{array}{cc} \frac{1}{3} & x\\ \mathrm{e}^{x} &...
x^2 \end{array}\right)
Create the x-axis ticks by spanning the x-axis limits at intervals of pi/2. Convert the
axis limits to precise multiples of pi/2 using round and get the symbolic tick values in
S. Display the ticks by setting the XTick property of a to S. Create the LaTeX labels for
the x-axis by using arrayfun to apply latex to S and then concatenating $. Display the
labels by assigning them to the XTickLabel property of a.
Repeat these steps for the y-axis. Set the x- and y-axes labels and the title using the
latex interpreter.
syms x y
f = y.*sin(x)-x.*cos(y);
fsurf(f,[-2*pi 2*pi])
a = gca;
a.TickLabelInterpreter = 'latex';
a.Box = 'on';
a.BoxStyle = 'full';
S = sym(a.XLim(1):pi/2:a.XLim(2));
S = sym(round(vpa(S/pi*2))*pi/2);
a.XTick = double(S);
a.XTickLabel = strcat('$',arrayfun(@latex, S, 'UniformOutput', false),'$');
S = sym(a.YLim(1):pi/2:a.YLim(2));
S = sym(round(vpa(S/pi*2))*pi/2);
a.YTick = double(S);
a.YTickLabel = strcat('$',arrayfun(@latex, S, 'UniformOutput', false),'$');
xlabel('x','Interpreter','latex');
ylabel('y','Interpreter','latex');
4-903
4 Functions Alphabetical List
zlabel('z','Interpreter','latex');
title(['$' latex(f) '$ for $x$ and $y$ in $[-2\pi,2\pi]$'],'Interpreter','latex')
Input Arguments
S Input
symbolic number | symbolic variable | symbolic vector | symbolic matrix | symbolic
multidimensional array | symbolic function | symbolic expression
4-904
latex
See Also
ccode | fortran | pretty | texlabel
4-905
4 Functions Alphabetical List
lcm
Least common multiple
Syntax
lcm(A)
lcm(A,B)
Description
lcm(A) finds the least common multiple of all elements of A.
Examples
Find the least common multiple of these four integers, specified as elements of a symbolic
vector.
A =
[ 4420, -128, 8984, -488]
ans =
9689064320
4-906
lcm
lcm(A)
A =
[ 4420, -128]
[ 8984, -488]
ans =
9689064320
Find the least common multiple of these rational numbers, specified as elements of a
symbolic vector.
lcm(sym([3/4, 7/3, 11/2, 12/3, 33/4]))
ans =
924
Find the least common multiple of these complex numbers, specified as elements of a
symbolic vector.
lcm(sym([10 - 5*i, 20 - 10*i, 30 - 15*i]))
ans =
- 60 + 30i
Find the least common multiples for the elements of these two matrices.
A = sym([309, 186; 486, 224]);
B = sym([558, 444; 1024, 1984]);
lcm(A,B)
4-907
4 Functions Alphabetical List
ans =
[ 57474, 13764]
[ 248832, 13888]
Find the least common multiples for the elements of matrix A and the value 99. Here,
lcm expands 99 into the 2-by-2 matrix with all elements equal to 99.
lcm(A,99)
ans =
[ 10197, 6138]
[ 5346, 22176]
syms x
lcm(x^3 - 3*x^2 + 3*x - 1, x^2 - 5*x + 4)
ans =
(x - 4)*(x^3 - 3*x^2 + 3*x - 1)
Find the least common multiple of these multivariate polynomials. Because there are
more than two polynomials, specify them as elements of a symbolic vector.
syms x y
lcm([x^2*y + x^3, (x + y)^2, x^2 + x*y^2 + x*y + x + y^3 + y])
ans =
(x^3 + y*x^2)*(x^2 + x*y^2 + x*y + x + y^3 + y)
Input Arguments
A Input value
number | symbolic number | symbolic variable | symbolic expression | symbolic
function | symbolic vector | symbolic matrix
4-908
lcm
B Input value
number | symbolic number | symbolic variable | symbolic expression | symbolic
function | symbolic vector | symbolic matrix
More About
Tips
Calling lcm for numbers that are not symbolic objects invokes the MATLAB lcm
function.
The MATLAB lcm function does not accept rational or complex arguments. To find
the least common multiple of rational or complex numbers, convert these numbers to
symbolic objects by using sym, and then use lcm.
Nonscalar arguments must have the same size. If one input arguments is nonscalar,
then lcm expands the scalar into a vector or matrix of the same size as the nonscalar
argument, with all elements equal to the corresponding scalar.
See Also
gcd
Introduced in R2014b
4-909
4 Functions Alphabetical List
ldivide, .\
Symbolic array left division
Syntax
B.\A
ldivide(B,A)
Description
B.\A divides A by B.
Examples
B = sym('b', [2 3])
B =
[ b1_1, b1_2, b1_3]
[ b2_1, b2_2, b2_3]
syms a
B.\sin(a)
ans =
[ sin(a)/b1_1, sin(a)/b1_2, sin(a)/b1_3]
[ sin(a)/b2_1, sin(a)/b2_2, sin(a)/b2_3]
4-910
ldivide, .\
H =
[ 1, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
d =
[ 1, 0, 0]
[ 0, 2, 0]
[ 0, 0, 3]
Divide d by H by using the elementwise left division operator .\. This operator divides
each element of the first matrix by the corresponding element of the second matrix. The
dimensions of the matrices must be the same.
H.\d
ans =
[ 1, 0, 0]
[ 0, 6, 0]
[ 0, 0, 15]
f1(x) =
(x^2 + 5*x + 6)/x^2
Input Arguments
A Input
symbolic variable | symbolic vector | symbolic matrix | symbolic multidimensional array
| symbolic function | symbolic expression
4-911
4 Functions Alphabetical List
B Input
symbolic variable | symbolic vector | symbolic matrix | symbolic multidimensional array
| symbolic function | symbolic expression
See Also
ctranspose | minus | mldivide | mpower | mrdivide | mtimes | plus | power |
rdivide | times | transpose
4-912
le
le
Define less than or equal to relation
Compatibility
In previous releases, le in some cases evaluated inequalities involving only symbolic
numbers and returned logical 1 or 0. To obtain the same results as in previous releases,
wrap inequalities in isAlways. For example, use isAlways(A <= B).
Syntax
A <= B
le(A,B)
Description
A <= B creates a less than or equal to relation.
Input Arguments
A
4-913
4 Functions Alphabetical List
Examples
Use assume and the relational operator <= to set the assumption that x is less than or
equal to 3:
syms x
assume(x <= 3)
Solve this equation. The solver takes into account the assumption on variable x, and
therefore returns these three solutions.
ans =
1
2
3
syms x
cond = (abs(sin(x)) <= 1/2);
for i = 0:sym(pi/12):sym(pi)
if subs(cond, x, i)
disp(i)
end
end
Use the for loop with step /24 to find angles from 0 to that satisfy that condition:
0
pi/12
pi/6
(5*pi)/6
(11*pi)/12
pi
Alternatives
You can also define this relation by combining an equation and a less than relation.
Thus, A <= B is equivalent to (A < B) | (A == B).
4-914
le
More About
Tips
Calling <= or le for non-symbolic A and B invokes the MATLAB le function. This
function returns a logical array with elements set to logical 1 (true) where A is less
than or equal to B; otherwise, it returns logical 0 (false).
If both A and B are arrays, then these arrays must have the same dimensions. A <= B
returns an array of relations A(i,j,...) <= B(i,j,...)
If one input is scalar and the other an array, then the scalar input is expanded into
an array of the same dimensions as the other array. In other words, if A is a variable
(for example, x), and B is an m-by-n matrix, then A is expanded into m-by-n matrix of
elements, each set to x.
The field of complex numbers is not an ordered field. MATLAB projects complex
numbers in relations to a real axis. For example, x <= i becomes x <= 0, and x <=
3 + 2*i becomes x <= 3.
See Also
eq | ge | gt | isAlways | lt | ne
Introduced in R2012a
4-915
4 Functions Alphabetical List
legendreP
Legendre polynomials
Syntax
legendreP(n,x)
Description
legendreP(n,x) returns the nth degree Legendre polynomial at x.
Examples
legendreP(3,5.6)
ans =
430.6400
syms x
legendreP(2,x)
ans =
(3*x^2)/2 - 1/2
If you do not specify a numerical value for the degree n, the legendreP function cannot
find the explicit form of the polynomial and returns the function call.
syms n
4-916
legendreP
legendreP(n,x)
ans =
legendreP(n, x)
syms x
legendreP([1 2],x)
ans =
[ x, (3*x^2)/2 - 1/2]
If multiple inputs are specified as a vector, matrix, or multidimensional array, the inputs
must be the same size. Find the Legendre polynomials where input arguments n and x
are matrices.
n = [2 3; 1 2];
xM = [x^2 11/7; -3.2 -x];
legendreP(n,xM)
ans =
[ (3*x^4)/2 - 1/2, 2519/343]
[ -16/5, (3*x^2)/2 - 1/2]
legendreP acts element-wise on n and x to return a matrix of the same size as n and x.
syms x
expr = legendreP(4,x);
limit(expr,x,-Inf)
ans =
Inf
Use diff to find the third derivative of the Legendre polynomial of degree 5.
4-917
4 Functions Alphabetical List
syms n
expr = legendreP(5,x);
diff(expr,x,3)
ans =
(945*x^2)/2 - 105/2
syms x
expr = legendreP(2,x);
taylor(expr,x)
ans =
(3*x^2)/2 - 1/2
syms x y
fplot(legendreP(1:4, x))
axis([-1.5 1.5 -1 1])
grid on
ylabel('P_n(x)')
title('Legendre polynomials of degrees 1 through 4')
legend('1','2','3','4','Location','best')
4-918
legendreP
syms x
roots = vpasolve(legendreP(7,x) == 0)
roots =
-0.94910791234275852452618968404785
-0.74153118559939443986386477328079
-0.40584515137739716690660641207696
0
0.40584515137739716690660641207696
4-919
4 Functions Alphabetical List
0.74153118559939443986386477328079
0.94910791234275852452618968404785
Input Arguments
n Degree of polynomial
nonnegative number | vector | matrix | multidimensional array | symbolic number |
symbolic vector | symbolic matrix | symbolic function | symbolic multidimensional array
x Input
number | vector | matrix | multidimensional array | symbolic number | symbolic vector
| symbolic matrix | symbolic function | symbolic multidimensional array
More About
Legendre Polynomial
1 dn n
n(
P ( n, x ) = x2 - 1) .
n
2 n ! dx
2n - 1 n- 1
P ( n, x ) = xP ( n - 1, x) - P ( n - 2, x) ,
n n
where
P ( 0, x) = 1
P (1, x) = x.
4-920
legendreP
The Legendre polynomials are orthogonal on the interval [-1,1] with respect to the weight
function w(x)=1.
1
P ( n, x ) = G n, , x .
2
P ( n, x ) = P ( n, 0, 0, x ) .
See Also
chebyshevT | chebyshevU | gegenbauerC | hermiteH | hypergeom | jacobiP |
laguerreL
Introduced in R2014b
4-921
4 Functions Alphabetical List
limit
Compute limit of symbolic expression
Syntax
limit(expr,x,a)
limit(expr,a)
limit(expr)
limit(expr,x,a,'left')
limit(expr,x,a,'right')
Description
limit(expr,x,a) computes bidirectional limit of the symbolic expression expr when x
approaches a.
limit(expr,a) computes bidirectional limit of the symbolic expression expr when the
default variable approaches a.
limit(expr) computes bidirectional limit of the symbolic expression expr when the
default variable approaches 0.
Examples
Compute bidirectional limits for the following expressions:
syms x h
limit(sin(x)/x)
limit((sin(x + h) - sin(x))/h, h, 0)
4-922
limit
ans =
1
ans =
cos(x)
Compute the limits from the left and right for the following expressions:
syms x
limit(1/x, x, 0, 'right')
limit(1/x, x, 0, 'left')
ans =
Inf
ans =
-Inf
ans =
[ exp(a), 0]
See Also
diff | taylor
4-923
4 Functions Alphabetical List
linsolve
Solve linear system of equations given in matrix form
Syntax
X = linsolve(A,B)
[X,R] = linsolve(A,B)
Description
X = linsolve(A,B) solves the matrix equation AX=B. In particular, if B is a column
vector, linsolve solves a linear system of equations given in the matrix form.
[X,R] = linsolve(A,B) solves the matrix equation AX=B and returns the reciprocal
of the condition number of A if A is a square matrix, and the rank of A otherwise.
Input Arguments
A
Coefficient matrix.
Output Arguments
X
4-924
linsolve
Examples
Define the matrix equation using the following matrices A and B:
syms x y z
A = [x 2*x y; x*z 2*x*z y*z+z; 1 0 1];
B = [z y; z^2 y*z; 0 0];
Use linsolve to solve this equation. Assigning the result of the linsolve call to a
single output argument, you get the matrix of solutions:
X = linsolve(A, B)
X =
[ 0, 0]
[ z/(2*x), y/(2*x)]
[ 0, 0]
To return the solution and the reciprocal of the condition number of the square coefficient
matrix, assign the result of the linsolve call to a vector of two output arguments:
syms a x y z
A = [a 0 0; 0 a 0; 0 0 1];
B = [x; y; z];
[X, R] = linsolve(A, B)
X =
x/a
y/a
z
R =
1/(max(abs(a), 1)*max(1/abs(a), 1))
If the coefficient matrix is rectangular, linsolve returns the rank of the coefficient
matrix as the second output argument:
syms a b x y
A = [a 0 1; 1 b 0];
B = [x; y];
[X, R] = linsolve(A, B)
4-925
4 Functions Alphabetical List
X =
x/a
-(x - a*y)/(a*b)
0
R =
2
More About
Matrix Representation of System of Linear Equations
a11 a1n
A= M O M
a
m1 L amn
b
r 1
b= M
b
m
Tips
If the solution is not unique, linsolve issues a warning, chooses one solution and
returns it.
If the system does not have a solution, linsolve issues a warning and returns X with
all elements set to Inf.
4-926
linsolve
Calling linsolve for numeric matrices that are not symbolic objects invokes the
MATLAB linsolve function. This function accepts real arguments only. If your
system of equations uses complex numbers, use sym to convert at least one matrix to a
symbolic matrix, and then call linsolve.
See Also
cond | dsolve | equationsToMatrix | inv | norm | odeToVectorField | rank |
solve | symvar | vpasolve
Introduced in R2012b
4-927
4 Functions Alphabetical List
log
Natural logarithm of entries of symbolic matrix
Syntax
Y = log(X)
Description
Y = log(X) returns the natural logarithm of X.
Input Arguments
X
Output Arguments
Y
Examples
Compute the natural logarithm of each entry of this symbolic matrix:
syms x
M = x*hilb(2);
log(M)
ans =
4-928
log
[ log(x), log(x/2)]
[ log(x/2), log(x/3)]
ans =
3/x
See Also
log10 | log2
4-929
4 Functions Alphabetical List
log10
Logarithm base 10 of entries of symbolic matrix
Syntax
Y = log10(X)
Description
Y = log10(X) returns the logarithm to the base 10 of X. If X is a matrix, Y is a matrix of
the same size, each entry of which is the logarithm of the corresponding entry of X.
See Also
log | log2
4-930
log2
log2
Logarithm base 2 of entries of symbolic matrix
Syntax
Y = log2(X)
Description
Y = log2(X) returns the logarithm to the base 2 of X. If X is a matrix, Y is a matrix of
the same size, each entry of which is the logarithm of the corresponding entry of X.
See Also
log | log10
4-931
4 Functions Alphabetical List
logical
Check validity of equation or inequality
Syntax
logical(cond)
Description
logical(cond) checks whether the condition cond is valid. To test conditions that
require assumptions or simplifications, use isAlways instead of logical.
Input Arguments
cond
Examples
Use logical to check if 3/5 is less than 2/3:
ans =
logical
1
Check the validity of this equation using logical. Without an additional assumption
that x is nonnegative, this equation is invalid.
syms x
logical(x == sqrt(x^2))
4-932
logical
ans =
logical
0
Use assume to set an assumption that x is nonnegative. Now the expression sqrt(x^2)
evaluates to x, and logical returns 1:
assume(x >= 0)
logical(x == sqrt(x^2))
ans =
logical
1
ans =
logical
0
ans =
logical
1
Check if the following two conditions are both valid. To check if several conditions are
valid at the same time, combine these conditions by using the logical operator and or its
shortcut &.
syms x
logical(1 < 2 & x == x)
ans =
logical
4-933
4 Functions Alphabetical List
Check this inequality. Note that logical evaluates the left side of the inequality.
ans =
logical
1
syms x
logical(int(x, x, 0, 2) - 1 == 1)
ans =
logical
1
Do not use logical to check equations and inequalities that require simplification or
mathematical transformations. For such equations and inequalities, logical might
return unexpected results. For example, logical does not recognize mathematical
equivalence of these expressions:
syms x
logical(sin(x)/cos(x) == tan(x))
ans =
logical
0
logical(sin(x)/cos(x) ~= tan(x))
ans =
logical
1
isAlways(sin(x)/cos(x) == tan(x))
4-934
logical
ans =
logical
1
isAlways(sin(x)/cos(x) ~= tan(x))
More About
Tips
For symbolic equations, logical returns logical 1 (true) only if the left and right
sides are identical. Otherwise, it returns logical 0 (false).
For symbolic inequalities constructed with ~=, logical returns logical 0 (false)
only if the left and right sides are identical. Otherwise, it returns logical 1 (true).
For all other inequalities (constructed with <, <=, >, or >=), logical returns logical
1 if it can prove that the inequality is valid and logical 0 if it can prove that the
inequality is invalid. If logical cannot determine whether such inequality is valid or
not, it throws an error.
logical evaluates expressions on both sides of an equation or inequality, but does
not simplify or mathematically transform them. To compare two expressions applying
mathematical transformations and simplifications, use isAlways.
logical typically ignores assumptions on variables.
See Also
assume | assumeAlso | assumptions | in | isAlways | isequal | isequaln |
isfinite | isinf | isnan | sym | syms
Introduced in R2012a
4-935
4 Functions Alphabetical List
logint
Logarithmic integral function
Syntax
logint(X)
Description
logint(X) represents the logarithmic integral function (integral logarithm).
Examples
Compute integral logarithms for these numbers. Because these numbers are not symbolic
objects, logint returns floating-point results.
A =
0.0737 + 3.4227i 0.0000 + 0.0000i -0.1187 + 0.0000i -0.3787 + 0.0000i...
-Inf + 0.0000i 1.0452 + 0.0000i 6.1656 + 0.0000i
Compute integral logarithms for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, logint returns unresolved symbolic calls.
symA =
[ logint(-1), 0, logint(1/4), logint(1/2), -Inf, logint(2), logint(10)]
4-936
logint
vpa(symA)
ans =
[ 0.07366791204642548599010096523015...
+ 3.4227333787773627895923750617977i,...
0,...
-0.11866205644712310530509570647204,...
-0.37867104306108797672720718463656,...
-Inf,...
1.0451637801174927848445888891946,...
6.1655995047872979375229817526695]
syms x
fplot(logint(x), [0, 10])
grid on
4-937
4 Functions Alphabetical List
syms x
diff(logint(x), x)
diff(logint(x), x, x)
ans =
1/log(x)
4-938
logint
ans =
-1/(x*log(x)^2)
Find the right and left limits of this expression involving logint:
ans =
Inf
ans =
0
Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
More About
Logarithmic Integral Function
The logarithmic integral function, also called the integral logarithm, is defined as follows:
x
1
logint ( x) = Li ( x ) = ln (t ) dt
0
Tips
logint(sym(0)) returns 1.
logint(sym(1)) returns -Inf.
logint(z) = ei(log(z)) for all complex z.
4-939
4 Functions Alphabetical List
References
[1] Gautschi, W., and W. F. Cahill. Exponential Integral and Related Functions.
Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical
Tables. (M. Abramowitz and I. A. Stegun, eds.). New York: Dover, 1972.
See Also
coshint | cosint | ei | expint | int | log | sinhint | sinint | ssinint
Introduced in R2014a
4-940
logm
logm
Matrix logarithm
Syntax
R = logm(A)
Description
R = logm(A) computes the matrix logarithm of the square matrix A.
Examples
Matrix Logarithm
Compute the matrix logarithm for the 2-by-2 matrix.
syms x
A = [x 1; 0 -x];
logm(A)
ans =
[ log(x), log(x)/(2*x) - log(-x)/(2*x)]
[ 0, log(-x)]
Input Arguments
A Input matrix
square matrix
4-941
4 Functions Alphabetical List
Output Arguments
R Resulting matrix
symbolic matrix
See Also
eig | expm | funm | jordan | sqrtm
Introduced in R2014b
4-942
lt
lt
Define less than relation
Compatibility
In previous releases, lt in some cases evaluated inequalities involving only symbolic
numbers and returned logical 1 or 0. To obtain the same results as in previous releases,
wrap inequalities in isAlways. For example, use isAlways(A < B).
Syntax
A < B
lt(A,B)
Description
A < B creates a less than relation.
Input Arguments
A
Examples
Use assume and the relational operator < to set the assumption that x is less than 3:
4-943
4 Functions Alphabetical List
syms x
assume(x < 3)
Solve this equation. The solver takes into account the assumption on variable x, and
therefore returns these two solutions.
ans =
1
2
syms x
cond = abs(sin(x)) + abs(cos(x)) < 6/5;
Use the for loop with step /24 to find angles from 0 to that satisfy that condition:
for i = 0:sym(pi/24):sym(pi)
if subs(cond, x, i)
disp(i)
end
end
0
pi/24
(11*pi)/24
pi/2
(13*pi)/24
(23*pi)/24
pi
More About
Tips
Calling < or lt for non-symbolic A and B invokes the MATLAB lt function. This
function returns a logical array with elements set to logical 1 (true) where A is less
than B; otherwise, it returns logical 0 (false).
If both A and B are arrays, then these arrays must have the same dimensions. A < B
returns an array of relations A(i,j,...) < B(i,j,...)
4-944
lt
If one input is scalar and the other an array, then the scalar input is expanded into
an array of the same dimensions as the other array. In other words, if A is a variable
(for example, x), and B is an m-by-n matrix, then A is expanded into m-by-n matrix of
elements, each set to x.
The field of complex numbers is not an ordered field. MATLAB projects complex
numbers in relations to a real axis. For example, x < i becomes x < 0, and x < 3
+ 2*i becomes x < 3.
See Also
eq | ge | gt | isAlways | le | ne
Introduced in R2012a
4-945
4 Functions Alphabetical List
lu
LU factorization
Syntax
[L,U] = lu(A)
[L,U,P] = lu(A)
[L,U,p] = lu(A,'vector')
[L,U,p,q] = lu(A,'vector')
[L,U,P,Q,R] = lu(A)
[L,U,p,q,R] = lu(A,'vector')
lu(A)
Description
[L,U] = lu(A) returns an upper triangular matrix U and a matrix L, such that A =
L*U. Here, L is a product of the inverse of the permutation matrix and a lower triangular
matrix.
lu(A) returns the matrix that contains the strictly lower triangular matrix L (the matrix
without its unit diagonal) and the upper triangular matrix U as submatrices. Thus,
4-946
lu
Input Arguments
A
'vector'
Output Arguments
L
Lower triangular matrix or a product of the inverse of the permutation matrix and a
lower triangular matrix.
Permutation matrix.
Row vector.
Row vector.
Permutation matrix.
4-947
4 Functions Alphabetical List
Examples
Compute the LU factorization of this matrix. Because these numbers are not symbolic
objects, you get floating-point results.
L =
1.0000 0 0
0.2500 1.0000 0
0 0.5714 1.0000
U =
2.0000 -3.0000 -1.0000
0 1.7500 -0.7500
0 0 -0.5714
Now convert this matrix to a symbolic object, and compute the LU factorization:
L =
[ 1, 0, 0]
[ 1/4, 1, 0]
[ 0, 4/7, 1]
U =
[ 2, -3, -1]
[ 0, 7/4, -3/4]
[ 0, 0, -4/7]
Compute the LU factorization returning the lower and upper triangular matrices and the
permutation matrix:
syms a
[L, U, P] = lu(sym([0 0 a; a 2 3; 0 a 2]))
L =
[ 1, 0, 0]
4-948
lu
[ 0, 1, 0]
[ 0, 0, 1]
U =
[ a, 2, 3]
[ 0, a, 2]
[ 0, 0, a]
P =
0 1 0
0 0 1
1 0 0
syms a
A = [0 0 a; a 2 3; 0 a 2];
[L, U, p] = lu(A, 'vector')
L =
[ 1, 0, 0]
[ 0, 1, 0]
[ 0, 0, 1]
U =
[ a, 2, 3]
[ 0, a, 2]
[ 0, 0, a]
p =
2 3 1
isAlways(A(p,:) == L*U)
ans =
33 logical array
1 1 1
1 1 1
1 1 1
P = zeros(3, 3);
for i = 1:3
P(i, p(i)) = 1;
end
P
4-949
4 Functions Alphabetical List
P =
0 1 0
0 0 1
1 0 0
syms a
A = [a, 2, 3*a; 2*a, 3, 4*a; 4*a, 5, 6*a];
[L, U, p, q] = lu(A, 'vector')
L =
[ 1, 0, 0]
[ 2, 1, 0]
[ 4, 3, 1]
U =
[ a, 2, 3*a]
[ 0, -1, -2*a]
[ 0, 0, 0]
p =
1 2 3
q =
1 2 3
isAlways(A(p, q) == L*U)
ans =
33 logical array
1 1 1
1 1 1
1 1 1
Compute the LU factorization of this matrix returning the lower and upper triangular
matrices, permutation matrices, and the scaling matrix:
syms a
A = [0, a; 1/a, 0; 0, 1/5; 0,-1];
[L, U, P, Q, R] = lu(A)
L =
[ 1, 0, 0, 0]
[ 0, 1, 0, 0]
4-950
lu
[ 0, 1/(5*a), 1, 0]
[ 0, -1/a, 0, 1]
U =
[ 1/a, 0]
[ 0, a]
[ 0, 0]
[ 0, 0]
P =
0 1 0 0
1 0 0 0
0 0 1 0
0 0 0 1
Q =
1 0
0 1
R =
[ 1, 0, 0, 0]
[ 0, 1, 0, 0]
[ 0, 0, 1, 0]
[ 0, 0, 0, 1]
isAlways(P*(R\A)*Q == L*U)
ans =
42 logical array
1 1
1 1
1 1
1 1
Compute the LU factorization of this matrix using the 'vector' flag to return the
permutation information as vectors p and q. Also compute the scaling matrix R:
syms a
A = [0, a; 1/a, 0; 0, 1/5; 0,-1];
[L, U, p, q, R] = lu(A, 'vector')
L =
[ 1, 0, 0, 0]
[ 0, 1, 0, 0]
[ 0, 1/(5*a), 1, 0]
[ 0, -1/a, 0, 1]
U =
4-951
4 Functions Alphabetical List
[ 1/a, 0]
[ 0, a]
[ 0, 0]
[ 0, 0]
p =
2 1 3 4
q =
1 2
R =
[ 1, 0, 0, 0]
[ 0, 1, 0, 0]
[ 0, 0, 1, 0]
[ 0, 0, 0, 1]
isAlways(R(:,p)\A(:,q) == L*U)
ans =
42 logical array
1 1
1 1
1 1
1 1
syms a
A = [0 0 a; a 2 3; 0 a 2];
lu(A)
ans =
[ a, 2, 3]
[ 0, a, 2]
[ 0, 0, a]
Verify that the resulting matrix is equal to U + L - eye(size(A)), where L and U are
defined as [L,U,P] = lu(A):
[L,U,P] = lu(A);
U + L - eye(size(A))
ans =
[ a, 2, 3]
[ 0, a, 2]
4-952
lu
[ 0, 0, a]
More About
LU Factorization of a Matrix
Permutation Vector
1 if j = pi
Pij = d p , j =
0 if j pi
i
Tips
Calling lu for numeric arguments that are not symbolic objects invokes the MATLAB
lu function.
The thresh option supported by the MATLAB lu function does not affect symbolic
inputs.
If you use 'matrix' instead of 'vector', then lu returns permutation matrices, as
it does by default.
L and U are nonsingular if and only if A is nonsingular. lu also can compute the LU
factorization of a singular matrix A. In this case, L or U is a singular matrix.
Most algorithms for computing LU factorization are variants of Gaussian elimination.
See Also
chol | eig | isAlways | lu | qr | svd | vpa
Introduced in R2013a
4-953
4 Functions Alphabetical List
massMatrixForm
Extract mass matrix and right side of semilinear system of differential algebraic
equations
Syntax
[M,F] = massMatrixForm(eqs,vars)
Description
[M,F] = massMatrixForm(eqs,vars) returns the mass matrix M and the right side of
equations F of a semilinear system of first-order differential algebraic equations (DAEs).
Algebraic equations in eqs that do not contain any derivatives of the variables in vars
correspond to empty rows of the mass matrix M.
The mass matrix M and the right side of equations F refer to the form
M ( t, x ( t ) ) x& ( t ) = F ( t, x ( t) )
Examples
Create the following system of differential algebraic equations. Here, the functions
x1(t) and x2(t) represent state variables of the system. The system also contains
symbolic parameters r and m, and the function f(t, x1, x2). Specify the equations
and variables as two symbolic vectors: equations as a vector of symbolic equations, and
variables as a vector of symbolic function calls.
4-954
massMatrixForm
M =
[ m*x2(t), m*t]
[ 0, 0]
F =
f(t, x1(t), x2(t))
r^2 - x2(t)^2 - x1(t)^2
Solve this system using the numerical solver ode15s. Before you use ode15s, assign
the following values to symbolic parameters of the system: m = 100, r = 1, f(t, x1,
x2) = t + x1*x2. Also, replace the state variables x1(t), x2(t) by variables Y1, Y2
acceptable by matlabFunction.
syms Y1 Y2;
M = subs(M, [vars, m, r, f], [Y1, Y2, 100, 1, @(t,x1,x2) t + x1*x2]);
F = subs(F, [vars, m, r, f], [Y1, Y2, 100, 1, @(t,x1,x2) t + x1*x2]);
Create the following function handles MM and FF. You can use these function handles
as input arguments for odeset and ode15s. Note that these functions require state
variables to be specified as column vectors.
4-955
4 Functions Alphabetical List
Input Arguments
eqs System of semilinear first-order DAEs
vector of symbolic equations | vector of symbolic expressions
State variables, specified as a vector of symbolic functions or function calls, such as x(t).
4-956
massMatrixForm
Output Arguments
M Mass matrix
symbolic matrix
Mass matrix of the system, returned as a symbolic matrix. The number of rows is the
number of equations in eqs, and the number of columns is the number of variables in
vars.
See Also
daeFunction | decic | findDecoupledBlocks | incidenceMatrix |
isLowIndexDAE | matlabFunction | ode15s | odeFunction | odeset
| reduceDAEIndex | reduceDAEToODE | reduceDifferentialOrder |
reduceRedundancies
Introduced in R2014b
4-957
4 Functions Alphabetical List
matlabFunction
Convert symbolic expression to function handle or file
Syntax
g = matlabFunction(f)
g = matlabFunction(f1,...,fN)
g = matlabFunction( ___ ,Name,Value)
Description
g = matlabFunction(f) converts f to a MATLAB function with the handle g. Here, f
can be a symbolic expression, function, or a vector of symbolic expressions or functions.
Examples
syms x y
r = sqrt(x^2 + y^2);
ht = matlabFunction(sin(r)/r)
ht =
4-958
matlabFunction
ht =
function_handle with value:
@(x,y)deal(sin(sqrt(x.^2+y.^2)).*1.0./sqrt(x.^2+y.^2),...
cos(sqrt(x.^2+y.^2)).*1.0./sqrt(x.^2+y.^2))
ht =
function_handle with value:
@(x,y)x.^3+y.^3
Convert r to a MATLAB function and write this function to a file called myfile. If
myfile.m already exists in the current folder, matlabFunction replaces the existing
function with the converted symbolic expression. You can open and edit the resulting file.
f = matlabFunction(log(r)+r^(-1/2),'File','myfile');
4-959
4 Functions Alphabetical List
If a path to the file is an empty character vector, then matlabFunction does not create
a file. It generates an anonymous function instead.
syms x y z
r = x^2 + y^2 + z^2;
f = matlabFunction(log(r)+r^(-1/2),'File','')
f =
function_handle with value:
@(x,y,z)log(x.^2+y.^2+z.^2)+1.0./sqrt(x.^2+y.^2+z.^2)
syms x
r = x^2*(x^2 + 1);
Convert r to a MATLAB function and write the function to the file myfile. By default,
matlabFunction creates a file containing the optimized code.
f = matlabFunction(r,'File','myfile');
function r = myfile(x)
%MYFILE
% R = MYFILE(X)
t2 = x.^2;
r = t2.*(t2+1.0);
4-960
matlabFunction
f = matlabFunction(r,'File','myfile','Optimize',false);
function r = myfile(x)
%MYFILE
% R = MYFILE(X)
r = x.^2.*(x.^2+1.0);
syms x
A = diag(x*ones(1,3))
A =
[ x, 0, 0]
[ 0, x, 0]
[ 0, 0, x]
Convert A to a MATLAB function representing a numeric matrix, and write the result to
the file myfile1. By default, the generated MATLAB function creates the dense numeric
matrix specifying each element of the matrix, including all zero elements.
f1 = matlabFunction(A,'File','myfile1');
function A = myfile1(x)
%MYFILE1
% A = MYFILE1(X)
A = reshape([x,0.0,0.0,0.0,x,0.0,0.0,0.0,x],[3,3]);
Convert A to a MATLAB function setting Sparse to true. Now, the generated MATLAB
function creates the sparse numeric matrix specifying only nonzero elements and
assuming that all other elements are zeros.
f2 = matlabFunction(A,'File','myfile2','Sparse',true);
function A = myfile2(x)
%MYFILE2
4-961
4 Functions Alphabetical List
% A = MYFILE2(X)
A = sparse([1,2,3],[1,2,3],[x,x,x],3,3);
Convert r to a MATLAB function and write this function to the file myfile. By default,
matlabFunction uses alphabetical order of input arguments when converting symbolic
expressions.
matlabFunction(r,'File','myfile');
function r = myfile(x,y,z)
%MYFILE
% R = MYFILE(X,Y,Z)
r = x+y.*(1.0./2.0)+z.*(1.0./3.0);
Use the Vars argument to specify the order of input arguments for the generated
MATLAB function.
matlabFunction(r,'File','myfile','Vars',[y z x]);
function r = myfile(y,z,x)
%MYFILE
% R = MYFILE(Y,Z,X)
r = x+y.*(1.0./2.0)+z.*(1.0./3.0);
function r = myfile(t,in2)
%MYFILE
4-962
matlabFunction
% R = MYFILE(T,IN2)
x = in2(:,1);
y = in2(:,2);
z = in2(:,3);
r = exp(-t).*(x+y.*(1.0./2.0)+z.*(1.0./3.0));
Convert r and q to a MATLAB function and write the resulting function to a file myfile,
which returns a vector of two elements, name1 and name2.
f = matlabFunction(r,q,'File','myfile',...
'Outputs',{'name1','name2'});
4-963
4 Functions Alphabetical List
syms x y
f = evalin(symengine, 'arcsin(x) + arccos(y)');
matlabFunction(f,'File','myfile');
function f = myfile(x,y)
%MYFILE
% F = MYFILE(X,Y)
f = asin(x) + acos(y);
Input Arguments
f Symbolic input to be converted to MATLAB function
symbolic expression | symbolic function | symbolic vector | symbolic matrix
matlabFunction does not create a separate output argument for each element of a
symbolic vector or matrix. For example, g = matlabFunction([x + 1, y + 1])
creates a MATLAB function with one output argument, while g = matlabFunction(x
+ 1, y + 1) creates a MATLAB function with two output arguments.
4-964
matlabFunction
Example: matlabFunction(f,'File','myfile','Optimize',false)
Path to the file containing the generated MATLAB function, specified as a character
vector. The generated function accepts arguments of type double, and can be used
without Symbolic Math Toolbox. If File is empty, matlabFunction generates an
anonymous function. If File does not end in .m, the function appends .m.
matlabFunction without the File argument (or with a file path specified by an empty
character vector) creates a function handle. In this case, the code is not optimized. If you
try to enforce code optimization by setting Optimize to true, then matlabFunction
throws an error.
'Sparse' Flag that switches between sparse and dense matrix generation
false (default) | true
Flag that switches between sparse and dense matrix generation, specified as true or
false. When you specify 'Sparse',true, the generated MATLAB function represents
symbolic matrices by sparse numeric matrices. Use 'Sparse',true when you convert
4-965
4 Functions Alphabetical List
symbolic matrices containing many zero elements. Often, operations on sparse matrices
are more efficient than the same operations on dense matrices.
The number of specified input variables must equal or exceed the number of free
variables in f. Do not use the same names for the input variables specified by Vars and
the output variables specified by Outputs.
By default, when you convert symbolic expressions, the order is alphabetical. When you
convert symbolic functions, their input arguments appear in front of other variables, and
all other variables are sorted alphabetically.
If you do not specify the output variable names, then they coincide with the names you
use when calling matlabFunction. If you call matlabFunction using an expression
instead of individual variables, the default names of output variables consist of the word
out followed by a number, for example, out3.
Do not use the same names for the input variables specified by Vars and the output
variables specified by Outputs.
matlabFunction without the File argument (or with a file path specified by an empty
character vector) creates a function handle. In this case, matlabFunction ignores the
Outputs flag.
4-966
matlabFunction
Output Arguments
g Function handle that can serve as input argument to numerical functions
MATLAB function handle
Function handle that can serve as an input argument to numerical functions, returned as
a MATLAB function handle.
More About
Tips
When you use the File argument, use rehash to make the generated function
available immediately. rehash updates the MATLAB list of known files for
directories on the search path.
To convert a MuPAD expression or function to a MATLAB symbolic
expression, use f = evalin(symengine,'MuPAD_Expression') or f =
feval(symengine,'MuPAD_Function',x1,...,xn). Then you can convert the
resulting symbolic expression to a MATLAB function.
See Also
ccode | daeFunction | evalin | feval | fortran | matlabFunctionBlock |
odeFunction | rehash | simscapeEquation | subs | sym2poly
Introduced in R2008b
4-967
4 Functions Alphabetical List
matlabFunctionBlock
Convert symbolic expression to MATLAB Function block
Syntax
matlabFunctionBlock(block,f)
matlabFunctionBlock(block,f1,...,fN)
matlabFunctionBlock( ___ ,Name,Value)
Description
matlabFunctionBlock(block,f) converts f to a MATLAB Function block that you
can use in Simulink models. Here, f can be a symbolic expression, function, or a vector of
symbolic expressions or functions.
block specifies the name of the block that you create or modify.
Examples
4-968
matlabFunctionBlock
new_system('my_system')
open_system('my_system')
syms x y z
f = x^2 + y^2 + z^2;
matlabFunctionBlock('my_system/my_block',f)
function f = my_block(x,y,z)
%#codegen
f = x.^2 + y.^2 + z.^2;
If you use the name of an existing block, matlabFunctionBlock replaces the definition
of an existing block with the converted symbolic expression.
save_system('my_system')
close_system('my_system')
new_system('my_system')
open_system('my_system')
syms x y z
f(x, y, z) = x^2 + y^2 + z^2;
Convert f to a MATLAB Function block. Double-click the block to see the function.
matlabFunctionBlock('my_system/my_block',f)
4-969
4 Functions Alphabetical List
function f = my_block(x,y,z)
%#codegen
f = x.^2+y.^2+z.^2;
new_system('my_system')
open_system('my_system')
syms x y z
f = x^2;
g = y^2;
h = z^2;
matlabFunctionBlock('my_system/my_block',f,g,h)
new_system('my_system')
4-970
matlabFunctionBlock
open_system('my_system')
syms x y z
f = x^2 + y^2 + z^2;
Generate a block and set the function name to my_function. Double-click the block to
see the function.
matlabFunctionBlock('my_system/my_block',f,...
'FunctionName', 'my_function')
function f = my_function(x,y,z)
%#codegen
f = x.^2+y.^2+z.^2;
new_system('my_system')
open_system('my_system')
syms x
r = x^2*(x^2 + 1);
matlabFunctionBlock('my_system/my_block',r)
function r = my_block(x)
%#codegen
4-971
4 Functions Alphabetical List
t2 = x.^2;
r = t2.*(t2+1.0);
matlabFunctionBlock('my_system/my_block',r,...
'Optimize',false)
function r = my_block(x)
%#codegen
r = x.^2.*(x.^2+1.0);
new_system('my_system')
open_system('my_system')
syms x y z
f = x^2 + y^2 + z^2;
matlabFunctionBlock('my_system/my_block',f)
function f = my_block(x,y,z)
%#codegen
f = x.^2+y.^2+z.^2;
Use the Vars argument to specify the order of the input ports.
matlabFunctionBlock('my_system/my_block',f,...
'Vars', [y z x])
function f = my_block(y,z,x)
%#codegen
f = x.^2+y.^2+z.^2;
4-972
matlabFunctionBlock
new_system('my_system')
open_system('my_system')
syms x y z
f = x^2 + y^2 + z^2;
Convert the expression to a MATLAB Function block and specify the names of the output
variables and ports. Double-click the block to see the function defining the block.
new_system('my_system')
open_system('my_system')
4-973
4 Functions Alphabetical List
syms x y z
f = x^2 + y^2 + z^2;
new_system('my_system')
open_system('my_system')
syms x y
f = evalin(symengine, 'arcsin(x) + arccos(y)');
Convert the expression to a MATLAB Function block The resulting block contains the
same expressions written in the MATLAB language:
matlabFunctionBlock('my_system/my_block', f)
function f = my_block(x,y)
4-974
matlabFunctionBlock
%#codegen
f = asin(x) + acos(y);
Input Arguments
block Block to create of modify
character vector
4-975
4 Functions Alphabetical List
'Vars' Order of input variables and corresponding input ports of generated block
character vector | one-dimensional cell array of character vectors | one-dimensional cell
array of symbolic variables | one-dimensional cell array of vectors of symbolic variables |
vector of symbolic variables
Order of input variables and corresponding input ports of generated block, specified
as a character vector, a vector of symbolic variables, or a one-dimensional cell array of
character vectors, symbolic variables, or vectors of symbolic variables.
The number of specified input ports must equal or exceed the number of free variables in
f. Do not use the same names for the input ports specified by Vars and the output ports
specified by Outputs.
By default, when you convert symbolic expressions, the order is alphabetical. When you
convert symbolic functions, their input arguments appear in front of other variables, and
all other variables are sorted alphabetically.
Do not use the same names for the input ports specified by Vars and the output ports
specified by Outputs. See Specify Output Ports on page 4-973.
4-976
matlabFunctionBlock
More About
Tips
See Also
ccode | evalin | feval | fortran | matlabFunction | simscapeEquation | subs
| sym2poly
Introduced in R2009a
4-977
4 Functions Alphabetical List
max
Largest elements
Syntax
C = max(A)
C = max(A,[],dim)
[C,I] = max( ___ )
C = max(A,B)
Description
C = max(A) returns the largest element of A if A is a vector. If A is a matrix, this syntax
treats the columns of A as vectors, returning a row vector containing the largest element
from each column.
C = max(A,[],dim) returns the largest elements of matrix A along the dimension dim.
Thus, max(A,[],1) returns a row vector containing the largest elements of each column
of A, and max(A,[],2) returns a column vector containing the largest elements of each
row of A.
Here, the required argument [] serves as a divider. If you omit it, max(A,dim)
compares elements of A with the value dim.
[C,I] = max( ___ ) finds the indices of the largest elements, and returns them in
output vector I. If there are several identical largest values, this syntax returns the
index of the first largest element that it finds.
4-978
max
Examples
Maximum of Vector of Numbers
Find the largest of these numbers. Because these numbers are not symbolic objects, you
get a floating-point result.
max([-pi, pi/2, 1, 1/3])
ans =
1.5708
ans =
pi/2
A =
[ 0, 1, 2]
[ 3, 4, 5]
[ 1, 2, 3]
ans =
[ 3, 4, 5]
A =
4-979
4 Functions Alphabetical List
[ 0, 1, 2]
[ 3, 4, 5]
[ 1, 2, 3]
ans =
2
5
3
A =
[ 1/8, 1, 1/6]
[ 1/3, 1/5, 1/7]
[ 1/4, 1/9, 1/2]
Cc =
[ 1/3, 1, 1/2]
Ic =
2 1 3
Now, find the largest element in each row and its index.
[Cr,Ir] = max(A,[],2)
Cr =
1
1/3
1/2
Ir =
2
1
3
If dim exceeds the number of dimensions of A, then the syntax [C,I] = max(A,
[],dim) returns C = A and I = ones(size(A)).
[C,I] = max(A,[],3)
4-980
max
C =
[ 1/8, 1, 1/6]
[ 1/3, 1/5, 1/7]
[ 1/4, 1/9, 1/2]
I =
1 1 1
1 1 1
1 1 1
A =
[ 1, 1, 1]
[ 1, 2, 3]
[ 1, 3, 6]
B =
[ pi/3, pi/2, pi]
[ pi/2, pi/3, pi/2]
[ pi, pi/2, pi/3]
maxAB =
[ pi/3, pi/2, pi]
[ pi/2, 2, 3]
[ pi, 3, 6]
modulus =
4-981
4 Functions Alphabetical List
1.4142 1.1180
maximum =
1 - 1i
If the numbers have the same complex modulus, min chooses the number with the
largest phase angle.
modulus = abs([1 - 1/2*i, 1 + 1/2*i])
phaseAngle = angle([1 - 1/2*i, 1 + 1/2*i])
maximum = max(sym([1 - 1/2*i, 1/2 + i]))
modulus =
1.1180 1.1180
phaseAngle =
-0.4636 0.4636
maximum =
1/2 + 1i
Input Arguments
A Input
symbolic number | symbolic vector | symbolic matrix
Dimension to operate along, specified as a positive integer. The default value is 1. If dim
exceeds the number of dimensions of A, then max(A,[],dim) returns A, and [C,I] =
max(A,[],dim) returns C = A and I = ones(size(A)).
B Input
symbolic number | symbolic vector | symbolic matrix
4-982
max
If one argument is a vector or matrix, the other argument must either be a scalar or have
the same dimensions as the first one. If one argument is a scalar and the other argument
is a vector or matrix, then max expands the scalar into a vector or a matrix of the same
length with all elements equal to that scalar.
Output Arguments
C Largest elements
symbolic number | symbolic vector
More About
Tips
Calling max for numbers (or vectors or matrices of numbers) that are not symbolic
objects invokes the MATLAB max function.
For complex input A, max returns the complex number with the largest complex
modulus (magnitude), computed with max(abs(A)). If complex numbers have
the same modulus, max chooses the number with the largest phase angle,
max(angle(A)).
max ignores NaNs.
See Also
abs | angle | max | min | sort
Introduced in R2014a
4-983
4 Functions Alphabetical List
mfun
Numeric evaluation of special mathematical function
Compatibility
mfun will be removed in a future release. Instead, use the appropriate special
function syntax listed in mfunlist. For example, use bernoulli(n) instead of
mfun('bernoulli',n).
Syntax
mfun('function',par1,par2,par3,par4)
Description
mfun('function',par1,par2,par3,par4) numerically evaluates one of the special
mathematical functions listed in mfunlist. Each par argument is a numeric quantity
corresponding to a parameter for function. You can use up to four parameters. The last
parameter specified can be a matrix, usually corresponding to X. The dimensions of all
other parameters depend on the specifications for function. You can access parameter
information for mfun functions in mfunlist.
MuPAD software evaluates function using 16-digit accuracy. Each element of the
result is a MATLAB numeric quantity. Any singularity in function is returned as NaN.
See Also
mfunlist
4-984
mfunlist
mfunlist
List special functions for use with mfun
Compatibility
mfun will be removed in a future release. Instead, use the appropriate special
function syntax listed below. For example, use bernoulli(n) instead of
mfun('bernoulli',n).
Syntax
mfunlist
Description
mfunlist lists the special mathematical functions for use with the mfun function. The
following tables describe these special functions.
x, y real argument
z, z1, z2 complex argument
m, n integer argument
4-985
4 Functions Alphabetical List
BesselK(v,x) besselk(v,x)
Beta function G( x) G( y) Beta(x,y) beta(x,y)
B( x, y) =
G( x + y)
G( m + 1)
=
G ( n + 1) G( m - n + 1)
4-986
mfunlist
and its p z
erfc(n,z) erfc(n,z)
iterated
integrals
2 2
erfc( -1, z) = e- z
p
erfc( n, z) = erfc(n - 1, t)dt
z
4-987
4 Functions Alphabetical List
x et
Ei( x) = PV -
t
-
Fresnel sine x FresnelC(x) fresnelc(x)
and cosine p
integrals
C( x) = cos t2 dt
2 FresnelS(x) fresnels(x)
0
x
p
S( x) = sin t2 dt
2
0
4-988
mfunlist
parameter m = k 2 = sin2 a .
Incomplete GAMMA(z1,z2) igamma(z1,z2)
gamma e-t t a-1dt
function
G( a, z) = z1 = a z1 = a
z
z2 = z z2 = z
Logarithm of lnGAMMA( z) = ln(G( z)) lnGAMMA(z) gammaln(z)
the gamma
function
Logarithmic x dt Li(x) logint(x) x>1
integral Li( x) = PV = Ei(ln x)
0 ln t
4-989
4 Functions Alphabetical List
The following orthogonal polynomials are available using mfun. In all cases, n is a
nonnegative integer and x is real.
Orthogonal Polynomials
Limitations
In general, the accuracy of a function will be lower near its roots and when its arguments
are relatively large.
4-990
mfunlist
Running time depends on the specific function and its parameters. In general,
calculations are slower than standard MATLAB calculations.
References
[1] Abramowitz, M. and I.A., Stegun, Handbook of Mathematical Functions With
Formulas, Graphs, and Mathematical Tables. New York: Dover, 1972.
See Also
mfun
4-991
4 Functions Alphabetical List
min
Smallest elements
Syntax
C = min(A)
C = min(A,[],dim)
[C,I] = min( ___ )
C = min(A,B)
Description
C = min(A) returns the smallest element of A if A is a vector. If A is a matrix, this
syntax treats the columns of A as vectors, returning a row vector containing the smallest
element from each column.
Here, the required argument [] serves as a divider. If you omit it, min(A,dim)
compares elements of A with the value dim.
[C,I] = min( ___ ) finds the indices of the smallest elements, and returns them in
output vector I. If there are several identical smallest values, this syntax returns the
index of the first smallest element that it finds.
4-992
min
Examples
Minimum of Vector of Numbers
Find the smallest of these numbers. Because these numbers are not symbolic objects, you
get a floating-point result.
min([-pi, pi/2, 1, 1/3])
ans =
-3.1416
ans =
-pi
A =
[ 0, 1, 2]
[ 3, 4, 5]
[ 1, 2, 3]
ans =
[ 0, 1, 2]
A =
4-993
4 Functions Alphabetical List
[ 0, 1, 2]
[ 3, 4, 5]
[ 1, 2, 3]
ans =
0
3
1
A =
[ 1/8, 1, 1/6]
[ 1/3, 1/5, 1/7]
[ 1/4, 1/9, 1/2]
Cc =
[ 1/8, 1/9, 1/7]
Ic =
1 3 2
Now, find the smallest element in each row and its index.
[Cr,Ir] = min(A,[],2)
Cr=
1/8
1/7
1/9
Ir =
1
3
2
If dim exceeds the number of dimensions of A, then the syntax [C,I] = min(A,
[],dim) returns C = A and I = ones(size(A)).
[C,I] = min(A,[],3)
4-994
min
C =
[ 1/8, 1, 1/6]
[ 1/3, 1/5, 1/7]
[ 1/4, 1/9, 1/2]
I =
1 1 1
1 1 1
1 1 1
A =
[ 1, 1, 1]
[ 1, 2, 3]
[ 1, 3, 6]
B =
[ pi/3, pi/2, pi]
[ pi/2, pi/3, pi/2]
[ pi, pi/2, pi/3]
minAB =
[ 1, 1, 1]
[ 1, pi/3, pi/2]
[ 1, pi/2, pi/3]
modulus =
4-995
4 Functions Alphabetical List
1.4142 1.1180
minimum =
1/2 + 1i
If the numbers have the same complex modulus, min chooses the number with the
smallest phase angle.
modulus = abs([1 - 1/2*i, 1 + 1/2*i])
phaseAngle = angle([1 - 1/2*i, 1 + 1/2*i])
minimum = min(sym([1 - 1/2*i, 1/2 + i]))
modulus =
1.1180 1.1180
phaseAngle =
-0.4636 0.4636
minimum =
1 - 1i/2
Input Arguments
A Input
symbolic number | symbolic vector | symbolic matrix
Dimension to operate along, specified as a positive integer. The default value is 1. If dim
exceeds the number of dimensions of A, then min(A,[],dim) returns A, and [C,I] =
min(A,[],dim) returns C = A and I = ones(size(A)).
B Input
symbolic number | symbolic vector | symbolic matrix
4-996
min
If one argument is a vector or matrix, the other argument must either be a scalar or have
the same dimensions as the first one. If one argument is a scalar and the other argument
is a vector or matrix, then min expands the scalar into a vector or a matrix of the same
length with all elements equal to that scalar.
Output Arguments
C Smallest elements
symbolic number | symbolic vector
More About
Tips
Calling min for numbers (or vectors or matrices of numbers) that are not symbolic
objects invokes the MATLAB min function.
For complex input A, min returns the complex number with the smallest complex
modulus (magnitude), computed with min(abs(A)). If complex numbers have
the same modulus, min chooses the number with the smallest phase angle,
min(angle(A)).
min ignores NaNs.
See Also
abs | angle | max | min | sort
Introduced in R2014a
4-997
4 Functions Alphabetical List
minpoly
Minimal polynomial of matrix
Syntax
minpoly(A)
minpoly(A,var)
Description
minpoly(A) returns a vector of the coefficients of the minimal polynomial of A. If A is a
symbolic matrix, minpoly returns a symbolic vector. Otherwise, it returns a vector with
elements of type double.
Input Arguments
A
Matrix.
var
Default: If you do not specify var, minpoly returns a vector of coefficients of the
minimal polynomial instead of returning the polynomial itself.
Examples
Compute the minimal polynomial of the matrix A in terms of the variable x:
syms x
4-998
minpoly
A = sym([1 1 0; 0 1 0; 0 0 1]);
minpoly(A, x)
ans =
x^2 - 2*x + 1
To find the coefficients of the minimal polynomial of A, call minpoly with one argument:
A = sym([1 1 0; 0 1 0; 0 0 1]);
minpoly(A)
ans =
[ 1, -2, 1]
Find the coefficients of the minimal polynomial of the symbolic matrix A. For this matrix,
minpoly returns the symbolic vector of coefficients:
A = sym([0 2 0; 0 0 2; 2 0 0]);
P = minpoly(A)
P =
[ 1, 0, 0, -8]
Now find the coefficients of the minimal polynomial of the matrix B, all elements of
which are double-precision values. Note that in this case minpoly returns coefficients as
double-precision values:
B = [0 2 0; 0 0 2; 2 0 0];
P = minpoly(B)
P =
1 0 0 -8
More About
Minimal Polynomial of a Matrix
The minimal polynomial of a square matrix A is the monic polynomial p(x) of the least
degree, such that p(A)=0.
See Also
charpoly | eig | jordan | poly2sym | sym2poly
4-999
4 Functions Alphabetical List
Introduced in R2012b
4-1000
minus, -
minus, -
Symbolic subtraction
Syntax
-A
A - B
minus(A,B)
Description
-A returns the negation of A.
Examples
Subtract Scalar from Array
Subtract 2 from array A.
syms x
A = [x 1;-2 sin(x)];
A - 2
ans =
[ x - 2, -1]
[ -4, sin(x) - 2]
4-1001
4 Functions Alphabetical List
M - eye(2)
ans =
[ -1, x]
[ y, z - 1]
ans =
0.5833
ans =
7/12
minus(sym(11/6),sym(5/4))
ans =
7/12
Subtract Matrices
Subtract matrices B and C from A.
A = sym([3 4; 2 1]);
B = sym([8 1; 5 2]);
C = sym([6 3; 4 9]);
Y = A - B - C
Y =
[ -11, 0]
[ -7, -10]
4-1002
minus, -
-Y
ans =
[ 11, 0]
[ 7, 10]
Subtract Functions
Subtract function g from function f.
syms f(x) g(x)
f = sin(x) + 2*x;
y = f - g
y(x) =
2*x - g(x) + sin(x)
Input Arguments
A Input
symbolic variable | symbolic vector | symbolic matrix | symbolic multidimensional array
| symbolic function | symbolic expression
B Input
symbolic variable | symbolic vector | symbolic matrix | symbolic multidimensional array
| symbolic function | symbolic expression
More About
Tips
All nonscalar arguments must have the same size. If one input argument is nonscalar,
then minus expands the scalar into an array of the same size as the nonscalar
argument, with all elements equal to the corresponding scalar.
4-1003
4 Functions Alphabetical List
See Also
ctranspose | ldivide | mldivide | mpower | mrdivide | mtimes | plus | power
| rdivide | times | transpose
4-1004
mldivide, \
mldivide, \
Symbolic matrix left division
Syntax
X = A\B
X = mldivide(A,B)
Description
X = A\B solves the symbolic system of linear equations in matrix form, A*X = B for X.
If the solution does not exist or if it is not unique, the \ operator issues a warning.
A can be a rectangular matrix, but the equations must be consistent. The symbolic
operator \ does not compute least-squares solutions.
Examples
System of Equations in Matrix Form
Solve a system of linear equations specified by a square matrix of coefficients and a
vector of right sides of equations.
Create a matrix containing the coefficient of equation terms, and a vector containing the
right sides of equations.
A = sym(pascal(4))
b = sym([4; 3; 2; 1])
A =
[ 1, 1, 1, 1]
[ 1, 2, 3, 4]
[ 1, 3, 6, 10]
[ 1, 4, 10, 20]
4-1005
4 Functions Alphabetical List
b =
4
3
2
1
X =
5
-1
0
0
Rank-Deficient System
Create a matrix containing the coefficients of equation terms, and a vector containing the
right sides of equations.
A = sym(magic(4))
b = sym([0; 1; 1; 0])
A =
[ 16, 2, 3, 13]
[ 5, 11, 10, 8]
[ 9, 7, 6, 12]
[ 4, 14, 15, 1]
b =
0
1
1
0
Find the rank of the system. This system contains four equations, but its rank is 3.
Therefore, the system is rank-deficient. This means that one variable of the system is not
independent and can be expressed in terms of other variables.
rank(horzcat(A,b))
ans =
3
4-1006
mldivide, \
Try to solve this system using the symbolic \ operator. Because the system is rank-
deficient, the returned solution is not unique.
A\b
ans =
1/34
19/34
-9/17
0
Inconsistent System
Create a matrix containing the coefficient of equation terms, and a vector containing the
right sides of equations.
A = sym(magic(4))
b = sym([0; 1; 2; 3])
A =
[ 16, 2, 3, 13]
[ 5, 11, 10, 8]
[ 9, 7, 6, 12]
[ 4, 14, 15, 1]
b =
0
1
2
3
Try to solve this system using the symbolic \ operator. The operator issues a warning
and returns a vector with all elements set to Inf because the system of equations is
inconsistent, and therefore, no solution exists. The number of elements in the resulting
vector equals the number of equations (rows in the coefficient matrix).
A\b
ans =
Inf
4-1007
4 Functions Alphabetical List
Inf
Inf
Inf
Find the reduced row echelon form of this system. The last row shows that one of the
equations reduced to 0 = 1, which means that the system of equations is inconsistent.
rref(horzcat(A,b))
ans =
[ 1, 0, 0, 1, 0]
[ 0, 1, 0, 3, 0]
[ 0, 0, 1, -3, 0]
[ 0, 0, 0, 0, 1]
Input Arguments
A Coefficient matrix
symbolic number | symbolic variable | symbolic function | symbolic expression |
symbolic vector | symbolic matrix
B Right side
symbolic number | symbolic variable | symbolic function | symbolic expression |
symbolic vector | symbolic matrix
Output Arguments
X Solution
symbolic number | symbolic variable | symbolic function | symbolic expression |
symbolic vector | symbolic matrix
4-1008
mldivide, \
More About
Tips
When dividing by zero, mldivide considers the numerators sign and returns Inf or
-Inf accordingly.
syms x
[sym(0)\sym(1), sym(0)\sym(-1), sym(0)\x]
ans =
[ Inf, -Inf, Inf*x]
See Also
ctranspose | ldivide | minus | mpower | mrdivide | mtimes | plus | power |
rdivide | times | transpose
4-1009
4 Functions Alphabetical List
mod
Symbolic modulus after division
Syntax
mod(a,b)
Description
mod(a,b) finds the modulus after division. To find the remainder, use rem.
If a is a polynomial expression, then mod(a,b) finds the modulus for each coefficient.
Examples
Divide Integers by Integers
Find the modulus after division in case both the dividend and divisor are integers.
ans =
[ 3, -1, 1, -3]
ans =
4-1010
mod
syms x
mod(x^3 - 2*x + 999, 10)
ans =
x^3 + 8*x + 9
ans =
x^3 + 2*x^2 + 3*x + 4
Find the modulus after division for the elements of these two matrices.
ans =
[ 1, 1]
[ 1, 0]
Find the modulus after division for the elements of matrix A and the value 9. Here, mod
expands 9 into the 2-by-2 matrix with all elements equal to 9.
mod(A,9)
ans =
[ 0, 1]
4-1011
4 Functions Alphabetical List
[ 2, 3]
Input Arguments
a Dividend (numerator)
number | symbolic number | symbolic variable | polynomial expression | vector |
matrix
b Divisor (denominator)
number | symbolic number | vector | matrix
More About
Modulus
a
mod ( a, b ) = a - b * floor ,
b
where floor rounds (a/b) towards negative infinity. For example, the modulus of -8 and
-3 is -2, but the modulus of -8 and 3 is 1.
Tips
Calling mod for numbers that are not symbolic objects invokes the MATLAB mod
function.
All nonscalar arguments must be the same size. If one input arguments is nonscalar,
then mod expands the scalar into a vector or matrix of the same size as the nonscalar
argument, with all elements equal to the corresponding scalar.
4-1012
mod
See Also
quorem | rem
4-1013
4 Functions Alphabetical List
mpower, ^
Symbolic matrix power
Syntax
A^B
mpower(A,B)
Description
A^B computes A to the B power.
Examples
Matrix Base and Scalar Exponent
Create a 2-by-2 matrix.
A = sym('a%d%d', [2 2])
A =
[ a11, a12]
[ a21, a22]
Find A^2.
A^2
ans =
[ a11^2 + a12*a21, a11*a12 + a12*a22]
[ a11*a21 + a21*a22, a22^2 + a12*a21]
4-1014
mpower, ^
A = sym(magic(2))
A =
[ 1, 3]
[ 4, 2]
Find A.
sym(pi)^A
ans =
[ (3*pi^7 + 4)/(7*pi^2), (3*(pi^7 - 1))/(7*pi^2)]
[ (4*(pi^7 - 1))/(7*pi^2), (4*pi^7 + 3)/(7*pi^2)]
Input Arguments
A Base
number | symbolic number | symbolic variable | symbolic function | symbolic
expression | square symbolic matrix
B Exponent
number | symbolic number | symbolic variable | symbolic function | symbolic
expression | symbolic square matrix
See Also
ctranspose | ldivide | minus | mldivide | mrdivide | mtimes | plus | power |
rdivide | times | transpose
4-1015
4 Functions Alphabetical List
4-1016
mrdivide, /
mrdivide, /
Symbolic matrix right division
Syntax
X = B/A
X = mrdivide(B,A)
Description
X = B/A solves the symbolic system of linear equations in matrix form, X*A = B for X.
The matrices A and B must contain the same number of columns. The right division of
matrices B/A is equivalent to (A'\B')'.
If the solution does not exist or if it is not unique, the / operator issues a warning.
A can be a rectangular matrix, but the equations must be consistent. The symbolic
operator / does not compute least-squares solutions.
Examples
Create a matrix containing the coefficient of equation terms, and a vector containing the
right sides of equations.
A = sym(pascal(4))
b = sym([4 3 2 1])
A =
4-1017
4 Functions Alphabetical List
[ 1, 1, 1, 1]
[ 1, 2, 3, 4]
[ 1, 3, 6, 10]
[ 1, 4, 10, 20]
b =
[ 4, 3, 2, 1]
X = b/A
X =
[ 5, -1, 0, 0]
Rank-Deficient System
Create a matrix containing the coefficient of equation terms, and a vector containing the
right sides of equations.
A = sym(magic(4))'
b = sym([0 1 1 0])
A =
[ 16, 5, 9, 4]
[ 2, 11, 7, 14]
[ 3, 10, 6, 15]
[ 13, 8, 12, 1]
b =
[ 0, 1, 1, 0]
Find the rank of the system. This system contains four equations, but its rank is 3.
Therefore, the system is rank-deficient. This means that one variable of the system is not
independent and can be expressed in terms of other variables.
rank(vertcat(A,b))
ans =
3
Try to solve this system using the symbolic / operator. Because the system is rank-
deficient, the returned solution is not unique.
4-1018
mrdivide, /
b/A
ans =
[ 1/34, 19/34, -9/17, 0]
Inconsistent System
Create a matrix containing the coefficient of equation terms, and a vector containing the
right sides of equations.
A = sym(magic(4))'
b = sym([0 1 2 3])
A =
[ 16, 5, 9, 4]
[ 2, 11, 7, 14]
[ 3, 10, 6, 15]
[ 13, 8, 12, 1]
b =
[ 0, 1, 2, 3]
Try to solve this system using the symbolic / operator. The operator issues a warning
and returns a vector with all elements set to Inf because the system of equations is
inconsistent, and therefore, no solution exists. The number of elements equals the
number of equations (rows in the coefficient matrix).
b/A
ans =
[ Inf, Inf, Inf, Inf]
Find the reduced row echelon form of this system. The last row shows that one of the
equations reduced to 0 = 1, which means that the system of equations is inconsistent.
rref(vertcat(A,b)')
ans =
[ 1, 0, 0, 1, 0]
[ 0, 1, 0, 3, 0]
[ 0, 0, 1, -3, 0]
4-1019
4 Functions Alphabetical List
[ 0, 0, 0, 0, 1]
Input Arguments
A Coefficient matrix
symbolic number | symbolic variable | symbolic function | symbolic expression |
symbolic vector | symbolic matrix
B Right side
symbolic number | symbolic variable | symbolic function | symbolic expression |
symbolic vector | symbolic matrix
Output Arguments
X Solution
symbolic number | symbolic variable | symbolic function | symbolic expression |
symbolic vector | symbolic matrix
More About
Tips
When dividing by zero, mrdivide considers the numerators sign and returns Inf or
-Inf accordingly.
syms x
[sym(1)/sym(0), sym(-1)/sym(0), x/sym(0)]
ans =
4-1020
mrdivide, /
See Also
ctranspose | ldivide | minus | mldivide | mpower | mtimes | plus | power |
rdivide | times | transpose
4-1021
4 Functions Alphabetical List
mtimes, *
Symbolic matrix multiplication
Syntax
A*B
mtimes(A,B)
Description
A*B is the matrix product of A and B. If A is an m-by-p and B is a p-by-n matrix, then the
result is an m-by-n matrix C defined as
p
C ( i, j ) = A (i, k) B ( k, j )
k= 1
For nonscalar A and B, the number of columns of A must equal the number of rows of
B. Matrix multiplication is not universally commutative for nonscalar inputs. That is,
typically A*B is not equal to B*A. If at least one input is scalar, then A*B is equivalent to
A.*B and is commutative.
Examples
Multiply Two Vectors
Create a 1-by-5 row vector and a 5-by-1 column vector.
syms x
A = [x, 2*x^2, 3*x^3, 4*x^4]
B = [1/x; 2/x^2; 3/x^3; 4/x^4]
A =
[ x, 2*x^2, 3*x^3, 4*x^4]
4-1022
mtimes, *
B =
1/x
2/x^2
3/x^3
4/x^4
ans =
30
A =
[ a11, a12, a13]
[ a21, a22, a23]
[ a31, a32, a33]
[ a41, a42, a43]
B =
[ b11, b12]
[ b21, b22]
[ b31, b32]
Multiply A by B.
A*B
ans =
[ a11*b11 + a12*b21 + a13*b31, a11*b12 + a12*b22 + a13*b32]
[ a21*b11 + a22*b21 + a23*b31, a21*b12 + a22*b22 + a23*b32]
[ a31*b11 + a32*b21 + a33*b31, a31*b12 + a32*b22 + a33*b32]
[ a41*b11 + a42*b21 + a43*b31, a41*b12 + a42*b22 + a43*b32]
4-1023
4 Functions Alphabetical List
H = sym(hilb(4))
H =
[ 1, 1/2, 1/3, 1/4]
[ 1/2, 1/3, 1/4, 1/5]
[ 1/3, 1/4, 1/5, 1/6]
[ 1/4, 1/5, 1/6, 1/7]
Multiply H by e .
C = H*exp(sym(pi))
C =
[ exp(pi), exp(pi)/2, exp(pi)/3, exp(pi)/4]
[ exp(pi)/2, exp(pi)/3, exp(pi)/4, exp(pi)/5]
[ exp(pi)/3, exp(pi)/4, exp(pi)/5, exp(pi)/6]
[ exp(pi)/4, exp(pi)/5, exp(pi)/6, exp(pi)/7]
Use vpa and digits to approximate symbolic results with the required number of digits.
For example, approximate it with five-digit accuracy.
old = digits(5);
vpa(C)
digits(old)
ans =
[ 23.141, 11.57, 7.7136, 5.7852]
[ 11.57, 7.7136, 5.7852, 4.6281]
[ 7.7136, 5.7852, 4.6281, 3.8568]
[ 5.7852, 4.6281, 3.8568, 3.3058]
Input Arguments
A Input
symbolic number | symbolic variable | symbolic function | symbolic expression |
symbolic vector | symbolic matrix
B Input
symbolic number | symbolic variable | symbolic function | symbolic expression |
symbolic vector | symbolic matrix
4-1024
mtimes, *
See Also
ctranspose | ldivide | minus | mldivide | mpower | mrdivide | plus | power |
rdivide | times | transpose
4-1025
4 Functions Alphabetical List
mupad
Start MuPAD notebook
Syntax
mphandle = mupad
mphandle = mupad(file)
Description
mphandle = mupad creates a MuPAD notebook, and keeps a handle (pointer) to the
notebook in the variable mphandle. You can use any variable name you like instead of
mphandle.
mphandle = mupad(file) opens the MuPAD notebook named file and keeps
a handle (pointer) to the notebook in the variable mphandle. The file name must
be a full path unless the file is in the current folder. You also can use the argument
file#linktargetname to refer to the particular link target inside a notebook. In this
case, the mupad function opens the MuPAD notebook (file) and jumps to the beginning
of the link target linktargetname. If there are multiple link targets with the name
linktargetname, the mupad function uses the last linktargetname occurrence.
Examples
To start a new notebook and define a handle mphandle to the notebook, enter:
reset(symengine);
if ~feature('ShowFigureWindows')
disp('no display available, skipping test ....');
else mphandle = mupad; end
mphandle = mupad;
To open an existing notebook named notebook1.mn located in the current folder, and
define a handle mphandle to the notebook, enter:
mphandle = mupad('notebook1.mn');
4-1026
mupad
To open a notebook and jump to a particular location, create a link target at that location
inside a notebook and refer to it when opening a notebook. For example, if you have the
Conclusions section in notebook1.mn, create a link target named conclusions and
refer to it when opening the notebook. The mupad function opens notebook1.mn and
scroll it to display the Conclusions section:
mphandle = mupad('notebook1.mn#conclusions');
For information about creating link targets, see Work with Links.
More About
Create MuPAD Notebooks on page 3-3
Open MuPAD Notebooks on page 3-6
See Also
getVar | mupadwelcome | openmn | openmu | setVar
Introduced in R2008b
4-1027
4 Functions Alphabetical List
mupadNotebookTitle
Window title of MuPAD notebook
Syntax
T = mupadNotebookTitle(nb)
Description
T = mupadNotebookTitle(nb) returns a cell array containing the window title of
the MuPAD notebook with the handle nb. If nb is a vector of handles to notebooks, then
mupadNotebookTitle(nb) returns a cell array of the same size as nb.
Examples
Find Titles of Particular 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-1028
mupadNotebookTitle
mupadNotebookTitle([nb1; nb2])
ans =
'myFile1'
'myFile2'
Get a cell array containing titles of all currently open MuPAD 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
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
List the titles of all open notebooks. The result is a cell array of character vectors.
mupadNotebookTitle(allNBs)
ans =
'myFile1'
'myFile2'
4-1029
4 Functions Alphabetical List
'Notebook1
mupadNotebookTitle returns a cell array of titles even if there is only one element in
that cell array. If mupadNotebookTitle returns a cell array of one element, you can
quickly convert it to a character vector by using char.
nb = mupad;
Input Arguments
nb Pointer to MuPAD notebook
handle to notebook | vector of handles to notebooks
You can get the list of all open notebooks using the allMuPADNotebooks function.
mupadNotebookTitle accepts a vector of handles returned by allMuPADNotebooks.
4-1030
mupadNotebookTitle
Output Arguments
T Window title of MuPAD notebook
cell array
See Also
allMuPADNotebooks | close | evaluateMuPADNotebook | getVar | mupad |
openmn | setVar
Introduced in R2013b
4-1031
4 Functions Alphabetical List
mupadwelcome
Start MuPAD interfaces
Syntax
mupadwelcome
Description
mupadwelcome opens a window that enables you to start various interfaces:
It also enables you to access recent MuPAD files or browse for files.
4-1032
mupadwelcome
More About
Create MuPAD Notebooks on page 3-3
Open MuPAD Notebooks on page 3-6
See Also
mupad
Introduced in R2008b
4-1033
4 Functions Alphabetical List
nchoosek
Binomial coefficient
Syntax
b = nchoosek(n,k)
C = nchoosek(v,k)
Description
b = nchoosek(n,k) returns the binomial coefficient of n and k, defined as n!/(k!(n
- k)!). This is the number of combinations of n items taken k at a time.
Examples
ans =
[ 1, 0, n]
If one or both parameters are negative numbers, convert these numbers to symbolic
objects.
[nchoosek(sym(-1), 3), nchoosek(sym(-7), 2), nchoosek(sym(-5), -5)]
ans =
[ -1, 28, 1]
4-1034
nchoosek
If one or both parameters are complex numbers, convert these numbers to symbolic
objects.
[nchoosek(sym(i), 3), nchoosek(sym(i), i), nchoosek(sym(i), i + 1)]
ans =
[ 1/2 + 1i/6, 1, 0]
ans =
-(psi(n - 1) - psi(n + 1))*nchoosek(n, 2)
ans =
-(n*gamma(n))/(k^2*gamma(k)*gamma(n - k) - k*n*gamma(k)*gamma(n - k))
Pascal Triangle
Use nchoosek to build the Pascal triangle.
m = 5;
for n = 0:m
C = sym([]);
for k = 0:n
C = horzcat(C, nchoosek(n, k));
end
disp(C)
end
1
[ 1, 1]
[ 1, 2, 1]
[ 1, 3, 3, 1]
4-1035
4 Functions Alphabetical List
[ 1, 4, 6, 4, 1]
[ 1, 5, 10, 10, 5, 1]
Create a 1-by-5 symbolic vector with the elements x1, x2, x3, x4, and x5.
v = sym('x', [1, 5])
v =
[ x1, x2, x3, x4, x5]
C =
[ x1, x2, x3]
[ x1, x2, x4]
[ x1, x3, x4]
[ x2, x3, x4]
[ x1, x2, x5]
[ x1, x3, x5]
[ x2, x3, x5]
[ x1, x4, x5]
[ x2, x4, x5]
[ x3, x4, x5]
C = nchoosek(v, 4)
C =
[ x1, x2, x3, x4]
[ x1, x2, x3, x5]
[ x1, x2, x4, x5]
[ x1, x3, x4, x5]
[ x2, x3, x4, x5]
Input Arguments
n Number of possible choices
symbolic number | symbolic variable | symbolic expression | symbolic function
4-1036
nchoosek
Output Arguments
b Binomial coefficient
nonnegative scalar value
C All combinations of v
matrix
More About
Binomial Coefficient
If n and k are integers and 0kn, the binomial coefficient is defined as:
n n!
= (
k k! n - k)!
For complex numbers, the binomial coefficient is defined via the gamma function:
4-1037
4 Functions Alphabetical List
n G ( n + 1)
= (
k G k + 1) G ( n - k + 1)
Tips
Calling nchoosek for numbers that are not symbolic objects invokes the MATLAB
nchoosek function.
If one or both parameters are complex or negative numbers, convert these numbers to
symbolic objects using sym, and then call nchoosek for those symbolic objects.
Algorithms
If one or both arguments are complex, nchoosek uses the formula representing the
binomial coefficient via the gamma function.
See Also
beta | factorial | gamma | psi
Introduced in R2012a
4-1038
ne
ne
Define inequality
Compatibility
In previous releases, ne in some cases evaluated inequalities involving only symbolic
numbers and returned logical 1 or 0. To obtain the same results as in previous releases,
wrap inequalities in isAlways. For example, use isAlways(A ~= B).
Syntax
A ~= B
ne(A,B)
Description
A ~= B creates a symbolic inequality.
ne(A,B) is equivalent to A ~= B.
Input Arguments
A
4-1039
4 Functions Alphabetical List
Examples
Use assume and the relational operator ~= to set the assumption that x does not equal to
5:
syms x
assume(x ~= 5)
Solve this equation. The solver takes into account the assumption on variable x, and
therefore returns only one solution.
solve((x - 5)*(x - 6) == 0, x)
ans =
6
Alternatives
You can also define inequality using eq (or its shortcut ==) and the logical negation not
(or ~). Thus, A ~= B is equivalent to ~(A == B).
More About
Tips
See Also
eq | ge | gt | isAlways | le | lt
4-1040
ne
Introduced in R2012a
4-1041
4 Functions Alphabetical List
nextprime
Next prime number
Syntax
nextprime(n)
Description
nextprime(n) returns the next prime number greater than or equal to n. If n is a vector
or matrix, then nextprime acts element-wise on n.
Examples
Find Next Prime Number
Find the next prime number greater than 100. Because nextprime only accepts
symbolic input, wrap 100 with sym.
nextprime(sym(100))
ans =
101
Find the next prime numbers greater than 1000, 10000, and 100000 by specifying the
input as a vector.
nextprime(sym([1000 10000 100000]))
ans =
[ 1009, 10007, 100003]
4-1042
nextprime
large prime is to use powers of 10, which are accurately represented without requiring
quotation marks. For more information, see Numeric to Symbolic Conversion on page
2-93.
nextprime(10^sym(18))
ans =
1000000000000000003
nextprime(sym('823572345728582545'))
ans =
823572345728582623
Input Arguments
n Input
symbolic number | symbolic vector | symbolic matrix
See Also
isprime | prevprime | primes
Introduced in R2016b
4-1043
4 Functions Alphabetical List
nnz
Number of nonzero elements
Syntax
nnz(X)
Description
nnz(X) computes the number of nonzero elements in X.
Examples
Number of Nonzero Elements and Matrix Density
Compute the number of nonzero elements of a 10-by-10 symbolic matrix and its density.
A =
[ 0, 1/2, 1/3, 0, 1/5, 1/6, 1/7, 0, 0, 1/10]
[ 1/2, 1/3, 1/4, 0, 0, 0, 0, 1/9, 0, 1/11]
[ 0, 1/4, 0, 0, 1/7, 1/8, 1/9, 1/10, 0, 0]
[ 0, 1/5, 0, 0, 1/8, 0, 1/10, 1/11, 0, 1/13]
[ 1/5, 0, 0, 1/8, 1/9, 0, 1/11, 1/12, 0, 0]
[ 1/6, 0, 1/8, 0, 0, 0, 0, 0, 1/14, 1/15]
[ 0, 1/8, 0, 0, 1/11, 0, 0, 0, 0, 1/16]
[ 1/8, 0, 1/10, 1/11, 0, 0, 0, 1/15, 1/16, 0]
[ 0, 0, 1/11, 0, 1/13, 0, 1/15, 1/16, 1/17, 0]
[ 1/10, 1/11, 0, 0, 1/14, 0, 1/16, 0, 1/18, 0]
4-1044
nnz
Number =
48
Density =
0.4800
Input Arguments
X Input array
symbolic vector | symbolic matrix | symbolic multidimensional array
See Also
nonzeros | rank | reshape | size
Introduced in R2014b
4-1045
4 Functions Alphabetical List
nonzeros
Nonzero elements
Syntax
nonzeros(X)
Description
nonzeros(X) returns a column vector containing all nonzero elements of X.
Examples
List All Nonzero Elements of Symbolic Matrix
Find all nonzero elements of a 10-by-10 symbolic matrix.
T =
[ 0, 2, 3, 4, 0]
[ 2, 0, 2, 3, 4]
[ 3, 2, 0, 2, 3]
[ 4, 3, 2, 0, 2]
[ 0, 4, 3, 2, 0]
Use the triu function to return a triangular matrix that retains only the upper part of T.
T1 = triu(T)
T1 =
[ 0, 2, 3, 4, 0]
[ 0, 0, 2, 3, 4]
[ 0, 0, 0, 2, 3]
[ 0, 0, 0, 0, 2]
4-1046
nonzeros
[ 0, 0, 0, 0, 0]
List all nonzero elements of this matrix. nonzeros searches for nonzero elements of a
matrix in the first column, then in the second one, and so on. It returns the column vector
containing all nonzero elements. It retains duplicate elements.
nonzeros(T1)
ans =
2
3
2
4
3
2
4
3
2
Input Arguments
X Input array
symbolic vector | symbolic matrix | symbolic multidimensional array
See Also
nnz | rank | reshape | size
Introduced in R2014b
4-1047
4 Functions Alphabetical List
norm
Norm of matrix or vector
Syntax
norm(A)
norm(A,p)
norm(V)
norm(V,P)
Description
norm(A) returns the 2-norm of matrix A.
Input Arguments
A
Symbolic matrix.
4-1048
norm
Default: 2
Symbolic vector.
Default: 2
Examples
Compute the 2-norm of the inverse of the 3-by-3 magic square A:
A = inv(sym(magic(3)))
norm2 = norm(A)
A =
[ 53/360, -13/90, 23/360]
[ -11/180, 1/45, 19/180]
[ -7/360, 17/90, -37/360]
norm2 =
3^(1/2)/6
ans =
0.28867513459481288225
Compute the 1-norm, Frobenius norm, and infinity norm of the inverse of the 3-by-3
magic square A:
A = inv(sym(magic(3)))
norm1 = norm(A, 1)
4-1049
4 Functions Alphabetical List
A =
[ 53/360, -13/90, 23/360]
[ -11/180, 1/45, 19/180]
[ -7/360, 17/90, -37/360]
norm1 =
16/45
normf =
391^(1/2)/60
normi =
16/45
vpa(norm1, 20)
vpa(normf, 20)
vpa(normi, 20)
ans =
0.35555555555555555556
ans =
0.32956199888808647519
ans =
0.35555555555555555556
Compute the 1-norm, 2-norm, and 3-norm of the column vector V = [Vx; Vy; Vz]:
syms Vx Vy Vz
V = [Vx; Vy; Vz];
norm1 = norm(V, 1)
norm2 = norm(V)
norm3 = norm(V, 3)
norm1 =
abs(Vx) + abs(Vy) + abs(Vz)
norm2 =
(abs(Vx)^2 + abs(Vy)^2 + abs(Vz)^2)^(1/2)
4-1050
norm
norm3 =
(abs(Vx)^3 + abs(Vy)^3 + abs(Vz)^3)^(1/3)
Compute the infinity norm, negative infinity norm, and Frobenius norm of V:
normi =
max(abs(Vx), abs(Vy), abs(Vz))
normni =
min(abs(Vx), abs(Vy), abs(Vz))
normf =
(abs(Vx)^2 + abs(Vy)^2 + abs(Vz)^2)^(1/2)
More About
1-norm of a Matrix
m
A 1 = max
j i =1
Aij , where j = 1 n
2-norm of a Matrix
A 2 = max eigenvalue of A H A
4-1051
4 Functions Alphabetical List
m n 2
A F
=
Aij
i =1 j =1
n n n
A = max
A1 j , A2 j ,, Amj
j =1 j =1 j =1
P-norm of a Vector
1
n P
P
V = Vi
P
i=1
n
2
V F
= Vi
i =1
V = max ( Vi ) , where i = 1 n
4-1052
norm
V - = min ( Vi ) , where i = 1 n
Tips
Calling norm for a numeric matrix that is not a symbolic object invokes the MATLAB
norm function.
See Also
cond | equationsToMatrix | inv | linsolve | rank
Introduced in R2012b
4-1053
4 Functions Alphabetical List
not
Logical NOT for symbolic expressions
Syntax
~A
not(A)
Description
~A represents the logical negation. ~A is true when A is false and vice versa.
Input Arguments
A
Examples
Create this logical expression using ~:
syms x y
xy = ~(x > y);
assume(xy)
assumptions
4-1054
not
ans =
~y < x
syms x
range = abs(x) < 1 & ~(abs(x) < 1/3);
Replace variable x with these numeric values. Note that subs does not evaluate these
inequalities to logical 1 or 0.
x1 = subs(range, x, 0)
x2 = subs(range, x, 2/3)
x1 =
0 < 1 & ~0 < 1/3
x2 =
2/3 < 1 & ~2/3 < 1/3
logical(x1)
isAlways(x2)
ans =
logical
0
ans =
logical
1
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 =
FALSE
s2 =
TRUE
4-1055
4 Functions Alphabetical List
logical(s1)
logical(s2)
ans =
logical
0
ans =
logical
1
More About
Tips
If you call simplify for a logical expression that contains 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 logical.
See Also
all | and | any | isAlways | or | piecewise | xor
Introduced in R2012a
4-1056
null
null
Form basis for null space of matrix
Syntax
Z = null(A)
Description
Z = null(A) returns a list of vectors that form the basis for the null space of a matrix
A. The product A*Z is zero. size(Z, 2) is the nullity of A. If A has full rank, Z is empty.
Examples
Find the basis for the null space and the nullity of the magic square of symbolic numbers.
Verify that A*Z is zero:
A = sym(magic(4));
Z = null(A)
nullityOfA = size(Z, 2)
A*Z
Z =
-1
-3
3
1
nullityOfA =
1
ans =
0
0
0
0
Find the basis for the null space of the matrix B that has full rank:
4-1057
4 Functions Alphabetical List
B = sym(hilb(3))
Z = null(B)
B =
[ 1, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
Z =
Empty sym: 1-by-0
See Also
rank | rref | size | svd
4-1058
numden
numden
Extract numerator and denominator
Syntax
[N,D] = numden(A)
Description
[N,D] = numden(A) converts A to a rational form where the numerator and
denominator are relatively prime polynomials with integer coefficients. The function
returns the numerator and denominator of the rational form of an expression.
Examples
Numerators and Denominators of Symbolic Numbers
Find the numerator and denominator of a symbolic number.
[n, d] = numden(sym(4/5))
n =
4
d =
5
4-1059
4 Functions Alphabetical List
n =
x^2 + y^2
d =
x*y
n =
[ a, 1]
[ 1, 1]
d =
[ b, b]
[ a, a*b]
Input Arguments
A Input
symbolic number | symbolic expression | symbolic function | symbolic vector | symbolic
matrix
Output Arguments
N Numerator
symbolic number | symbolic expression | symbolic function | symbolic vector | symbolic
matrix
D Denominator
symbolic number | symbolic expression | symbolic function | symbolic vector | symbolic
matrix
4-1060
numden
See Also
divisors | partfrac | simplifyFraction
4-1061
4 Functions Alphabetical List
numel
Number of elements of symbolic array
Syntax
numel(A)
Description
numel(A) returns the number of elements in symbolic array A, equal to
prod(size(A)).
Examples
Number of Elements in Vector
Find the number of elements in vector V.
syms x y
V = [x y 3];
numel(V)
ans =
3
A(:,:,1) =
[ 8, 1, 6]
4-1062
numel
[ 3, 5, 7]
[ 4, 9, 2]
A(:,:,2) =
[ 8, 3, 4]
[ 1, 5, 9]
[ 6, 7, 2]
numel(A)
ans =
18
Input Arguments
A Input
symbolic variable | symbolic vector | symbolic matrix | symbolic multidimensional array
See Also
prod | size
Introduced in R2008b
4-1063
4 Functions Alphabetical List
odeFunction
Convert system of symbolic algebraic expressions to MATLAB function handle suitable
for ode45, ode15s, and other ODE solvers
Syntax
f = odeFunction(expr,vars)
f = odeFunction(expr,vars,p1,...,pN)
f = odeFunction( ___ ,Name,Value)
Description
f = odeFunction(expr,vars) converts a system of symbolic algebraic expressions to
a MATLAB function handle acceptable as an input argument to the numerical MATLAB
ODE solvers, except for ode15i. The argument vars specifies the state variables of the
system.
Examples
syms y(t);
eqn = diff(y(t), t, t) == (1 - y(t)^2)*diff(y(t),t) - y(t);
4-1064
odeFunction
[eqs,vars] = reduceDifferentialOrder(eqn,y(t))
eqs =
diff(Dyt(t), t) + y(t) + Dyt(t)*(y(t)^2 - 1)
Dyt(t) - diff(y(t), t)
vars =
y(t)
Dyt(t)
Set initial conditions for y(t) and its derivative Dy(t). For example, set the initial value
of the variable to 2 and the initial value of its first derivative to 0.
initConditions = [2,0];
Find the mass matrix M of the system and a vector F containing the right sides of
equations.
[M,F] = massMatrixForm(eqs,vars)
M =
[ 0, 1]
[ -1, 0]
F =
- y(t) - Dyt(t)*(y(t)^2 - 1)
-Dyt(t)
f = M\F
f =
Dyt(t)
Dyt(t) - y(t) - Dyt(t)*y(t)^2
4-1065
4 Functions Alphabetical List
odefun = odeFunction(f,vars);
ode15s(odefun, [0 10], initConditions)
Create the system of differential algebraic equations. Here, the symbolic functions x1(t)
and x2(t) represent the state variables of the system. The system also contains constant
symbolic parameters a, b, and the parameter function r(t). These parameters do not
represent state variables. Specify the equations and state variables as two symbolic
4-1066
odeFunction
Find the mass matrix M and vector of the right side F for this system. M and F refer to the
form M ( t, x ( t ) ) x& ( t ) = F ( t, x ( t) ) .
M =
[ 1, 0]
[ 0, 0]
F =
b*x2(t)^2 + a*x1(t)
r(t)^2 - x1(t)^2 - x2(t)^2
Use odeFunction to generate MATLAB function handles from M and F. The function
handle F contains symbolic parameters.
M = odeFunction(M, vars)
F = odeFunction(F, vars, a, b, r(t))
M =
function_handle with value:
@(t,in2)reshape([1.0,0.0,0.0,0.0],[2,2])
F =
function_handle with value:
@(t,in2,param1,param2,param3)[param1.*in2(1,:)+...
param2.*in2(2,:).^2;param3.^2-in2(1,:).^2-in2(2,:).^2]
4-1067
4 Functions Alphabetical List
t0 = 0;
y0 = [-r(t0)*sin(0.1); r(t0)*cos(0.1)];
yp0= [a*y0(1) + b*y0(2)^2; 1.234];
Create an option set that contains the mass matrixMof the system and vectoryp0of
initial conditions for the derivatives.
4-1068
odeFunction
Create the following system of differential algebraic equations. Here, the functions x(t)
and y(t) represent state variables of the system.
Find the mass matrix M and vector of the right side F for this system. M andF refer to the
form M ( t, x ( t ) ) x& ( t ) = F ( t, x ( t) ) .
M =
[ 1, 2]
[ 0, 0]
F =
y(t)/10
cos(t) - x(t) + y(t) - (t*sin(x(t)))/5
Use odeFunction to generate MATLAB code from M and F, and to write that code to
myfileM.m and myfileF.m. If the files myfileM.m and myfileF.m already exist in the
current folder, odeFunction overwrites the contents of the existing files. You can open
and edit the resulting files.
4-1069
4 Functions Alphabetical List
%MYFILEF
% EXPR = MYFILEF(T,IN2)
x = in2(1,:);
y = in2(2,:);
expr = [y.*(1.0./1.0e1);-x+y+cos(t)-t.*sin(x).*(1.0./5.0)];
Specify consistent initial values for x(t) and y(t) and their first derivatives. Here,
the vector xy0 specifies initial values for x(t) and y(t), and the vector xyp0 specifies
initial values for their derivatives.
Create an option set that contains the mass matrixMof the system, vectorxyp0of initial
conditions for the derivatives, and numerical tolerances for the numerical search.
4-1070
odeFunction
Sparse Matrices
Use the name-value pair argument 'Sparse',true when converting sparse symbolic
matrices to MATLAB function handles.
Create the system of differential algebraic equations. Here, the symbolic functions x1(t)
and x2(t) represent the state variables of the system. Specify the equations and state
variables as two symbolic vectors: equations as a vector of symbolic equations, and
variables as a vector of symbolic function calls.
syms x1(t) x2(t)
a = -0.6;
4-1071
4 Functions Alphabetical List
b = -0.1;
r = @(t) cos(t)/(1 + t^2);
Find the mass matrix M and vector of the right side F for this system. M and F refer to the
form M ( t, x ( t ) ) x& ( t ) = F ( t, x ( t) ) .
M =
[ 1, 0]
[ 0, 0]
F =
- (3*x1(t))/5 - x2(t)^2/10
cos(t)^2/(t^2 + 1)^2 - x1(t)^2 - x2(t)^2
Generate MATLAB function handles from M and F. Because most of the elements of the
mass matrix M are zeros, use the Sparse argument when converting M.
M = odeFunction(M, vars, 'Sparse', true)
F = odeFunction(F, vars)
M =
function_handle with value:
@(t,in2)sparse([1],[1],[1.0],2,2)
F =
function_handle with value:
@(t,in2)[in2(1,:).*(-3.0./5.0)-in2(2,:).^2.*(1.0./1.0e1);...
cos(t).^2.*1.0./(t.^2+1.0).^2-in2(1,:).^2-in2(2,:).^2]
Create an option set that contains the mass matrixMof the system and vectoryp0of
initial conditions for the derivatives.
opt = odeset('mass', M, 'InitialSlope', yp0);
4-1072
odeFunction
Input Arguments
expr System of algebraic expressions
vector of symbolic expressions
4-1073
4 Functions Alphabetical List
State variables, specified as a vector of symbolic functions or function calls, such as x(t).
Example: [x(t),y(t)] or [x(t);y(t)]
Path to the file containing generated code, specified as a character vector. The generated
file accepts arguments of type double, and can be used without Symbolic Math Toolbox.
If the value is empty, odeFunction generates an anonymous function. If the character
vector does not end in .m, the function appends .m.
By default, odeFunction with the File argument generates a file containing optimized
code. Optimized means intermediate variables are automatically generated to simplify
or speed up the code. MATLAB generates intermediate variables as a lowercase letter
t followed by an automatically generated number, for example t32. To disable code
optimization, use the Optimize argument.
4-1074
odeFunction
By default, odeFunction with the File argument generates a file containing optimized
code. Optimized means intermediate variables are automatically generated to simplify
or speed up the code. MATLAB generates intermediate variables as a lowercase letter t
followed by an automatically generated number, for example t32.
odeFunction without the File argument (or with a file path specified by an empty
character vector) creates a function handle. In this case, the code is not optimized. If you
try to enforce code optimization by setting Optimize to true, then odeFunction throws
an error.
'Sparse' Flag that switches between sparse and dense matrix generation
false (default) | true
Flag that switches between sparse and dense matrix generation, specified as true or
false. When you specify 'Sparse',true, the generated function represents symbolic
matrices by sparse numeric matrices. Use 'Sparse',true when you convert symbolic
matrices containing many zero elements. Often, operations on sparse matrices are more
efficient than the same operations on dense matrices. See Sparse Matrices on page
4-1071.
Output Arguments
f Function handle that can serve as input argument to all numerical MATLAB ODE solvers,
except for ode15i
MATLAB function handle
Function handle that can serve as input argument to all numerical MATLAB ODE
solvers, except for ode15i, returned as a MATLAB function handle.
odeFunction returns a function handle suitable for the ODE solvers such as ode45,
ode15s, ode23t, and others. The only ODE solver that does not accept this function
handle is the solver for fully implicit differential equations, ode15i. To convert the
system of equations to a function handle suitable for ode15i, use daeFunction.
See Also
daeFunction | decic | findDecoupledBlocks | incidenceMatrix |
isLowIndexDAE | massMatrixForm | matlabFunction | ode15i | ode15s | ode23t
| ode45 | reduceDAEIndex | reduceDAEToODE | reduceDifferentialOrder |
reduceRedundancies
4-1075
4 Functions Alphabetical List
Introduced in R2015a
4-1076
odeToVectorField
odeToVectorField
Convert higher-order differential equations to systems of first-order differential
equations
Syntax
V = odeToVectorField(eqn1,...,eqnN)
[V,Y] = odeToVectorField(eqn1,...,eqnN)
Description
Input Arguments
eqn1,...,eqnN
When representing eqn as a symbolic equation, you must create a symbolic function,
for example y(x). Here x is an independent variable for which you solve an ordinary
differential equation. Use the == operator to create an equation. Use the diff function to
indicate differentiation. For example, to convert d y(x)/dt = x*y(x), use:
2 2
4-1077
4 Functions Alphabetical List
syms y(x)
V = odeToVectorField(diff(y, 2) == x*y)
When representing eqn as a character vector, use the letter D to indicate differentiation.
By default, odeToVectorField assumes that the independent variable is t. Thus, Dy
means dy/dt. You can specify the independent variable. The letter D followed by a digit
indicates repeated differentiation. Any character immediately following a differentiation
operator is a dependent variable. For example, to convert d y(x)/dt = x*y(x), enter:
2 2
V = odeToVectorField('D2y = x*y','x')
or
V = odeToVectorField('D2y == x*y','x')
Output Arguments
V
Symbolic vector representing the substitutions made when converting the input
equations eqn1,...,eqnN to the elements of V.
Examples
syms y(t)
V = odeToVectorField(t^3*diff(y, 5) + 2*t*diff(y, 4) + diff(y, 2) + y^2 == -3*t)
V =
4-1078
odeToVectorField
Y[2]
Y[3]
Y[4]
Y[5]
-(3*t + Y[1]^2 + 2*t*Y[5] + Y[3])/t^3
V =
Y[1] - Y[2]
Y[3]
Y[1] + Y[2]
Y =
g
f
Df
syms y(t)
V = odeToVectorField(diff(y, 2) == (1 - y^2)*diff(y) - y)
V =
Y[2]
- (Y[1]^2 - 1)*Y[2] - Y[1]
Generate a MATLAB function from this system of first-order differential equations using
matlabFunction with V as an input:
M = matlabFunction(V,'vars', {'t','Y'})
M =
4-1079
4 Functions Alphabetical List
To solve this system, call the MATLAB ode45 numerical solver using the generated
MATLAB function as an input:
Plot the solution using linspace to generate 100 points in the interval [0,20] and deval
to evaluate the solution for each point:
x = linspace(0,20,100);
y = deval(sol,x,1);
plot(x,y)
4-1080
odeToVectorField
V =
Y[2]
x
If you define equations by character vectors and do not specify the independent variable,
odeToVectorField assumes that the independent variable is t. This assumption
makes the equation y(t)=x inconsistent with the initial condition y(0)=t. In this case,
y(t)=d2t/dt2=0, and odeToVectorField errors.
More About
Tips
The names of symbolic variables used in differential equations should not contain the
letter D because odeToVectorField assumes that D is a differential operator and
any character immediately following D is a dependent variable.
To generate a MATLAB function for the resulting system of first-order differential
equations, use matlabFunction with V as an input. Then, you can use the generated
MATLAB function as an input for the MATLAB numerical solvers ode23 and ode45.
The highest-order derivatives must appear in eqn1,...,eqnN linearly. For example,
odeToVectorField can convert these equations:
y(t) = t2
y*y(t) = t2. odeToVectorField can convert this equation because it can be
rewritten as y(t) = t2/y.
y(t)2 = t2
sin(y(t)) = t2
4-1081
4 Functions Alphabetical List
Algorithms
Y1 = y
Y2 = y
Y3 = y
Yn-1 = y( n -2)
Yn = y( n -1)
Using the new variables, you can rewrite the equation as a system of n first-order
differential equations:
Y1 = y = Y2
Y2 = y = Y3
Yn-1 = y(n -1) = Yn
a (t ) a ( t) a (t ) a (t ) r (t )
Yn = - n -1 Yn - n- 2 Yn-1 - ... - 1 Y2 - 0 Y1 +
an t( ) (
an t ) (
an t ) (
an t ) an ( t )
odeToVectorField returns the right sides of these equations as the elements of vector
V.
See Also
dsolve | matlabFunction | ode23 | ode45 | syms
4-1082
odeToVectorField
Introduced in R2012a
4-1083
4 Functions Alphabetical List
openmn
Open MuPAD notebook
Syntax
h = openmn(file)
Description
h = openmn(file) opens the MuPAD notebook file named file, and returns a handle
to the file in h. The file name must be a full path unless the file is in the current folder.
The command h = mupad(file) accomplishes the same task.
Examples
To open a notebook named e-e-x.mn in the folder \Documents\Notes of drive H:,
enter:
h = openmn('H:\Documents\Notes\e-e-x.mn');
More About
Create MuPAD Notebooks on page 3-3
Open MuPAD Notebooks on page 3-6
See Also
mupad | open | openmu | openxvc | openxvz
Introduced in R2008b
4-1084
openmu
openmu
Open MuPAD program file
Syntax
openmu(file)
Description
openmu(file) opens the MuPAD program file named file in the MATLAB Editor. The
command open(file) accomplishes the same task.
Examples
To open a program file named yyx.mu located in the folder \Documents\Notes on drive
H:, enter:
openmu('H:\Documents\Notes\yyx.mu')
More About
Open MuPAD Notebooks on page 3-6
See Also
mupad | open | openmn | openxvc | openxvz
Introduced in R2008b
4-1085
4 Functions Alphabetical List
openxvc
Open MuPAD uncompressed graphics file (XVC)
Syntax
openxvc(file)
Description
openxvc(file) opens the MuPAD XVC graphics file named file. The file name must
be a full path unless the file is in the current folder.
Input Arguments
file
Examples
To open a graphics file named image1.xvc in the folder \Documents\Notes of drive
H:, enter:
openxvc('H:\Documents\Notes\image1.xvc')
More About
Open MuPAD Notebooks on page 3-6
See Also
mupad | open | openmn | openmu | openxvz
Introduced in R2008b
4-1086
openxvz
openxvz
Open MuPAD compressed graphics file (XVZ)
Syntax
openxvz(file)
Description
openxvz(file) opens the MuPAD XVZ graphics file named file. The file name must
be a full path unless the file is in the current folder.
Input Arguments
file
Examples
To open a graphics file named image1.xvz in the folder \Documents\Notes of drive
H:, enter:
openxvz('H:\Documents\Notes\image1.xvz')
More About
Open MuPAD Notebooks on page 3-6
See Also
mupad | open | openmn | openmu | openxvc
Introduced in R2008b
4-1087
4 Functions Alphabetical List
or
Logical OR for symbolic expressions
Syntax
A | B
or(A,B)
Description
A | B represents the logical disjunction. A | B is true when either A or B or both are
true.
or(A,B) is equivalent to A | B.
Input Arguments
A
Examples
Combine these symbolic inequalities into the logical expression using |:
syms x y
xy = x >= 0 | y >= 0;
4-1088
or
assume(xy)
ans =
0 <= x | 0 <= y
Replace variable x with these numeric values. If you replace x with 10, one inequality
is valid. If you replace x with 0, both inequalities are invalid. Note that subs does not
evaluate these inequalities to logical 1 or 0.
x1 = subs(range, x, 10)
x2 = subs(range, x, 0)
x1 =
1 < 10 | 10 < -1
x2 =
0 < -1 | 1 < 0
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-1089
4 Functions Alphabetical List
s2 =
FALSE
isAlways(s1)
isAlways(s2)
ans =
logical
1
ans =
logical
0
Combine multiple conditions by applying or to the conditions using the fold function.
syms x
cond = fold(@or, x == 1:10);
assume(cond)
assumptions
ans =
x == 1 | x == 2 | x == 3 | x == 4 | x == 5 |...
x == 6 | x == 7 | x == 8 | x == 9 | x == 10
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 | and | any | isAlways | not | piecewise | xor
Introduced in R2012a
4-1090
orth
orth
Orthonormal basis for range of symbolic matrix
Syntax
B = orth(A)
B = orth(A,'real')
B = orth(A,'skipnormalization')
B = orth(A,'real','skipnormalization')
Description
B = orth(A) computes an orthonormal basis for the range of A.
Input Arguments
A
Symbolic matrix.
'real'
Flag that prompts orth to avoid using a complex scalar product in the orthogonalization
process.
4-1091
4 Functions Alphabetical List
'skipnormalization'
Flag that prompts orth to skip normalization and compute an orthogonal basis instead
of an orthonormal basis. If you use this flag, lengths of the resulting vectors (the columns
of matrix B) are not required to be 1.
Output Arguments
B
Symbolic matrix.
Examples
Compute an orthonormal basis of the range of this matrix. Because these numbers are
not symbolic objects, you get floating-point results.
B =
-0.9859 -0.1195 0.1168
0.0290 -0.8108 -0.5846
0.1646 -0.5729 0.8029
Now, convert this matrix to a symbolic object, and compute an orthonormal basis:
B =
[ (2*5^(1/2))/5, -6^(1/2)/6, -(2^(1/2)*15^(1/2))/30]
[ 5^(1/2)/5, 6^(1/2)/3, (2^(1/2)*15^(1/2))/15]
[ 0, 6^(1/2)/6, -(2^(1/2)*15^(1/2))/6]
You can use double to convert this result to the double-precision numeric form. The
resulting matrix differs from the matrix returned by the MATLAB orth function because
these functions use different versions of the Gram-Schmidt orthogonalization algorithm:
double(B)
4-1092
orth
ans =
0.8944 -0.4082 -0.1826
0.4472 0.8165 0.3651
0 0.4082 -0.9129
B'*B
ans =
[ 1, 0, 0]
[ 0, 1, 0]
[ 0, 0, 1]
norm(B(:, 1))
norm(B(:, 2))
norm(B(:, 3))
ans =
1
ans =
1
ans =
1
Compute an orthonormal basis of this matrix using 'real' to avoid complex conjugates:
syms a
A = [a 1; 1 a];
B = orth(A,'real')
B =
[ a/(a^2 + 1)^(1/2), -(a^2 - 1)/((a^2 + 1)*((a^2 -...
1)^2/(a^2 + 1)^2 + (a^2*(a^2 - 1)^2)/(a^2 + 1)^2)^(1/2))]
[ 1/(a^2 + 1)^(1/2), (a*(a^2 - 1))/((a^2 + 1)*((a^2 -...
1)^2/(a^2 + 1)^2 + (a^2*(a^2 - 1)^2)/(a^2 + 1)^2)^(1/2))]
syms a
A = [a 1; 1 a];
4-1093
4 Functions Alphabetical List
B = orth(A,'skipnormalization')
B =
[ a, -(a^2 - 1)/(a*conj(a) + 1)]
[ 1, -(conj(a) - a^2*conj(a))/(a*conj(a) + 1)]
syms a
A = [a 1; 1 a];
B = orth(A,'skipnormalization','real')
B =
[ a, -(a^2 - 1)/(a^2 + 1)]
[ 1, (a*(a^2 - 1))/(a^2 + 1)]
More About
Orthonormal Basis
Tips
Calling orth for numeric arguments that are not symbolic objects invokes the
MATLAB orth function. Results returned by MATLAB orth can differ from results
returned by orth because these two functions use different algorithms to compute an
orthonormal basis. The Symbolic Math Toolbox orth function uses the classic Gram-
Schmidt orthogonalization algorithm. The MATLAB orth function uses the modified
Gram-Schmidt algorithm because the classic algorithm is numerically unstable.
Using 'skipnormalization' to compute an orthogonal basis instead of an
orthonormal basis can speed up your computations.
Algorithms
4-1094
orth
See Also
norm | null | orth | rank | svd
Introduced in R2013a
4-1095
4 Functions Alphabetical List
pade
Pade approximant
Syntax
pade(f,var)
pade(f,var,a)
pade( ___ ,Name,Value)
Description
pade(f,var) returns the third-order Pad approximant of the expression f at var = 0.
For details, see Pad Approximant on page 4-1102.
If you do not specify var, then pade uses the default variable determined by
symvar(f,1).
pade( ___ ,Name,Value) uses additional options specified by one or more Name,Value
pair arguments. You can specify Name,Value after the input arguments in any of the
previous syntaxes.
Examples
syms x
pade(sin(x))
4-1096
pade
ans =
-(x*(7*x^2 - 60))/(3*(x^2 + 20))
syms x y
pade(sin(x) + cos(y))
ans =
(- 7*x^3 + 3*cos(y)*x^2 + 60*x + 60*cos(y))/(3*(x^2 + 20))
Specify the expansion variable as y. The pade function returns the Pad approximant
with respect to y.
pade(sin(x) + cos(y),y)
ans =
(12*sin(x) + y^2*sin(x) - 5*y^2 + 12)/(y^2 + 12)
syms x
f = tan(x);
P = pade(f);
y = subs(P,x,3*pi/4)
y =
(pi*((9*pi^2)/16 - 15))/(4*((9*pi^2)/8 - 5))
vpa(y)
ans =
4-1097
4 Functions Alphabetical List
-1.2158518789569086447244881326842
Find the Pad approximant of tan(x) using pade with an expansion point of 0 and
Order of [1 1]. Find the value of tan(1/5) by substituting into the Pad approximant
using subs, and use vpa to convert 1/5 into a numeric value.
syms x
p11 = pade(tan(x),x,0,'Order',[1 1])
p11 = subs(p11,x,vpa(1/5))
p11 =
x
p11 =
0.2
Find the approximation error by subtracting p11 from the actual value of tan(1/5).
y = tan(vpa(1/5));
error = y - p11
error =
0.0027100355086724833213582716475345
Increase the accuracy of the Pad approximant by increasing the order using Order. Set
Order to [2 2], and find the error.
p22 =
-(3*x)/(x^2 - 3)
error =
0.0000073328059697806186555689448317799
4-1098
pade
If the expansion point is a pole or zero, the accuracy of the Pad approximant decreases.
Setting the OrderMode option to relative compensates for the decreased accuracy. For
details, see Pad Approximant on page 4-1102. Because the tan function has a zero
at 0, setting OrderMode to relative increases accuracy. This option has no effect if the
expansion point is not a pole or zero.
p22Rel =
(x*(x^2 - 15))/(3*(2*x^2 - 5))
error =
0.0000000084084014806113311713765317725998
The accuracy increases if the expansion point is a pole or zero and OrderMode is set to
relative.
syms x
expr = exp(x);
hold on
grid on
for i = 1:4
fplot(expr - pade(expr,'Order',i))
end
axis([-4 4 -4 4])
legend('Order [1,1]','Order [2,2]','Order [3,3]','Order [4,4]',...
'Location','Best')
title('Difference Between exp(x) and its Pade Approximant')
ylabel('Error')
4-1099
4 Functions Alphabetical List
Input Arguments
f Input to approximate
symbolic number | symbolic variable | symbolic vector | symbolic matrix | symbolic
multidimensional array | symbolic function | symbolic expression
4-1100
pade
Expansion variable, specified as a symbolic variable. If you do not specify var, then pade
uses the default variable determined by symvar(f,1).
a Expansion point
number | symbolic number | symbolic variable | symbolic function | symbolic
expression
4-1101
4 Functions Alphabetical List
'OrderMode' Flag that selects absolute or relative order for Pad approximant
character vector
Flag that selects absolute or relative order for Pad approximant, specified as a
character vector. The default value of absolute uses the standard definition of the Pad
approximant. If you set OrderMode to relative, it only has an effect when there is a
pole or a zero at the expansion point a. In this case, to increase accuracy, pade multiplies
the numerator by (var - a) where p is the multiplicity of the zero or pole at the
p
More About
Pad Approximant
By default, pade approximates the function f(x) using the standard form of the Pad
approximant of order [m,n] around x=x0 which is
m
a0 + a1 ( x - x0 ) + ... + am ( x - x0 )
.
n
1 + b1 ( x - x0 ) + ... + bn ( x - x0 )
When OrderMode is relative, and a pole or zero exists at the expansion point x=x0,
the pade function uses this form of the Pad approximant
( x - x0 ) p (a
0 + a1 ( x - x0 ) + ... + am ( x - x0 )
m
).
n
1 + b1 ( x - x0 ) + ... + bn ( x - x0 )
The parameters p and a0 are given by the leading order term f = a0(x - x0)p + O((x - x0)p + 1)
of the series expansion of f around x = x0. Thus, p is the multiplicity of the pole or zero at
x0.
Tips
If you use both the third argument a and ExpansionPoint to specify the expansion
point, the value specified via ExpansionPoint prevails.
4-1102
pade
Algorithms
The parameters a1,,bn are chosen such that the series expansion of the Pade
approximant coincides with the series expansion of f to the maximal possible order.
The expansion points and i are not allowed.
When pade cannot find the Pad approximant, it returns the function call.
For pade to return the Pad approximant, a Taylor or Laurent series expansion of f
must exist at the expansion point.
See Also
series | taylor
Introduced in R2014b
4-1103
4 Functions Alphabetical List
partfrac
Partial fraction decomposition
Syntax
partfrac(expr,var)
partfrac(expr,var,Name,Value)
Description
partfrac(expr,var) finds the partial fraction decomposition of expr with respect to
var. If you do not specify var, then partfrac uses the variable determined by symvar.
Examples
Partial Fraction Decomposition
Find partial fraction decomposition of univariate and multivariate expressions.
First, find partial fraction decomposition of univariate expressions. For expressions with
one variable, you can omit specifying the variable.
syms x
partfrac(x^2/(x^3 - 3*x + 2))
ans =
5/(9*(x - 1)) + 1/(3*(x - 1)^2) + 4/(9*(x + 2))
ans =
4-1104
partfrac
ans =
b/(2*(a - b)) - b/(2*(a + b)) + 1
ans =
a/(2*(a + b)) + a/(2*(a - b))
If you do not specify the variable, then partfrac computes partial fraction
decomposition with respect to a variable determined by symvar.
symvar(a^2/(a^2 - b^2),1)
partfrac(a^2/(a^2 - b^2))
ans =
b
ans =
a/(2*(a + b)) + a/(2*(a - b))
Factorization Modes
Use the FactorMode argument to choose a particular factorization mode.
Find the partial fraction decomposition without specifying the factorization mode. By
default, partfrac uses factorization over rational numbers. In this mode, partfrac
keeps numbers in their exact symbolic form.
syms x
partfrac(1/(x^3 + 2), x)
ans =
1/(x^3 + 2)
Find the partial fraction decomposition of the same expression, but this time use numeric
factorization over real numbers. In this mode, partfrac factors the denominator into
linear and quadratic irreducible polynomials with real coefficients. This mode converts
all numeric values to floating-point numbers.
4-1105
4 Functions Alphabetical List
ans =
0.2099868416491455274612017678797/(x + 1.2599210498948731647672106072782) -...
(0.2099868416491455274612017678797*x - 0.52913368398939982491723521309077)/(x^2 -...
1.2599210498948731647672106072782*x + 1.5874010519681994747517056392723)
Find the partial fraction decomposition of this expression using factorization over
complex numbers. In this mode, partfrac reduces quadratic polynomials in the
denominator to linear expressions with complex coefficients. This mode converts all
numeric values to floating-point numbers.
partfrac(1/(x^3 + 2), x, 'FactorMode', 'complex')
ans =
0.2099868416491455274612017678797/(x + 1.2599210498948731647672106072782) +...
(- 0.10499342082457276373060088393985 - 0.18185393932862023392667876903163i)/...
(x - 0.62996052494743658238360530363911 - 1.0911236359717214035600726141898i) +...
(- 0.10499342082457276373060088393985 + 0.18185393932862023392667876903163i)/...
(x - 0.62996052494743658238360530363911 + 1.0911236359717214035600726141898i)
Find the partial fraction decomposition of this expression using the full factorization
mode. In this mode, partfrac factors the denominator into linear expressions, reducing
quadratic polynomials to linear expressions with complex coefficients. This mode keeps
numbers in their exact symbolic form.
partfrac(1/(x^3 + 2), x, 'FactorMode', 'full')
ans =
2^(1/3)/(6*(x + 2^(1/3))) +...
(2^(1/3)*((3^(1/2)*1i)/2 - 1/2))/(6*(x + 2^(1/3)*((3^(1/2)*1i)/2 - 1/2))) -...
(2^(1/3)*((3^(1/2)*1i)/2 + 1/2))/(6*(x - 2^(1/3)*((3^(1/2)*1i)/2 + 1/2)))
Approximate the result with floating-point numbers by using vpa. Because the
expression does not contain any symbolic parameters besides the variable x, the result is
the same as in complex factorization mode.
vpa(ans)
ans =
0.2099868416491455274612017678797/(x + 1.2599210498948731647672106072782) +...
(- 0.10499342082457276373060088393985 - 0.18185393932862023392667876903163i)/...
(x - 0.62996052494743658238360530363911 - 1.0911236359717214035600726141898i) +...
(- 0.10499342082457276373060088393985 + 0.18185393932862023392667876903163i)/...
(x - 0.62996052494743658238360530363911 + 1.0911236359717214035600726141898i)
4-1106
partfrac
Replace 2 in the same expression with a symbolic parameter a and find partial fraction
decomposition in the complex and full factorization modes. In the complex mode,
partfrac factors only those expressions in the denominator whose coefficients can be
converted to floating-point numbers. Thus, it returns this expression unchanged.
syms a
partfrac(1/(x^3 + a), x, 'FactorMode', 'complex')
ans =
1/(x^3 + a)
When you use the full factorization mode, partfrac factors expressions in the
denominator symbolically. Thus, the partial fraction decomposition of the same
expression in the full factorization mode is the following expression.
ans =
1/(3*(-a)^(2/3)*(x - (-a)^(1/3))) -...
((3^(1/2)*1i)/2 + 1/2)/(3*(-a)^(2/3)*(x + (-a)^(1/3)*((3^(1/2)*1i)/2 + 1/2))) +...
((3^(1/2)*1i)/2 - 1/2)/(3*(-a)^(2/3)*(x - (-a)^(1/3)*((3^(1/2)*1i)/2 - 1/2)))
syms x
s = partfrac(1/(x^3 + x - 3), x, 'FactorMode','full')
s =
symsum(-((6*root(z^3 + z - 3, z, k)^2)/247 +...
(27*root(z^3 + z - 3, z, k))/247 +...
4/247)/(root(z^3 + z - 3, z, k) - x), k, 1, 3)
vpa(s)
ans =
0.1846004942289254798185772017286/(x - 1.2134116627622296341321313773815) +...
(- 0.092300247114462739909288600864302 + 0.11581130283490645120989658654914i)/...
4-1107
4 Functions Alphabetical List
P =
5/(9*(x - 1)) + 1/(3*(x - 1)^2) + 4/(9*(x + 2))
Partial fraction decomposition is a sum of fractions. Use the children function to return
a vector containing the terms of that sum. then use numden to extract numerators and
denominators of the terms.
[N,D] = numden(children(P))
N =
[ 5, 1, 4]
D =
[ 9*x - 9, 3*(x - 1)^2, 9*x + 18]
Reconstruct the partial fraction decomposition from the vectors of numerators and
denominators.
P1 = sum(N./D)
P1 =
1/(3*(x - 1)^2) + 5/(9*x - 9) + 4/(9*x + 18)
Verify that the reconstructed expression, P1, is equivalent to the original partial fraction
decomposition, P.
isAlways(P1 == P)
ans =
logical
1
4-1108
partfrac
Input Arguments
expr Rational expression
symbolic expression | symbolic function
4-1109
4 Functions Alphabetical List
More About
Partial Fraction Decomposition
p ( x)
f (x) = g (x) + ,
q(x)
pj (x)
f ( x ) = g ( x) + q (x)
j j
polynomials. Also, the numerators p j ( x) are polynomials of smaller degrees than the
corresponding denominators q j ( x ) .
Partial fraction decomposition can simplify integration by integrating each term of the
returned expression separately.
See Also
children | coeffs | collect | combine | compose | divisors | expand | factor
| horner | numden | rewrite | simplify | simplifyFraction
Introduced in R2015a
4-1110
piecewise
piecewise
Conditionally defined expression or function
Syntax
pw = piecewise(cond1,val1,cond2,val2,...)
pw = piecewise(cond1,val1,cond2,val2,...,otherwiseVal)
Description
pw = piecewise(cond1,val1,cond2,val2,...) returns the piecewise expression
or function pw whose value is val1 when condition cond1 is true, is val2 when cond2 is
true, and so on. If no condition is true, the value of pw is NaN.
Examples
-1 x<0
y=
1 x>0
syms x
y = piecewise(x<0, -1, x>0, 1)
y =
4-1111
4 Functions Alphabetical List
ans =
[ -1, NaN, 1]
- 1 x < 0
y ( x) =
1 x >0
syms y(x)
y(x) = piecewise(x<0, -1, x>0, 1)
y(x) =
piecewise(x < 0, -1, 0 < x, 1)
Because y(x) is a symbolic function, you can directly evaluate it for values of x. Evaluate
y(x) at -2, 0, and 2. Because y(x) is undefined at x = 0, the value is NaN. For details,
see Create Symbolic Functions on page 1-7.
y([-2 0 2])
ans =
[ -1, NaN, 1]
4-1112
piecewise
- 2 x < -2
( )
y x = 0 -2 < x < 0 .
1 otherwise
syms y(x)
y(x) = piecewise(x<-2, -2, -2<x<0, 0, 1)
y(x) =
piecewise(x < -2, -2, x in Dom::Interval(-2, 0), 0, 1)
Evaluate y(x) between -3 and 1 by generating values using linspace and substituting
for x using subs. At -2 and 0, y(x) evaluates to 1 because the other conditions are not
true.
xvalues = linspace(-3,1,5)
yvalues = y(xvalues)
xvalues =
-3 -2 -1 0 1
yvalues =
[ -2, 1, 0, 1, 1]
syms x
y = piecewise(x<-2, -2, -2<x<2, x, x>2, 2);
fplot(y)
4-1113
4 Functions Alphabetical List
Assume x > 0. Then define a piecewise expression with the same condition x > 0.
piecewise automatically applies the assumption to simplify the condition.
syms x
assume(x > 0)
pw = piecewise(x<0, -1, x>0, 1)
pw =
4-1114
piecewise
assume(x,'clear')
Create a piecewise expression pw with the condition x > 0. Then set the assumption
that x > 0. Apply the assumption to pw by using simplify.
pw =
1
assume(x, 'clear')
1/x x < -1
y=
sin( x) / x x -1
syms x
y = piecewise(x<-1, 1/x, x>=-1, sin(x)/x);
diffy = diff(y, x)
diffy =
piecewise(x < -1, -1/x^2, -1 < x, cos(x)/x - sin(x)/x^2)
inty = int(y, x)
inty =
piecewise(x < -1, log(x), -1 <= x, sinint(x))
4-1115
4 Functions Alphabetical List
Find the limits of y at 0 and -1 by using limit. Because limit finds the double-sided
limit, the piecewise expression must be defined from both sides. Alternatively, you can
find the right- or left-sided limit. For details, see limit.
limit(y, x, 0)
limit(y, x, -1)
ans =
1
ans =
limit(piecewise(x < -1, 1/x, -1 < x, sin(x)/x), x, -1)
Because the two conditions meet at -1, the limits from both sides differ and limit
cannot find a double-sided limit.
syms x
pw1 = piecewise(x<-1, -1, x>=-1, 1);
pw2 = piecewise(x<0, -2, x>=0, 2);
add = pw1 + pw2
sub = pw1 - pw2
mul = pw1 * pw2
div = pw1 / pw2
add =
piecewise(x < -1, -3, x in Dom::Interval([-1], 0), -1, 0 <= x, 3)
sub =
piecewise(x < -1, 1, x in Dom::Interval([-1], 0), 3, 0 <= x, -1)
mul =
piecewise(x < -1, 2, x in Dom::Interval([-1], 0), -2, 0 <= x, 2)
div =
piecewise(x < -1, 1/2, x in Dom::Interval([-1], 0), -1/2, 0 <= x, 1/2)
4-1116
piecewise
does not check for overlapping or conflicting conditions. Instead, like an if-else ladder,
piecewise returns the value for the first true condition.
pw =
piecewise(x < 0, -1, 0 < x, 1)
Add the condition x>5 with the value 1/x to pw by creating a new piecewise expression
with pw as the otherwise value.
pw = piecewise(x>5, 1/x, pw)
pw =
piecewise(5 < x, 1/x, x < 0, -1, 0 < x, 1)
Input Arguments
cond Condition
symbolic condition | symbolic variable
4-1117
4 Functions Alphabetical List
Output Arguments
pw Piecewise expression or function
symbolic expression | symbolic function
More About
Tips
See Also
and | assume | assumeAlso | assumptions | if | in | isAlways | not | or
Introduced in R2016b
4-1118
pinv
pinv
Moore-Penrose inverse (pseudoinverse) of symbolic matrix
Syntax
X = pinv(A)
Description
X = pinv(A) returns the pseudoinverse of A. Pseudoinverse is also called the Moore-
Penrose inverse.
Input Arguments
A
Output Arguments
X
Examples
Compute the pseudoinverse of this matrix. Because these numbers are not symbolic
objects, you get floating-point results.
A = [1 1i 3; 1 3 2];
X = pinv(A)
X =
4-1119
4 Functions Alphabetical List
Now, convert this matrix to a symbolic object, and compute the pseudoinverse.
A = sym([1 1i 3; 1 3 2]);
X = pinv(A)
X =
[ 7/96 + 1i/32, 1/24 - 1i/32]
[ - 7/32 - 5i/96, 5/16 + 7i/96]
[ 7/24 + 1i/16, 1/96 - 3i/32]
isAlways(A*X*A == A)
ans =
23 logical array
1 1 1
1 1 1
isAlways(X*A*X == X)
ans =
32 logical array
1 1
1 1
1 1
isAlways(A*X == (A*X)')
ans =
22 logical array
1 1
1 1
isAlways(X*A == (X*A)')
ans =
33 logical array
1 1 1
1 1 1
4-1120
pinv
1 1 1
syms a
A = [1 a; -a 1];
X = pinv(A)
X =
[ (a*conj(a) + 1)/(a^2*conj(a)^2 + a^2 + conj(a)^2 + 1) -...
(conj(a)*(a - conj(a)))/(a^2*conj(a)^2 + a^2 + conj(a)^2 + 1),
- (a - conj(a))/(a^2*conj(a)^2 + a^2 + conj(a)^2 + 1) -...
(conj(a)*(a*conj(a) + 1))/(a^2*conj(a)^2 + a^2 + conj(a)^2 + 1)]
[ (a - conj(a))/(a^2*conj(a)^2 + a^2 + conj(a)^2 + 1) +...
(conj(a)*(a*conj(a) + 1))/(a^2*conj(a)^2 + a^2 + conj(a)^2 + 1),
(a*conj(a) + 1)/(a^2*conj(a)^2 + a^2 + conj(a)^2 + 1) -...
(conj(a)*(a - conj(a)))/(a^2*conj(a)^2 + a^2 + conj(a)^2 + 1)]
assume(a,'real')
A = [1 a; -a 1];
X = pinv(A)
X =
[ 1/(a^2 + 1), -a/(a^2 + 1)]
[ a/(a^2 + 1), 1/(a^2 + 1)]
syms a clear
More About
Moore-Penrose Pseudoinverse
Tips
Calling pinv for numeric arguments that are not symbolic objects invokes the
MATLAB pinv function.
4-1121
4 Functions Alphabetical List
See Also
inv | linalg::pseudoInverse | pinv | rank | svd
Introduced in R2013a
4-1122
plus, +
plus, +
Symbolic addition
Syntax
A + B
plus(A,B)
Description
A + B adds A and B.
plus(A,B) is equivalent to A + B.
Examples
Add Scalar to Array
plus adds x to each element of the array.
syms x
A = [x sin(x) 3];
A + x
ans =
[ 2*x, x + sin(x), x + 3]
ans =
4-1123
4 Functions Alphabetical List
[ x + 1, x^2]
[ Inf, 1]
ans =
[ x + 1, x^2]
[ Inf, 1]
h(x) =
x^2 + 8*x + 4
f(x) =
2*x^2 + 3*x
Input Arguments
A Input
symbolic variable | symbolic vector | symbolic matrix | symbolic multidimensional array
| symbolic function | symbolic expression
4-1124
plus, +
B Input
symbolic variable | symbolic vector | symbolic matrix | symbolic multidimensional array
| symbolic function | symbolic expression
More About
Tips
All nonscalar arguments must be the same size. If one input argument is nonscalar,
then plus expands the scalar into an array of the same size as the nonscalar
argument, with all elements equal to the scalar.
See Also
ctranspose | ldivide | minus | mldivide | mpower | mrdivide | mtimes | power
| rdivide | times | transpose
4-1125
4 Functions Alphabetical List
pochhammer
Pochhammer symbol
Syntax
pochhammer(x,n)
Description
pochhammer(x,n) returns the Pochhammer Symbol on page 4-1130 (x)n.
Examples
Find Pochhammer Symbol for Numeric and Symbolic Inputs
Find the Pochhammer symbol for the numeric inputs x = 3 at n = 2.
pochhammer(3,2)
ans =
12
Find the Pochhammer symbol for the symbolic input x at n = 3 . The pochhammer
function does not automatically return the expanded form of the expression. Use expand
to force pochhammer to return the form of the expanded expression.
syms x
P = pochhammer(x, 3)
P = expand(P)
P =
pochhammer(x, 3)
P =
x^3 + 3*x^2 + 2*x
4-1126
pochhammer
syms n x
assume(x>0)
assume(n>0)
P = pochhammer(x, n);
P = expand(P)
P =
gamma(n + x)/gamma(x)
syms n x clear
P = expand(pochhammer(x, 4));
P = factor(P)
P =
[ x, x + 3, x + 2, x + 1]
syms n x
diff(pochhammer(x,n),x)
ans =
pochhammer(x, n)*(psi(n + x) - psi(x))
diff(pochhammer(x,n),n,2)
ans =
pochhammer(x, n)*psi(n + x)^2 + pochhammer(x, n)*psi(1, n + x)
4-1127
4 Functions Alphabetical List
syms x
taylor(pochhammer(x,3),x,2)
ans =
26*x + 9*(x - 2)^2 + (x - 2)^3 - 28
syms x
fplot(pochhammer(x,0:4))
axis([-4 4 -4 4])
grid on
legend('n = 0','n = 1','n = 2','n = 3','n = 4','Location','Best')
title('Pochhammer symbol (x)_n for n=0 to n=4')
4-1128
pochhammer
Input Arguments
x Input
number | vector | matrix | multidimensional array | symbolic number | symbolic
variable | symbolic vector | symbolic matrix | symbolic multidimensional array |
symbolic function | symbolic expression
4-1129
4 Functions Alphabetical List
n Input
number | vector | matrix | multidimensional array | symbolic number | symbolic
variable | symbolic vector | symbolic matrix | symbolic multidimensional array |
symbolic function | symbolic expression
More About
Pochhammer Symbol
( )
( x )n = G x + n ,
(
G x )
( x )n = x ( x + 1 ) ...( x + n - 1 )
Algorithms
G (1 - x)
( x )n = ( - 1) n .
G 1 - x - n)
(
4-1130
pochhammer
( x )0 = 1
( x )1 = x
( x )-1 = 1
x -1
(1 ) n = G ( n + 1 )
(2)n = G ( n + 2)
See Also
factorial | gamma
Introduced in R2014b
4-1131
4 Functions Alphabetical List
poles
Poles of expression or function
Syntax
poles(f,var)
P = poles(f,var)
[P,N] = poles(f,var)
[P,N,R] = poles(f,var)
poles(f,var,a,b)
P = poles(f,var,a,b)
[P,N] = poles(f,var,a,b)
[P,N,R] = poles(f,var,a,b)
Description
poles(f,var) finds nonremovable singularities of f. These singularities are called the
poles of f. Here, f is a function of the variable var.
[P,N] = poles(f,var) finds the poles of f and their orders. This syntax assigns the
poles to vector P and their orders to vector N.
[P,N,R] = poles(f,var) finds the poles of f and their orders and residues. This
syntax assigns the poles to vector P, their orders to vector N, and their residues to vector
R.
P = poles(f,var,a,b) finds the poles of f in the interval (a,b) and assigns them to
vector P.
[P,N] = poles(f,var,a,b) finds the poles of f in the interval (a,b) and their orders.
This syntax assigns the poles to vector P and their orders to vector N.
4-1132
poles
[P,N,R] = poles(f,var,a,b) finds the poles of f in the interval (a,b) and their
orders and residues. This syntax assigns the poles to vector P, their orders to vector N,
and their residues to vector R.
Input Arguments
f
var
Symbolic variable.
a,b
Real numbers (including infinities) that specify the search interval for function poles.
Output Arguments
P
Examples
Find the poles of these expressions:
4-1133
4 Functions Alphabetical List
syms x
poles(1/(x - i))
poles(sin(x)/(x - 1))
ans =
1i
ans =
1
Find the poles of this expression. If you do not specify a variable, poles uses the default
variable determined by symvar:
syms x a
poles(1/((x - 1)*(a - 2)))
ans =
1
To find the poles of this expression as a function of variable a, specify a as the second
argument:
syms x a
poles(1/((x - 1)*(a - 2)), a)
ans =
2
Find the poles of the tangent function in the interval (-pi, pi):
syms x
poles(tan(x), x, -pi, pi)
ans =
-pi/2
pi/2
The tangent function has an infinite number of poles. If you do not specify the interval,
poles cannot find all of them. It issues a warning and returns an empty symbolic object:
syms x
poles(tan(x))
4-1134
poles
ans =
Empty sym: 0-by-1
If poles can prove that the expression or function does not have any poles in the
specified interval, it returns an empty symbolic object without issuing a warning:
syms x
poles(tan(x), x, -1, 1)
ans =
Empty sym: 0-by-1
Use two output vectors to find the poles of this expression and their orders. Restrict the
search interval to (-pi, 10*pi):
syms x
[Poles, Orders] = poles(tan(x)/(x - 1)^3, x, -pi, pi)
Poles =
-pi/2
pi/2
1
Orders =
1
1
3
Use three output vectors to find the poles of this expression and their orders and
residues:
syms x a
[Poles, Orders, Residues] = poles(a/x^2/(x - 1), x)
Poles =
1
0
Orders =
1
2
Residues =
a
-a
4-1135
4 Functions Alphabetical List
More About
Tips
If poles cannot find all nonremovable singularities and cannot prove that they do not
exist, it issues a warning and returns an empty symbolic object.
If poles can prove that f has no poles (either in the specified interval (a,b) or in the
complex plane), it returns an empty symbolic object without issuing a warning.
a and b must be real numbers or infinities. If you provide complex numbers, poles
uses an empty interval and returns an empty symbolic object.
See Also
limit | solve | symvar | vpasolve
Introduced in R2012b
4-1136
poly2sym
poly2sym
Create symbolic polynomial from vector of coefficients
Compatibility
poly2sym does not accept character vectors as a second input argument anymore.
Instead, create symbolic variables with syms.
Syntax
p = poly2sym(c)
p = poly2sym(c,var)
Description
p = poly2sym(c) creates the symbolic polynomial expression p from the vector
of coefficients c. The polynomial variable is x. If c = [c1,c2,...,cn], then p =
poly2sym(c) returns c1 xn -1 + c2 xn -2 + ... + cn .
This syntax does not create the symbolic variable x in the MATLAB Workspace.
Examples
syms a b c d
4-1137
4 Functions Alphabetical List
p = poly2sym([a, b, c, d])
p =
a*x^3 + b*x^2 + c*x + d
p =
x^2/2 - x/3 + 1/4
p =
(3*x^2)/4 - x/2 + 1/4
syms a b c d t
p = poly2sym([a, b, c, d], t)
p =
a*t^3 + b*t^2 + c*t + d
p1 = subs(p, t, t^2 + 1)
p2 = subs(p, t, exp(t))
p1 =
d + a*(t^2 + 1)^3 + b*(t^2 + 1)^2 + c*(t^2 + 1)
p2 =
d + c*exp(t) + a*exp(3*t) + b*exp(2*t)
4-1138
poly2sym
Input Arguments
c Polynomial coefficients
numeric vector | symbolic vector
Output Arguments
p Polynomial
symbolic expression
More About
Tips
When you call poly2sym for a numeric vector c, the toolbox converts the numeric
vector to a vector of symbolic numbers using the default (rational) conversion mode of
sym.
See Also
coeffs | sym | sym2poly
4-1139
4 Functions Alphabetical List
polylog
Polylogarithm
Syntax
polylog(n,x)
Description
polylog(n,x) returns the polylogarithm of the order n and the argument x.
Examples
Compute polylogarithms for these numbers. Because these numbers are not symbolic
objects, you get floating-point results.
A =
-0.4726 0.3408 0.7697
Compute polylogarithms for the same numbers converted to symbolic objects. For most
symbolic (exact) numbers, polylog returns unresolved symbolic calls.
symA =
[ polylog(3, -1/2), polylog(4, 1/3), polylog(5, 3/4)]
Use vpa to approximate symbolic results with the required number of digits.
vpa(symA)
4-1140
polylog
ans =
[ -0.47259784465889687461862319312655,...
0.3407911308562507524776409440122,...
0.76973541059975738097269173152535]
syms x
polylog(1,x)
ans =
-log(1 - x)
polylog(0,x)
ans =
-x/(x - 1)
polylog(-1,x)
ans =
x/(x - 1)^2
polylog(-2,x)
ans =
-(x^2 + x)/(x - 1)^3
polylog(-3,x)
ans =
(x^3 + 4*x^2 + x)/(x - 1)^4
polylog(-10,x)
ans =
-(x^10 + 1013*x^9 + 47840*x^8 + 455192*x^7 + ...
1310354*x^6 + 1310354*x^5 + 455192*x^4 +...
4-1141
4 Functions Alphabetical List
If the second argument is 0, then the polylogarithm equals 0 for any integer value of the
first argument. If the second argument is 1, then the polylogarithm is the Riemann zeta
function of the first argument.
syms n
[polylog(n,0), polylog(n,1)]
ans =
[ 0, zeta(n)]
If the second argument is -1, then the polylogarithm has a special value for any integer
value of the first argument except 1.
assume(n ~= 1)
polylog(n,-1)
ans =
zeta(n)*(2^(1 - n) - 1)
ans =
[ pi^4/90, -(15*zeta(5))/16, catalan*1i - pi^2/48]
Plot Polylogarithm
Plot the polylogarithms of the orders from -3 to 1.
syms x
for n = -3:1
fplot(polylog(n,x),[-5 1])
hold on
4-1142
polylog
end
title('Polylogarithm')
hold off
syms n x
diff(polylog(n, x), x)
diff(x*polylog(n, x), x)
4-1143
4 Functions Alphabetical List
ans =
polylog(n - 1, x)/x
ans =
polylog(n, x) + polylog(n - 1, x)
ans =
polylog(n + 1, x)
ans =
x*polylog(n, x)
Input Arguments
n Index of polylogarithm
integer
x Argument of polylogarithm
number | symbolic variable | symbolic expression | symbolic function | vector | matrix
More About
Polylogarithm
For a complex number z of modulus |z| < 1, the polylogarithm of order n is defined as
follows.
zk
Li n ( z ) = n
k= 1 k
4-1144
polylog
This function is extended to the whole complex plane by analytic continuation, with a
branch cut along the real interval [1, ) for n1.
Tips
See Also
dilog | log | log10 | log2 | logint | zeta
Introduced in R2014b
4-1145
4 Functions Alphabetical List
potential
Potential of vector field
Syntax
potential(V,X)
potential(V,X,Y)
Description
potential(V,X) computes the potential of the vector field V with respect to the vector X
in Cartesian coordinates. The vector field V must be a gradient field.
Input Arguments
V
Vector of symbolic variables with respect to which you compute the potential.
Vector of symbolic variables, expressions, or numbers that you want to use as a base
point for the integration. If you use this argument, potential returns P(X) such that
P(Y) = 0. Otherwise, the potential is only defined up to some additive constant.
Examples
Compute the potential of this vector field with respect to the vector [x, y, z]:
4-1146
potential
syms x y z
P = potential([x, y, z*exp(z)], [x y z])
P =
x^2/2 + y^2/2 + exp(z)*(z - 1)
ans =
x
y
z*exp(z)
Compute the potential of this vector field specifying the integration base point as [0 0
0]:
syms x y z
P = potential([x, y, z*exp(z)], [x y z], [0 0 0])
P =
x^2/2 + y^2/2 + exp(z)*(z - 1) + 1
ans =
0
ans =
NaN
More About
Scalar Potential of Gradient Vector Field
4-1147
4 Functions Alphabetical List
The vector field is gradient if and only if the corresponding Jacobian is symmetrical:
vi v j
=
x j
xi
1
P( X ) = ( X- Y ) V(Y + l ( X- Y )) dl
0
Tips
See Also
curl | diff | divergence | gradient | hessian | jacobian | laplacian |
vectorPotential
Introduced in R2012a
4-1148
power, .^
power, .^
Symbolic array power
Syntax
A.^B
power(A,B)
Description
A.^B computes A to the B power and is an elementwise operation.
Examples
Square Each Matrix Element
Create a 2-by-3 matrix.
A = sym('a', [2 3])
A =
[ a1_1, a1_2, a1_3]
[ a2_1, a2_2, a2_3]
ans =
[ a1_1^2, a1_2^2, a1_3^2]
[ a2_1^2, a2_2^2, a2_3^2]
4-1149
4 Functions Alphabetical List
H = sym(hilb(3))
d = diag(sym([1 2 3]))
H =
[ 1, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
d =
[ 1, 0, 0]
[ 0, 2, 0]
[ 0, 0, 3]
Raise the elements of the Hilbert matrix to the powers of the diagonal matrix. The base
and the exponent must be matrices of the same size.
H.^d
ans =
[ 1, 1, 1]
[ 1, 1/9, 1]
[ 1, 1, 1/125]
Input Arguments
A Input
number | symbolic number | symbolic variable | symbolic vector | symbolic matrix |
symbolic multidimensional array | symbolic function | symbolic expression
B Input
number | symbolic number | symbolic variable | symbolic vector | symbolic matrix |
symbolic multidimensional array | symbolic function | symbolic expression
4-1150
power, .^
See Also
ctranspose | ldivide | minus | mldivide | mpower | mrdivide | mtimes | plus
| rdivide | times | transpose
4-1151
4 Functions Alphabetical List
pretty
Prettyprint symbolic expressions
Compatibility
pretty is not recommended. Use Live Scripts instead. Live Scripts provide full math
rendering while pretty uses plain-text formatting. See What Is a Live Script?
Syntax
pretty(X)
Description
pretty(X) prints X in a plain-text format that resembles typeset mathematics. For true
typeset rendering, use Live Scripts instead. See What Is a Live Script?
Examples
The following statements:
A = sym(pascal(2))
B = eig(A)
pretty(B)
return:
A =
[ 1, 1]
[ 1, 2]
B =
3/2 - 5^(1/2)/2
5^(1/2)/2 + 3/2
4-1152
pretty
/ 3 sqrt(5) \
| - - ------- |
| 2 2 |
| |
| sqrt(5) 3 |
| ------- + - |
\ 2 2 /
Solve this equation, and then use pretty to represent the solutions in the format similar
to typeset mathematics:
syms x
s = solve(x^4 + 2*x + 1, x,'MaxDegree',3);
pretty(s)
For better readability, pretty uses abbreviations when representing long expressions:
/ -1 \
| |
| 2 1 |
| #2 - ---- + - |
| 9 #2 3 |
| |
| 1 #2 1 |
| ---- - #1 - -- + - |
| 9 #2 2 3 |
| |
| 1 #2 1 |
| #1 + ---- - -- + - |
\ 9 #2 2 3 /
where
/ 2 \
sqrt(3) | ---- + #2 | 1i
\ 9 #2 /
#1 == ------------------------
2
4-1153
4 Functions Alphabetical List
prevprime
Previous prime number
Syntax
prevprime(n)
Description
prevprime(n) returns the largest prime number smaller than or equal to n. If n is a
vector or matrix, then prevprime acts element-wise on n.
Examples
Find Previous Prime Number
Find the largest prime number smaller than 100. Because prevprime only accepts
symbolic input, wrap 100 with sym.
prevprime(sym(100))
ans =
97
Find the largest prime numbers smaller than 1000, 10000, and 100000 by specifying
the input as a vector.
prevprime(sym([1000 10000 100000]))
ans =
[ 997, 9973, 99991]
4-1154
prevprime
large prime is to use powers of 10, which are accurately represented without requiring
quotation marks. For more information, see Numeric to Symbolic Conversion on page
2-93.
prevprime(10^sym(18))
ans =
999999999999999989
prevprime(sym('823572345728582545'))
ans =
823572345728582543
Input Arguments
n Input
symbolic number | symbolic vector | symbolic matrix
See Also
isprime | nextprime | primes
Introduced in R2016b
4-1155
4 Functions Alphabetical List
psi
Digamma function
Syntax
psi(x)
psi(k,x)
Description
psi(x) computes the digamma function of x.
psi(k,x) computes the polygamma function of x, which is the kth derivative of the
digamma function at x.
Input Arguments
x
Examples
Compute the digamma and polygamma functions for these numbers. Because these
numbers are not symbolic objects, you get the floating-point results.
[psi(1/2) psi(2, 1/2) psi(1.34) psi(1, sin(pi/3))]
4-1156
psi
ans =
-1.9635 -16.8288 -0.1248 2.0372
Compute the digamma and polygamma functions for the numbers converted to symbolic
objects.
[psi(sym(1/2)), psi(1, sym(1/2)), psi(sym(1/4))]
ans =
[ - eulergamma - 2*log(2), pi^2/2, - eulergamma - pi/2 - 3*log(2)]
For some symbolic (exact) numbers, psi returns unresolved symbolic calls.
psi(sym(sqrt(2)))
ans =
psi(2^(1/2))
Compute the derivatives of these expressions containing the digamma and polygamma
functions.
syms x
diff(psi(1, x^3 + 1), x)
diff(psi(sin(x)), x)
ans =
3*x^2*psi(2, x^3 + 1)
ans =
cos(x)*psi(1, sin(x))
ans =
psi(x + 1/2)/2 + log(2) + psi(x)/2 +...
1/(2*x + 1) + 1/(2*x + 2) + 1/(2*x)
ans =
psi(x)/x + psi(x)^2 + psi(x)/(x + 1)
Compute the limits for expressions containing the digamma and polygamma functions.
syms x
4-1157
4 Functions Alphabetical List
limit(x*psi(x), x, 0)
limit(psi(3, x), x, inf)
ans =
-1
ans =
0
ans =
[ -eulergamma, Inf]
Compute the polygamma function for elements of matrix M and vector V. The psi
function acts elementwise on nonscalar inputs.
M = sym([0 inf; 1/3 1/2]);
polyGammaM = [1 3; 2 2];
V = sym([1, inf]);
polyGammaV = [6 6];
psi(polyGammaM,M)
psi(polyGammaV,V)
ans =
[ Inf, 0]
[ - 26*zeta(3) - (4*3^(1/2)*pi^3)/9, -14*zeta(3)]
ans =
[ -720*zeta(7), 0]
Because all elements of polyGammaV have the same value, you can replace polyGammaV
by a scalar of that value. psi expands the scalar into a nonscalar of the same size as V
and computes the result.
V = sym([1, inf]);
psi(6,V)
ans =
[ -720*zeta(7), 0]
4-1158
psi
More About
Digamma Function
The digamma function is the first derivative of the logarithm of the gamma function:
d G ( x)
y (x) = ln G ( x ) =
dx G (x)
Polygamma Function
The polygamma function of the order k is the (k+1)th derivative of the logarithm of the
gamma function:
dk+1 dk
y (k ) ( x ) = ln G ( x ) = y ( x)
k +1
dx dxk
Tips
Calling psi for a number that is not a symbolic object invokes the MATLAB psi
function. This function accepts real nonnegative arguments x. If you want to compute
the polygamma function for a complex number, use sym to convert that number to a
symbolic object, and then call psi for that symbolic object.
psi(0, x) is equivalent to psi(x).
See Also
beta | gamma | nchoosek | factorial
Introduced in R2011b
4-1159
4 Functions Alphabetical List
qr
QR factorization
Syntax
R = qr(A)
[Q,R] = qr(A)
[Q,R,P] = qr(A)
[C,R] = qr(A,B)
[C,R,P] = qr(A,B)
[Q,R,p] = qr(A,'vector')
[C,R,p] = qr(A,B,'vector')
Description
R = qr(A) returns the R part of the QR decomposition A = Q*R. Here, A is an m-by-n
matrix, R is an m-by-n upper triangular matrix, and Q is an m-by-m unitary matrix.
[Q,R] = qr(A) returns an upper triangular matrix R and a unitary matrix Q, such that
A = Q*R.
[C,R] = qr(A,B) returns an upper triangular matrix R and a matrix C, such that C =
Q'*B and A = Q*R. Here, A and B must have the same number of rows.
4-1160
qr
approximated by the floating-point numbers, then this syntax chooses the permutation
matrix P so that abs(diag(R)) is decreasing. Otherwise, it returns P = eye(n). Here,
A and B must have the same number of rows.
C, R, and p represent the solution of the matrix equation A*X = B as X(p,:) = R\C.
___ = qr( ___ ,'econ') returns the "economy size" decomposition. If A is an m-by-n
matrix with m > n, then qr computes only the first n columns of Q and the first n rows of
R. For m <= n, the syntaxes with 'econ' are equivalent to the corresponding syntaxes
without 'econ'.
When you use 'econ', qr always returns the permutation information as a vector p.
You can use 0 instead of 'econ'. For example, [Q,R] = qr(A,0) is equivalent to
[Q,R] = qr(A,'econ').
___ = qr( ___ ,'real') assumes that input arguments and intermediate results
are real, and therefore, suppresses calls to abs and conj. When you use this flag, qr
assumes that all symbolic variables represent real numbers. When using this flag, ensure
that all numeric arguments are real numbers.
Examples
R part of QR Factorization
Compute the R part of the QR decomposition of the 4-by-4 Wilkinson's eigenvalue test
matrix.
A = sym(wilkinson(4))
4-1161
4 Functions Alphabetical List
A =
[ 3/2, 1, 0, 0]
[ 1, 1/2, 1, 0]
[ 0, 1, 1/2, 1]
[ 0, 0, 1, 3/2]
Use the syntax with one output argument to return the R part of the QR decomposition
without returning the Q part:
R = qr(A)
R =
[ 13^(1/2)/2, (4*13^(1/2))/13, (2*13^(1/2))/13, 0]
[ 0, (13^(1/2)*53^(1/2))/26, (10*13^(1/2)*53^(1/2))/689, (2*13^(1/2)*53^(1/2))/53]
[ 0, 0, (53^(1/2)*381^(1/2))/106, (172*53^(1/2)*381^(1/2))/20193]
[ 0, 0, 0, (35*381^(1/2))/762]
A =
[ 1, 1, 1]
[ 1, 2, 3]
[ 1, 3, 6]
Q =
[ 3^(1/2)/3, -2^(1/2)/2, 6^(1/2)/6]
[ 3^(1/2)/3, 0, -6^(1/2)/3]
[ 3^(1/2)/3, 2^(1/2)/2, 6^(1/2)/6]
R =
[ 3^(1/2), 2*3^(1/2), (10*3^(1/2))/3]
[ 0, 2^(1/2), (5*2^(1/2))/2]
[ 0, 0, 6^(1/2)/6]
4-1162
qr
ans =
33 logical array
1 1 1
1 1 1
1 1 1
Permutation Information
Using permutations helps increase numerical stability of the QR factorization for
floating-point matrices. The qr function returns permutation information either as a
matrix or as a vector.
Set the number of significant decimal digits, used for variable-precision arithmetic, to 10.
Approximate the 3-by-3 symbolic Hilbert matrix by floating-point numbers:
previoussetting = digits(10);
A = vpa(hilb(3))
A =
[ 1.0, 0.5, 0.3333333333]
[ 0.5, 0.3333333333, 0.25]
[ 0.3333333333, 0.25, 0.2]
[Q,R] = qr(A)
Q =
[ 0.8571428571, -0.5016049166, 0.1170411472]
[ 0.4285714286, 0.5684855721, -0.7022468832]
[ 0.2857142857, 0.6520863915, 0.7022468832]
R =
[ 1.166666667, 0.6428571429, 0.45]
[ 0, 0.1017143303, 0.1053370325]
[ 0, 0, 0.003901371573]
Compute the difference between A and Q*R. The computed Q and R matrices do not
strictly satisfy the equality A*P = Q*R because of the round-off errors.
A - Q*R
ans =
[ -1.387778781e-16, -3.989863995e-16, -2.064320936e-16]
4-1163
4 Functions Alphabetical List
[Q,R,P] = qr(A)
Q =
[ 0.8571428571, -0.4969293466, -0.1355261854]
[ 0.4285714286, 0.5421047417, 0.7228063223]
[ 0.2857142857, 0.6776309272, -0.6776309272]
R =
[ 1.166666667, 0.45, 0.6428571429]
[ 0, 0.1054092553, 0.1016446391]
[ 0, 0, 0.003764616262]
P =
1 0 0
0 0 1
0 1 0
Check the equality A*P = Q*R again. QR factorization with permutations results in
smaller round-off errors.
A*P - Q*R
ans =
[ -3.469446952e-18, -4.33680869e-18, -6.938893904e-18]
[ 0, -8.67361738e-19, -1.734723476e-18]
[ 0, -4.33680869e-19, -1.734723476e-18]
Now, return the permutation information as a vector by using the 'vector' argument:
[Q,R,p] = qr(A,'vector')
Q =
[ 0.8571428571, -0.4969293466, -0.1355261854]
[ 0.4285714286, 0.5421047417, 0.7228063223]
[ 0.2857142857, 0.6776309272, -0.6776309272]
R =
[ 1.166666667, 0.45, 0.6428571429]
[ 0, 0.1054092553, 0.1016446391]
[ 0, 0, 0.003764616262]
4-1164
qr
p =
1 3 2
A(:,p) - Q*R
ans =
[ -3.469446952e-18, -4.33680869e-18, -6.938893904e-18]
[ 0, -8.67361738e-19, -1.734723476e-18]
[ 0, -4.33680869e-19, -1.734723476e-18]
A = sym(hilb(3));
[Q,R] = qr(A);
A - Q*R
ans =
[ 0, 0, 0]
[ 0, 0, 0]
[ 0, 0, 0]
digits(previoussetting)
Suppose you need to solve the system of equations A*X = b, where A and b are the
following matrix and vector:
A = sym(invhilb(5))
b = sym([1:5]')
A =
[ 25, -300, 1050, -1400, 630]
[ -300, 4800, -18900, 26880, -12600]
[ 1050, -18900, 79380, -117600, 56700]
[ -1400, 26880, -117600, 179200, -88200]
[ 630, -12600, 56700, -88200, 44100]
b =
4-1165
4 Functions Alphabetical List
1
2
3
4
5
[C,R] = qr(A,b);
X = R\C
X =
5
71/20
197/70
657/280
1271/630
isAlways(A*X == b)
ans =
51 logical array
1
1
1
1
1
Suppose you need to solve the system of equations A*X = b, where A and b are the
following matrix and vector:
previoussetting = digits(10);
4-1166
qr
[C,R,P] = qr(A,b)
C =
-2.110579412
-0.2132007164
0.7071067812
R =
[ 3.31662479, 0.3015113446, -1.507556723]
[ 0, 1.705605731, -1.492405014]
[ 0, 0, 0.7071067812]
P =
0 0 1
1 0 0
0 1 0
X = P*(R\C)
X =
1.0
-0.25
0.75
[C,R,p] = qr(A,b,'vector')
C =
-2.110579412
-0.2132007164
0.7071067812
R =
[ 3.31662479, 0.3015113446, -1.507556723]
[ 0, 1.705605731, -1.492405014]
[ 0, 0, 0.7071067812]
p =
2 3 1
4-1167
4 Functions Alphabetical List
X(p,:) = R\C
X =
1.0
-0.25
0.75
Create a matrix that consists of the first two columns of the 4-by-4 Pascal matrix:
A = sym(pascal(4));
A = A(:,1:2)
A =
[ 1, 1]
[ 1, 2]
[ 1, 3]
[ 1, 4]
Q =
[ 1/2, -(3*5^(1/2))/10, (3^(1/2)*10^(1/2))/10, 0]
[ 1/2, -5^(1/2)/10, -(2*3^(1/2)*10^(1/2))/15, 6^(1/2)/6]
[ 1/2, 5^(1/2)/10, -(3^(1/2)*10^(1/2))/30, -6^(1/2)/3]
[ 1/2, (3*5^(1/2))/10, (3^(1/2)*10^(1/2))/15, 6^(1/2)/6]
R =
[ 2, 5]
[ 0, 5^(1/2)]
[ 0, 0]
[ 0, 0]
Now, compute the economy size QR decomposition for this matrix. Because the number
of rows exceeds the number of columns, qr computes only the first 2 columns of Q and the
first 2 rows of R.
4-1168
qr
[Q,R] = qr(A,'econ')
Q =
[ 1/2, -(3*5^(1/2))/10]
[ 1/2, -5^(1/2)/10]
[ 1/2, 5^(1/2)/10]
[ 1/2, (3*5^(1/2))/10]
R =
[ 2, 5]
[ 0, 5^(1/2)]
syms x
A = [1 2; 3 x]
A =
[ 1, 2]
[ 3, x]
[Q,R] = qr(A)
Q =
[ 10^(1/2)/10, -((3*x)/10 - 9/5)/(abs(x/10 - 3/5)^2...
+ abs((3*x)/10 - 9/5)^2)^(1/2)]
[ (3*10^(1/2))/10, (x/10 - 3/5)/(abs(x/10 - 3/5)^2...
+ abs((3*x)/10 - 9/5)^2)^(1/2)]
R =
[ 10^(1/2), (10^(1/2)*(3*x + 2))/10]
[ 0, (abs(x/10 - 3/5)^2 + abs((3*x)/10 - 9/5)^2)^(1/2)]
When you use 'real', qr assumes that all symbolic variables represent real numbers,
and can return shorter results:
[Q,R] = qr(A,'real')
4-1169
4 Functions Alphabetical List
Q =
[ 10^(1/2)/10, -((3*x)/10 - 9/5)/(x^2/10 - (6*x)/5...
+ 18/5)^(1/2)]
[ (3*10^(1/2))/10, (x/10 - 3/5)/(x^2/10 - (6*x)/5...
+ 18/5)^(1/2)]
R =
[ 10^(1/2), (10^(1/2)*(3*x + 2))/10]
[ 0, (x^2/10 - (6*x)/5 + 18/5)^(1/2)]
Input Arguments
A Input matrix
m-by-n symbolic matrix
B Input
symbolic vector | symbolic matrix
Input, specified as a symbolic vector or matrix. The number of rows in B must be the
same as the number of rows in A.
Output Arguments
R R part of the QR decomposition
m-by-n upper triangular symbolic matrix
P Permutation information
matrix of double-precision values
4-1170
qr
p Permutation information
vector of double-precision values
More About
QR Factorization of Matrix
Tips
See Also
chol | eig | lu | svd
Introduced in R2014a
4-1171
4 Functions Alphabetical List
quorem
Quotient and remainder
Syntax
[Q,R] = quorem(A,B,var)
[Q,R] = quorem(A,B)
Description
[Q,R] = quorem(A,B,var) divides A by B and returns the quotient Q and remainder
R of the division, such that A = Q*B + R. This syntax regards A and B as polynomials in
the variable var.
If A and B are matrices, quorem performs elements-wise division, using var are a
variable. It returns the quotient Q and remainder R of the division, such that A = Q.*B
+ R.
If both symvar(A,1) and symvar(B,1) are empty, then A and B must both be integers
or matrices with integer elements. In this case, quorem(A,B) returns symbolic integers
Q and R, such that A = Q*B + R. If A and B are matrices, then Q and R are symbolic
matrices with integer elements, such that A = Q.*B + R, and each element of R is
smaller in absolute value than the corresponding element of B.
Examples
4-1172
quorem
syms x y
p1 = x^3*y^4 - 2*x*y + 5*x + 1;
p2 = x*y;
[q, r] = quorem(p1, p2, y)
q =
x^2*y^3 - 2
r =
5*x + 1
syms x
p = x^3 - 2*x + 5;
[q, r] = quorem(x^5, p)
q =
x^2 + 2
r =
- 5*x^2 + 4*x - 10
Divide Integers
Compute the quotient and remainder of the division of these integers:
q =
101
r =
515
Input Arguments
A Dividend (numerator)
symbolic integer | polynomial | symbolic vector | symbolic matrix
4-1173
4 Functions Alphabetical List
B Divisor (denominator)
symbolic integer | polynomial | symbolic vector | symbolic matrix
Output Arguments
Q Quotient of the division
symbolic integer | symbolic expression | symbolic vector | symbolic matrix
See Also
deconv | mod
4-1174
rank
rank
Find rank of symbolic matrix
Syntax
rank(A)
Description
rank(A) returns the rank of symbolic matrix A.
Examples
ans =
2
Find the rank of the Hilbert matrix of order 15 numerically. Then convert the numeric
matrix to a symbolic matrix using sym and find the rank symbolically.
H = hilb(15);
rank(H)
rank(sym(H))
4-1175
4 Functions Alphabetical List
ans =
12
ans =
15
The symbolic calculation returns the correct rank of 15. The numeric calculation returns
an incorrect rank of 12 due to round-off errors.
1 - sin 2 ( x ) cos2 ( x )
A= .
1 1
syms x
A = [1-sin(x) cos(x); cos(x) 1+sin(x)];
rank(A)
ans =
2
rank returns an incorrect result because the outputs of intermediate steps are not
simplified. While there is no fail-safe workaround, you can simplify symbolic expressions
by using numeric substitution and evaluating the substitution using vpa.
Find the correct rank by substituting x with a number and evaluating the result using
vpa.
rank(vpa(subs(A,x,1)))
ans =
1
However, even after numeric substitution, rank can return incorrect results due to
round-off errors.
4-1176
rank
Input Arguments
A Input
number | vector | matrix | symbolic number | symbolic vector | symbolic matrix
See Also
eig | null | rref | size
4-1177
4 Functions Alphabetical List
rdivide, ./
Symbolic array right division
Syntax
A./B
rdivide(A,B)
Description
A./B divides A by B.
Examples
B = sym('b', [2 3])
B =
[ b1_1, b1_2, b1_3]
[ b2_1, b2_2, b2_3]
syms a
sin(a)./B
ans =
[ sin(a)/b1_1, sin(a)/b1_2, sin(a)/b1_3]
[ sin(a)/b2_1, sin(a)/b2_2, sin(a)/b2_3]
4-1178
rdivide, ./
H =
[ 1, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
d =
[ 1, 0, 0]
[ 0, 2, 0]
[ 0, 0, 3]
Divide d by H by using the elementwise right division operator .\. This operator divides
each element of the first matrix by the corresponding element of the second matrix. The
dimensions of the matrices must be the same.
d./H
ans =
[ 1, 0, 0]
[ 0, 6, 0]
[ 0, 0, 15]
f1(x) =
(x^2 + 5*x + 6)/x^2
Input Arguments
A Input
symbolic variable | symbolic vector | symbolic matrix | symbolic multidimensional array
| symbolic function | symbolic expression
4-1179
4 Functions Alphabetical List
B Input
symbolic variable | symbolic vector | symbolic matrix | symbolic multidimensional array
| symbolic function | symbolic expression
See Also
ctranspose | ldivide | minus | mldivide | mpower | mrdivide | mtimes | plus
| power | times | transpose
4-1180
read
read
Read MuPAD program file into symbolic engine
Syntax
read(symengine,filename)
Description
read(symengine,filename) reads the MuPAD program file filename into the
symbolic engine. Reading a program file means finding and executing it.
Input Arguments
filename
The name of a MuPAD program file that you want to read. This file must have the
extension .mu or .gz.
Examples
Suppose you wrote the MuPAD procedure myProc and saved it in the file
myProcedure.mu.
4-1181
4 Functions Alphabetical List
Before you can call this procedure at the MATLAB Command Window, you must read the
file myProcedure.mu into the symbolic engine. To read a program file into the symbolic
engine, use read:
read(symengine, 'myProcedure.mu')
If the file is not on the MATLAB path, specify the full path to this file. For example, if
myProcedure.mu is in the MuPAD folder on disk C, enter:
read(symengine, 'C:/MuPAD/myProcedure.mu')
Now you can access the procedure myProc using evalin or feval. For example,
compute the factorial of 10:
ans =
3628800
4-1182
read
Alternatives
You also can use feval to call the MuPAD read function. The read function available
from the MATLAB Command Window is equivalent to calling the MuPAD read function
with the Plain option. It ignores any MuPAD aliases defined in the program file:
If your program file contains aliases or uses the aliases predefined by MATLAB, do not
use Plain:
More About
Tips
If you do not specify the file extension, read searches for the file filename.mu.
If filename is a GNU zip file with the extension .gz, read uncompresses it upon
reading.
filename can include full or relative path information. If filename does not have a
path component, read uses the MATLAB function which to search for the file on the
MATLAB path.
read ignores any MuPAD aliases defined in the program file. If your program file
contains aliases or uses the aliases predefined by MATLAB, see Alternatives on
page 4-1183.
See Also
evalin | feval | symengine
Introduced in R2011b
4-1183
4 Functions Alphabetical List
real
Real part of complex number
Syntax
real(z)
real(A)
Description
real(z) returns the real part of z.
Input Arguments
z
Examples
Find the real parts of these numbers. Because these numbers are not symbolic objects,
you get floating-point results.
[real(2 + 3/2*i), real(sin(5*i)), real(2*exp(1 + i))]
ans =
2.0000 0 2.9374
4-1184
real
ans =
[ 2, 2/5, 0]
real(2*exp(1 + sym(i)))
ans =
2*cos(1)*exp(1)
In general, real cannot extract the entire real parts from symbolic expressions
containing variables. However, real can rewrite and sometimes simplify the input
expression:
syms a x y
real(a + 2)
real(x + y*i)
ans =
real(a) + 2
ans =
real(x) - imag(y)
If you assign numeric values to these variables or specify that these variables are real,
real can extract the real part of the expression:
syms a
a = 5 + 3*i;
real(a + 2)
ans =
7
syms x y real
real(x + y*i)
ans =
x
syms x y clear
4-1185
4 Functions Alphabetical List
syms x
A = [-1 + sym(i), sinh(x); exp(10 + sym(7)*i), exp(sym(pi)*i)];
real(A)
ans =
[ -1, real(sinh(x))]
[ cos(7)*exp(10), -1]
Alternatives
You can compute the real part of z via the conjugate: real(z)= (z + conj(z))/2.
More About
Tips
Calling real for a number that is not a symbolic object invokes the MATLAB real
function.
See Also
conj | imag | in | sign | signIm
4-1186
rectangularPulse
rectangularPulse
Rectangular pulse function
Syntax
rectangularPulse(a,b,x)
rectangularPulse(x)
Description
rectangularPulse(a,b,x) returns the rectangular pulse function.
Input Arguments
a
Default: -1/2
Default: 1/2
4-1187
4 Functions Alphabetical List
Examples
Find Rectangular Pulse Function
Compute the rectangular pulse function for these numbers. Because these numbers are
not symbolic objects, you get floating-point results:
[rectangularPulse(-1, 1, -2)
rectangularPulse(-1, 1, -1)
rectangularPulse(-1, 1, 0)
rectangularPulse(-1, 1, 1)
rectangularPulse(-1, 1, 2)]
ans =
0
0.5000
1.0000
0.5000
0
Compute the rectangular pulse function for the numbers converted to symbolic objects:
[rectangularPulse(sym(-1), 1, -2)
rectangularPulse(-1, sym(1), -1)
rectangularPulse(-1, 1, sym(0))
rectangularPulse(sym(-1), 1, 1)
rectangularPulse(sym(-1), 1, 2)]
ans =
0
1/2
1
1/2
0
4-1188
rectangularPulse
ans =
1/2
ans =
1/2
ans =
0
ans =
rectangularPulse(-1/2, 1/2, x)
[rectangularPulse(sym(-1))
rectangularPulse(sym(-1/2))
rectangularPulse(sym(0))
rectangularPulse(sym(1/2))
rectangularPulse(sym(1))]
ans =
0
1/2
1
1/2
0
4-1189
4 Functions Alphabetical List
syms x
rectangularPulse(-inf, 0, x)
rectangularPulse(0, inf, x)
rectangularPulse(-inf, inf, x)
ans =
heaviside(-x)
4-1190
rectangularPulse
ans =
heaviside(x)
ans =
1
More About
Rectangular Pulse Function
If a < x < b, then the rectangular pulse function equals 1. If x = a or x = b and a <>
b, then the rectangular pulse function equals 1/2. Otherwise, it equals 0.
The rectangular pulse function is also called the rectangle function, box function, -
function, or gate function.
Tips
See Also
dirac | heaviside | triangularPulse
Introduced in R2012b
4-1191
4 Functions Alphabetical List
reduceDAEIndex
Convert system of first-order differential algebraic equations to equivalent system of
differential index 1
Syntax
[newEqs,newVars] = reduceDAEIndex(eqs,vars)
[newEqs,newVars,R] = reduceDAEIndex(eqs,vars)
[newEqs,newVars,R,oldIndex] = reduceDAEIndex(eqs,vars)
Description
[newEqs,newVars] = reduceDAEIndex(eqs,vars) converts a high-index system
of first-order differential algebraic equations eqs to an equivalent system newEqs of
differential index 1.
reduceDAEIndex keeps the original equations and variables and introduces new
variables and equations. After conversion, reduceDAEIndex checks the differential
index of the new system by calling isLowIndexDAE. If the index of newEqs is 2 or
higher, then reduceDAEIndex issues a warning.
Examples
4-1192
reduceDAEIndex
Create the following system of two differential algebraic equations. Here, the symbolic
functions x(t), y(t), and z(t) represent the state variables of the system. Specify
the equations and variables as two symbolic vectors: equations as a vector of symbolic
equations, and variables as a vector of symbolic function calls.
Use isLowIndexDAE to check the differential index of the system. For this system,
isLowIndexDAE returns 0 (false). This means that the differential index of the system
is 2 or higher.
isLowIndexDAE(eqs, vars)
ans =
logical
0
Use reduceDAEIndex to rewrite the system so that the differential index is 1. The new
system has one additional state variable, Dyt(t).
newEqs =
diff(x(t), t) - z(t) - x(t)
Dyt(t) - f(t)
x(t) - y(t)
diff(x(t), t) - Dyt(t)
newVars =
x(t)
y(t)
z(t)
Dyt(t)
isLowIndexDAE(newEqs, newVars)
ans =
logical
1
4-1193
4 Functions Alphabetical List
Create the following system of two second-order DAEs. Here, x(t), y(t), and F(t) are
the state variables of the system. Specify the equations and variables as two symbolic
vectors: equations as a vector of symbolic equations, and variables as a vector of symbolic
function calls.
syms t x(t) y(t) F(t) r g
eqs = [diff(x(t), t, t) == -F(t)*x(t),...
diff(y(t), t, t) == -F(t)*y(t) - g,...
x(t)^2 + y(t)^2 == r^2 ];
vars = [x(t), y(t), F(t)];
Rewrite this system so that all equations become first-order differential equations. The
reduceDifferentialOrder function replaces the second-order DAE by two first-order
expressions by introducing the new variables Dxt(t) and Dyt(t). It also replaces the
first-order equations by symbolic expressions.
[eqs, vars] = reduceDifferentialOrder(eqs, vars)
eqs =
diff(Dxt(t), t) + F(t)*x(t)
diff(Dyt(t), t) + g + F(t)*y(t)
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)
F(t)
Dxt(t)
Dyt(t)
eqs =
Dxtt(t) + F(t)*x(t)
4-1194
reduceDAEIndex
g + Dytt(t) + F(t)*y(t)
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)
vars =
x(t)
y(t)
F(t)
Dxt(t)
Dyt(t)
Dytt(t)
Dxtt(t)
Dxt1(t)
Dyt1(t)
Dxt1t(t)
R =
[ Dytt(t), diff(Dyt(t), t)]
[ Dxtt(t), diff(Dxt(t), t)]
[ Dxt1(t), diff(x(t), t)]
[ Dyt1(t), diff(y(t), t)]
[ Dxt1t(t), diff(x(t), t, t)]
originalIndex =
3
eqs =
Dxtt(t) + F(t)*x(t)
g + Dytt(t) + F(t)*y(t)
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)
4-1195
4 Functions Alphabetical List
vars =
x(t)
y(t)
F(t)
Dxt(t)
Dyt(t)
Dytt(t)
Dxtt(t)
Input Arguments
eqs System of first-order DAEs
vector of symbolic equations | vector of symbolic expressions
State variables, specified as a vector of symbolic functions or function calls, such as x(t).
Example: [x(t),y(t)]
Output Arguments
newEqs System of first-order DAEs of differential index 1
column vector of symbolic expressions
Extended set of variables, returned as a column vector of symbolic function calls. This
vector includes the original state variables vars followed by the generated variables that
replace the second- and higher-order derivatives in eqs.
4-1196
reduceDAEIndex
Relations between new and original variables, returned as a symbolic matrix with two
columns. The first column contains the new variables. The second column contains their
definitions as derivatives of the original variables vars.
More About
Algorithms
See Also
daeFunction | decic | findDecoupledBlocks | incidenceMatrix |
isLowIndexDAE | massMatrixForm | odeFunction | reduceDAEToODE |
reduceDifferentialOrder | reduceRedundancies
Introduced in R2014b
4-1197
4 Functions Alphabetical List
reduceDAEToODE
Convert system of first-order semilinear differential algebraic equations to equivalent
system of differential index 0
Syntax
newEqs = reduceDAEToODE(eqs,vars)
[newEqs,constraintEqs] = reduceDAEToODE(eqs,vars)
[newEqs,constraintEqs,oldIndex] = reduceDAEToODE(eqs,vars)
Description
newEqs = reduceDAEToODE(eqs,vars) converts a high-index system of first-order
semilinear algebraic equations eqs to an equivalent system of ordinary differential
equations, newEqs. The differential index of the new system is 0, that is, the Jacobian of
newEqs with respect to the derivatives of the variables in vars is invertible.
Examples
Create the following system of two differential algebraic equations. Here, the symbolic
functions x(t), y(t), and z(t) represent the state variables of the system. Specify
the equations and variables as two symbolic vectors: equations as a vector of symbolic
equations, and variables as a vector of symbolic function calls.
4-1198
reduceDAEToODE
newEqs =
x(t)*diff(y(t), t) - y(t) + diff(x(t), t)
diff(x(t), t)*(cos(x(t)) - y(t)) - x(t)*diff(y(t), t)
z(t) - 2*x(t)*diff(x(t), t) - 2*y(t)*diff(y(t), t) + t*diff(z(t), t)
Create the system of differential algebraic equations. Here, the functions x1(t), x2(t),
and x3(t) represent the state variables of the system. The system also contains the
functions q1(t), q2(t), and q3(t). These functions do not represent state variables.
Specify the equations and variables as two symbolic vectors: equations as a vector of
symbolic equations, and variables as a vector of symbolic function calls.
Use isLowIndexDAE to check the differential index of the system. For this system,
isLowIndexDAE returns 0 (false). This means that the differential index of the system
is 2 or higher.
isLowIndexDAE(eqs, vars)
ans =
logical
0
4-1199
4 Functions Alphabetical List
Use reduceDAEIndex as your first attempt to rewrite the system so that the differential
index is 1. For this system, reduceDAEIndex issues a warning because it cannot reduce
the differential index of the system to 0 or 1.
[newEqs, newVars] = reduceDAEIndex(eqs, vars)
newEqs =
x1(t) - q1(t) + diff(x2(t), t)
Dx3t(t) - q2(t) + 2*x2(t) + t*(q1(t) - x1(t))
q3(t) - x3(t) - t*x2(t)
diff(q3(t), t) - x2(t) - t*diff(x2(t), t) - Dx3t(t)
newVars =
x1(t)
x2(t)
x3(t)
Dx3t(t)
newEqs =
x1(t) - q1(t) + diff(x2(t), t)
2*x2(t) - q2(t) + t*q1(t) - t*x1(t) + diff(x3(t), t)
diff(x1(t), t) - diff(q1(t), t) + diff(q2(t), t, t) - diff(q3(t), t, t, t)
constraintEqs =
x1(t) - q1(t) + diff(q2(t), t) - diff(q3(t), t, t)
x3(t) - q3(t) + t*x2(t)
x2(t) - q2(t) + diff(q3(t), t)
Use the syntax with three output arguments to return the new equations, constraint
equations, and the differential index of the original system, eqs.
[newEqs, constraintEqs, oldIndex] = reduceDAEToODE(eqs, vars)
newEqs =
x1(t) - q1(t) + diff(x2(t), t)
2*x2(t) - q2(t) + t*q1(t) - t*x1(t) + diff(x3(t), t)
4-1200
reduceDAEToODE
constraintEqs =
x1(t) - q1(t) + diff(q2(t), t) - diff(q3(t), t, t)
x3(t) - q3(t) + t*x2(t)
x2(t) - q2(t) + diff(q3(t), t)
oldIndex =
3
Input Arguments
eqs System of first-order semilinear DAEs
vector of symbolic equations | vector of symbolic expressions
State variables, specified as a vector of symbolic functions or function calls, such as x(t).
Example: [x(t),y(t)] or [x(t);y(t)]
Output Arguments
newEqs System of implicit ordinary differential equations
column vector of symbolic expressions
4-1201
4 Functions Alphabetical List
in newEqs, meaning that the time derivative of each constraint vanishes modulo the
equations in newEqs.
You can use these equations to determine consistent initial conditions for the DAE
system.
More About
Algorithms
See Also
daeFunction | decic | findDecoupledBlocks | incidenceMatrix |
isLowIndexDAE | massMatrixForm | odeFunction | reduceDAEIndex |
reduceDifferentialOrder | reduceRedundancies
Introduced in R2014b
4-1202
reduceDifferentialOrder
reduceDifferentialOrder
Reduce system of higher-order differential equations to equivalent system of first-order
differential equations
Syntax
[newEqs,newVars] = reduceDifferentialOrder(eqs,vars)
[newEqs,newVars,R] = reduceDifferentialOrder(eqs,vars)
Description
[newEqs,newVars] = reduceDifferentialOrder(eqs,vars) rewrites a system of
higher-order differential equations eqs as a system of first-order differential equations
newEqs by substituting derivatives in eqs with new variables. Here, newVars consists of
the original variables vars augmented with these new variables.
Examples
4-1203
4 Functions Alphabetical List
diff(y(t), t) == c2*x(t)];
vars = [x(t), y(t)];
Rewrite this system so that all equations become first-order differential equations. The
reduceDifferentialOrder function replaces the higher-order DAE by first-order
expressions by introducing the new variable Dxt(t). It also represents all equations as
symbolic expressions.
newEqs =
sin(x(t)) + y(t) + diff(Dxt(t), t) - c1*cos(t)
diff(y(t), t) - c2*x(t)
Dxt(t) - diff(x(t), t)
newVars =
x(t)
y(t)
Dxt(t)
4-1204
reduceDifferentialOrder
newEqs =
diff(Dxt(t), t) - diff(f(t), t, t, t)
diff(Dytt(t), t) - diff(f(t), t, t)
Dxt(t) - diff(x(t), t)
Dyt(t) - diff(y(t), t)
Dytt(t) - diff(Dyt(t), t)
newVars =
x(t)
y(t)
Dxt(t)
Dyt(t)
Dytt(t)
R =
[ Dxt(t), diff(x(t), t)]
[ Dyt(t), diff(y(t), t)]
[ Dytt(t), diff(y(t), t, t)]
Input Arguments
eqs System containing higher-order differential equations
vector of symbolic equations | vector of symbolic expressions
Output Arguments
newEqs System of first-order differential equations
column vector of symbolic expressions
4-1205
4 Functions Alphabetical List
Extended set of variables, returned as a column vector of symbolic function calls. This
vector includes the original state variables vars followed by the generated variables that
replace the higher-order derivatives in eqs.
Relations between new and original variables, returned as a symbolic matrix with two
columns. The first column contains the new variables newVars. The second column
contains their definition as derivatives of the original variables vars.
See Also
daeFunction | decic | findDecoupledBlocks | incidenceMatrix |
isLowIndexDAE | massMatrixForm | odeFunction | reduceDAEIndex |
reduceDAEToODE | reduceRedundancies
Introduced in R2014b
4-1206
reduceRedundancies
reduceRedundancies
Simplify system of first-order differential algebraic equations by eliminating redundant
equations and variables
Syntax
[newEqs,newVars] = reduceRedundancies(eqs,vars)
[newEqs,newVars,R] = reduceRedundancies(eqs,vars)
Description
[newEqs,newVars] = reduceRedundancies(eqs,vars) eliminates simple
equations from the system of first-order differential algebraic equations eqs. It returns
a column vector newEqs of symbolic expressions and a column vector newVars of those
variables that remain in the new DAE system newEqs. The expressions in newEqs
represent equations with a zero right side.
Examples
Create the following system of five differential algebraic equations in four state variables
x1(t), x2(t), x3(t), and x4(t). The system also contains symbolic parameters a1, a2,
a3, a4, b, c, and the function f(t) that is not a state variable.
4-1207
4 Functions Alphabetical List
newEqs =
a1*diff(x1(t), t) + (a2*diff(x1(t), t))/2 - b*f(t)
(a3*diff(x1(t), t))/2 + a4*diff(x3(t), t) - c*f(t)
newVars =
x1(t)
x3(t)
Create the following system of five differential algebraic equations in four state variables
x1(t), x2(t), x3(t), and x4(t). The system also contains symbolic parameters a1, a2,
a3, a4, b, c, and the function f(t) that is not a state variable.
newEqs =
a1*diff(x1(t), t) + (a2*diff(x1(t), t))/2 - b*f(t)
(a3*diff(x1(t), t))/2 + a4*diff(x3(t), t) - c*f(t)
newVars =
x1(t)
4-1208
reduceRedundancies
x3(t)
R =
struct with fields:
Here, R is a structure array with four fields. The solvedEquations field contains
equations that reduceRedundancies used to replace those state variables from vars
that do not appear in newEqs.
R.solvedEquations
ans =
x1(t) - 2*x2(t)
x4(t) - f(t)
The constantVariables field contains a matrix with the following two columns. The
first column contains those state variables from vars that reduceRedundancies
replaced by constant values. The second column contains the corresponding constant
values.
R.constantVariables
ans =
[ x4(t), f(t)]
The replacedVariables field contains a matrix with the following two columns. The
first column contains those state variables from vars that reduceRedundancies
replaced by expressions in terms of other variables. The second column contains the
corresponding values of the eliminated variables.
R.replacedVariables
ans =
[ x2(t), x1(t)/2]
The otherEquations field contains those equations from eqs that do not contain any of
the state variables vars.
R.otherEquations
4-1209
4 Functions Alphabetical List
ans =
f(t) - sin(t)
Input Arguments
eqs System of first-order DAEs
vector of symbolic equations | vector of symbolic expressions
State variables, specified as a vector of symbolic functions or function calls, such as x(t).
Example: [x(t),y(t)]
Output Arguments
newEqs System of first-order DAEs
column vector of symbolic expressions
4-1210
reduceRedundancies
and replaced by constant values. The second column contains the corresponding
constant values.
R.replacedVariables to return a matrix with the following two columns. The
first column contains those original state variables of the vector vars that were
eliminated and replaced in terms of other variables. The second column contains the
corresponding values of the eliminated variables.
R.otherEquations to return a column vector containing all original equations eqs
that do not contain any of the input variables vars.
See Also
daeFunction | decic | findDecoupledBlocks | incidenceMatrix |
isLowIndexDAE | massMatrixForm | odeFunction | reduceDAEIndex |
reduceDAEToODE | reduceDifferentialOrder
Introduced in R2014b
4-1211
4 Functions Alphabetical List
rem
Remainder after division
Syntax
rem(a,b)
Description
rem(a,b) finds the remainder after division. If b <> 0, then rem(a,b) = a -
fix(a/b)*b. If b = 0 or b = Inf or b = -Inf, then rem returns NaN.
The rem function does not support complex numbers: all values must be real numbers.
Examples
ans =
[ 3, 3, -3, -3]
4-1212
rem
ans =
[ 7/3, 1/2, 9/2]
Find the remainder after division for the elements of these two matrices.
A = sym([27, 28; 29, 30]);
B = sym([2, 3; 4, 5]);
rem(A,B)
ans =
[ 1, 1]
[ 1, 0]
Find the remainder after division for the elements of matrix A and the value 9. Here, rem
expands 9 into the 2-by-2 matrix with all elements equal to 9.
rem(A,9)
ans =
[ 0, 1]
[ 2, 3]
Input Arguments
a Dividend (numerator)
number | symbolic number | vector | matrix
b Divisor (denominator)
number | symbolic number | vector | matrix
4-1213
4 Functions Alphabetical List
More About
Tips
Calling rem for numbers that are not symbolic objects invokes the MATLAB rem
function.
All nonscalar arguments must be the same size. If one input arguments is nonscalar,
then mod expands the scalar into a vector or matrix of the same size as the nonscalar
argument, with all elements equal to the corresponding scalar.
See Also
mod | quorem
4-1214
reset
reset
Close MuPAD engine
Syntax
reset(symengine)
Description
reset(symengine) closes the MuPAD engine associated with the MATLAB
workspace, and resets all its assumptions. Immediately before or after executing
reset(symengine) you should clear all symbolic objects in the MATLAB workspace.
See Also
symengine
Introduced in R2008b
4-1215
4 Functions Alphabetical List
reshape
Reshape symbolic array
Syntax
reshape(A,n1,n2)
reshape(A,n1,...,nM)
reshape(A,...,[],...)
reshape(A,sz)
Description
reshape(A,n1,n2) returns the n1-by-n2 matrix, which has the same elements as
A. The elements are taken column-wise from A to fill in the elements of the n1-by-n2
matrix.
reshape(A,...,[],...) lets you represent a size value with the placeholder [] while
calculating the magnitude of that size value automatically. For example, if A has size 2-
by-6, then reshape(A,4,[]) returns a 4-by-3 array.
reshape(A,sz) reshapes A into an array with size specified by sz, where sz is a vector.
Examples
4-1216
reshape
syms f(x) y
V = [3 f(x) -4 y]
V =
[ 3, f(x), -4, y]
Reshape V into Y.
Y = reshape(V,4,1)
Y =
3
f(x)
-4
y
M = sym([1 9 4 3 0 1; 3 9 5 1 9 2])
N = reshape(M,4,3)
M =
[ 1, 9, 4, 3, 0, 1]
[ 3, 9, 5, 1, 9, 2]
N =
[ 1, 4, 0]
[ 3, 5, 9]
[ 9, 3, 1]
[ 9, 1, 2]
M and N must have the same number of elements. reshape reads M column-wise to fill in
the elements of N column-wise.
Alternatively, use a size vector to specify the dimensions of the reshaped matrix.
sz = [4 3];
N = reshape(M,sz)
N =
4-1217
4 Functions Alphabetical List
[ 1, 4, 0]
[ 3, 5, 9]
[ 9, 3, 1]
[ 9, 1, 2]
M = sym([1 9 4 3 0 1; 3 9 5 1 9 2])
M =
[ 1, 9, 4, 3, 0, 1]
[ 3, 9, 5, 1, 9, 2]
reshape(M,[],3)
ans =
[ 1, 4, 0]
[ 3, 5, 9]
[ 9, 3, 1]
[ 9, 1, 2]
reshape calculates that a reshaped matrix of three columns needs four rows.
Create matrix M.
syms x
M = sym([1 9 0 sin(x) 2 2; NaN x 5 1 4 7])
M =
[ 1, 9, 0, sin(x), 2, 2]
[ NaN, x, 5, 1, 4, 7]
4-1218
reshape
ans =
[ 1, NaN, 9, x]
[ 0, 5, sin(x), 1]
[ 2, 4, 2, 7]
Note that .' returns the non-conjugate transpose while ' returns the conjugate
transpose.
M has 18 elements. Because a 9-by-2 matrix also has 18 elements, M can be reshaped into
it. Construct M.
syms x
M = [sin(x) x 4; 3 2 9; 8 x x];
M(:,:,2) = M'
M(:,:,1) =
[ sin(x), x, 4]
[ 3, 2, 9]
[ 8, x, x]
M(:,:,2) =
[ sin(conj(x)), 3, 8]
[ conj(x), 2, conj(x)]
[ 4, 9, conj(x)]
N =
[ sin(x), sin(conj(x))]
[ 3, conj(x)]
[ 8, 4]
[ x, 3]
[ 2, 2]
[ x, 9]
[ 4, 8]
[ 9, conj(x)]
4-1219
4 Functions Alphabetical List
[ x, conj(x)]
Create vector V.
syms x
V = [exp(x) 1 3 9 x 2 7 7 1 8 x^2 3 4 sin(x) x]
V =
[ exp(x), 1, 3, 9, x, 2, 7, 7, 1, 8, x^2, 3, 4, sin(x), x]
Specify 3 for the number of rows. Use the placeholder [] for the number of columns. This
lets reshape automatically calculate the number of columns required for three rows.
M = prod( reshape(V,3,[]) )
M =
[ 3*exp(x), 18*x, 49, 24*x^2, 4*x*sin(x)]
reshape calculates that five columns are required for a matrix of three rows. prod then
multiples the elements of each column to return the result.
Input Arguments
A Input array
symbolic vector | symbolic matrix | symbolic multidimensional array
4-1220
reshape
Size of reshaped array, specified as a numeric vector. For example, reshape(A,[3 2])
returns a 3-by-2 matrix. The number of elements in the output array specified by sz
must be equal to numel(A).
See Also
colon | numel | transpose
4-1221
4 Functions Alphabetical List
rewrite
Rewrite expression in terms of another function
Syntax
rewrite(expr,target)
Description
rewrite(expr,target) rewrites the symbolic expression expr in terms of the target
function target. The rewritten expression is mathematically equivalent to the original
expression. If expr is a vector or matrix, rewrite acts element-wise on expr.
Examples
Rewrite Between Trigonometric and Exponential Functions
Rewrite any trigonometric function in terms of the exponential function by specifying the
target 'exp'.
syms x
sin2exp = rewrite(sin(x), 'exp')
tan2exp = rewrite(tan(x), 'exp')
sin2exp =
(exp(-x*1i)*1i)/2 - (exp(x*1i)*1i)/2
tan2exp =
-(exp(x*2i)*1i - 1i)/(exp(x*2i) + 1)
Rewrite the exponential function in terms of any trigonometric function by specifying the
trigonometric function as the target. For a full list of targets, see target.
syms x
exp2sin = rewrite(exp(x), 'sin')
exp2tan = rewrite(-(exp(x*2i)*1i - 1i)/(exp(x*2i) + 1), 'tan')
exp2sin =
4-1222
rewrite
1 - 2*sin((x*1i)/2)^2 - sin(x*1i)*1i
exp2tan =
-(((tan(x) - 1i)*1i)/(tan(x) + 1i) + 1i)/((tan(x) - 1i)/(tan(x) + 1i) - 1)
exp2tan =
tan(x)
Rewrite tan(x) in terms of the sine function by specifying the target 'sin'.
syms x
tan2sin = rewrite(tan(x), 'sin')
tan2sin =
-sin(x)/(2*sin(x/2)^2 - 1)
Rewrite tanh(x) in terms of the sine function by specifying the target 'sin'.
syms x
tanh2sin = rewrite(tanh(x), 'sin')
tanh2sin =
(sin(x*1i)*1i)/(2*sin((x*1i)/2)^2 - 1)
4-1223
4 Functions Alphabetical List
acos2log =
-log(x + (1 - x^2)^(1/2)*1i)*1i
acot2log =
(log(1 - 1i/x)*1i)/2 - (log(1i/x + 1)*1i)/2
ans =
[ (exp(-x*1i)*1i)/2 - (exp(x*1i)*1i)/2, exp(-x*1i)/2 + exp(x*1i)/2]
[ exp(x)/2 - exp(-x)/2, exp(-x)/2 + exp(x)/2]
ans =
1 - 2*sin(x/2)^2
rewrite does not replace sin(x) with either - 1 - cos 2 ( x) or 1 - cos2 ( x) because
these expressions are not valid for all x. However, using the square of these expressions
to replace sin(x)^2 is valid for all x. Thus, rewrite replaces sin(x)^2.
4-1224
rewrite
syms x
rewrite(sin(x),'cos')
rewrite(sin(x)^2,'cos')
ans =
sin(x)
ans =
1 - cos(x)^2
Input Arguments
expr Input to rewrite
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix | symbolic multidimensional array
Target function, specified as a character vector. This table summarizes the rewriting
rules for all allowed targets.
4-1225
4 Functions Alphabetical List
More About
Tips
rewrite replaces symbolic function calls in expr with the target function only if the
replacement is mathematically valid. Otherwise, it keeps the original function calls.
See Also
collect | combine | expand | factor | horner | numden | simplify |
simplifyFraction
Introduced in R2012a
4-1226
root
root
Represent roots of polynomial
Syntax
root(p,x)
root(p,x,k)
Description
root(p,x) returns a column vector of numbered roots of symbolic polynomial p with
respect to x. Symbolically solving a high-degree polynomial for its roots can be complex
or mathematically impossible. In this case, the Symbolic Math Toolbox uses the root
function to represent the roots of the polynomial.
Examples
Represent Roots of High-Degree Polynomial
Represent the roots of the polynomial x3 + 1 using root. The root function returns a
column vector. The elements of this vector represent the three roots of the polynomial.
syms x
p = x^3 + 1;
root(p,x)
ans =
root(x^3 + 1, x, 1)
root(x^3 + 1, x, 2)
root(x^3 + 1, x, 3)
4-1227
4 Functions Alphabetical List
syms x
p = x^5 + x^4 - 3;
S = solve(p,x)
S =
root(z^5 + z^4 - 3, z, 1)
root(z^5 + z^4 - 3, z, 2)
root(z^5 + z^4 - 3, z, 3)
root(z^5 + z^4 - 3, z, 4)
root(z^5 + z^4 - 3, z, 5)
When the root function is returned in output, you can use the root function as input in
subsequent symbolic calculations. However, if a numerical result is required, convert the
root function to a high-precision numeric result using vpa.
S_vpa = vpa(S)
S_vpa =
1.0940419373839833208629604782883
- 1.2635458567287355027456460225178 - 0.66843435297180629866904635857054i
- 1.2635458567287355027456460225178 + 0.66843435297180629866904635857054i
0.21652488803674384231416578337365 - 1.1380204547108505954236988045135i
0.21652488803674384231416578337365 + 1.1380204547108505954236988045135i
If the call to root contains parameters, substitute the parameters with numbers using
subs before calling vpa.
syms x
r = root(x^6 + x, x, 1);
4-1228
root
simplify(sin(r)^2 + cos(r)^2)
ans =
1
ans =
root(x^2 + 5*x, x, 1)
Substituting for parameters using subs is necessary before converting root to numeric
form using vpa.
ans =
root(b^2*x^2 + b^2*x, x, 1)
H =
t - symsum(exp(root(s3^4 + s3^3 + 1, s3, k)*t)/...
(4*root(s3^4 + s3^3 + 1, s3, k) + 3), k, 1, 4)
When you get the root function in output, you can use the root function as input in
subsequent symbolic calculations. However, if a numerical result is required, convert the
root function to a high-precision numeric result using vpa.
H_vpa =
4-1229
4 Functions Alphabetical List
t +...
0.30881178580997278695808136329347*exp(-1.0189127943851558447865795886366*t)*...
cos(0.60256541999859902604398442197193*t) -...
0.30881178580997278695808136329347*exp(0.5189127943851558447865795886366*t)*...
cos(0.666609844932018579153758800733*t) -...
0.6919689479355443779463355813596*exp(-1.0189127943851558447865795886366*t)*...
sin(0.60256541999859902604398442197193*t) -...
0.16223098826244593894459034019473*exp(0.5189127943851558447865795886366*t)*...
sin(0.666609844932018579153758800733*t)
Input Arguments
p Symbolic polynomial
symbolic expression
x Variable
symbolic variable
See Also
solve | vpa
Introduced in R2015b
4-1230
round
round
Symbolic matrix element-wise round
Syntax
Y = round(X)
Description
Y = round(X) rounds the elements of X to the nearest integers. Values halfway
between two integers are rounded away from zero.
Examples
x = sym(-5/2);
[fix(x) floor(x) round(x) ceil(x) frac(x)]
ans =
[ -2, -3, -3, -2, -1/2]
See Also
floor | ceil | fix | frac
4-1231
4 Functions Alphabetical List
rref
Reduced row echelon form of matrix (Gauss-Jordan elimination)
Syntax
rref(A)
Description
rref(A) computes the reduced row echelon form of the symbolic matrix A. If the
elements of a matrix contain free symbolic variables, rref regards the matrix as
nonzero.
Examples
Compute the reduced row echelon form of the magic square matrix:
rref(sym(magic(4)))
ans =
[ 1, 0, 0, 1]
[ 0, 1, 0, 3]
[ 0, 0, 1, -3]
[ 0, 0, 0, 0]
Compute the reduced row echelon form of the following symbolic matrix:
syms a b c
A = [a b c; b c a; a + b, b + c, c + a];
rref(A)
ans =
[ 1, 0, -(- c^2 + a*b)/(- b^2 + a*c)]
[ 0, 1, -(- a^2 + b*c)/(- b^2 + a*c)]
[ 0, 0, 0]
4-1232
rref
See Also
eig | jordan | rank | size | linsolve
4-1233
4 Functions Alphabetical List
rsums
Interactive evaluation of Riemann sums
Syntax
rsums(f)
rsums(f,a,b)
rsums(f,[a,b])
Description
rsums(f) interactively approximates the integral of f(x) by Middle Riemann sums for
x from 0 to 1. rsums(f) displays a graph of f(x) using 10 terms (rectangles). You can
adjust the number of terms taken in the Middle Riemann sum by using the slider below
the graph. The number of terms available ranges from 2 to 128. f can be a character
vector or a symbolic expression. The height of each rectangle is determined by the value
of the function in the middle of each interval.
Examples
Visualize Riemann Sums
syms x
rsums(exp(-5*x^2))
4-1234
rsums
4-1235
4 Functions Alphabetical List
sec
Symbolic secant function
Syntax
sec(X)
Description
sec(X) returns the secant function of X.
Examples
Compute the secant function for these numbers. Because these numbers are not symbolic
objects, sec returns floating-point results.
A =
-2.4030 -1.0000 1.1547 -1.6039 225.9531
Compute the secant function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, sec returns unresolved symbolic calls.
symA =
[ 1/cos(2), -1, (2*3^(1/2))/3, -1/cos((2*pi)/7), 1/cos(11)]
4-1236
sec
vpa(symA)
ans =
[ -2.4029979617223809897546004014201,...
-1.0,...
1.1547005383792515290182975610039,...
-1.6038754716096765049444092780298,...
225.95305931402493269037542703557]
syms x
fplot(sec(x), [-4*pi, 4*pi])
grid on
4-1237
4 Functions Alphabetical List
syms x
diff(sec(x), x)
diff(sec(x), x, x)
ans =
sin(x)/cos(x)^2
4-1238
sec
ans =
1/cos(x) + (2*sin(x)^2)/cos(x)^3
ans =
log(1/cos(x)) + log(sin(x) + 1)
taylor(sec(x), x)
ans =
(5*x^4)/24 + x^2/2 + 1
ans =
1/(exp(-x*1i)/2 + exp(x*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 | atan | cos | cot | csc | sin | tan
4-1239
4 Functions Alphabetical List
sech
Symbolic hyperbolic secant function
Syntax
sech(X)
Description
sech(X) returns the hyperbolic secant function of X.
Examples
Compute the hyperbolic secant function for these numbers. Because these numbers are
not symbolic objects, sech returns floating-point results.
A =
0.2658 -1.0000 1.1547 1.0000 2.0000 -1.6039 0.6481
Compute the hyperbolic secant function for the numbers converted to symbolic objects.
For many symbolic (exact) numbers, sech returns unresolved symbolic calls.
symA =
[ 1/cosh(2), -1, (2*3^(1/2))/3, 1, 2, -1/cosh((pi*2i)/7), 1/cosh(1)]
4-1240
sech
vpa(symA)
ans =
[ 0.26580222883407969212086273981989,...
-1.0,...
1.1547005383792515290182975610039,...
1.0,...
2.0,...
-1.6038754716096765049444092780298,...
0.64805427366388539957497735322615]
syms x
fplot(sech(x), [-10, 10])
grid on
4-1241
4 Functions Alphabetical List
Find the first and second derivatives of the hyperbolic secant function:
syms x
diff(sech(x), x)
diff(sech(x), x, x)
ans =
-sinh(x)/cosh(x)^2
4-1242
sech
ans =
(2*sinh(x)^2)/cosh(x)^3 - 1/cosh(x)
ans =
2*atan(exp(x))
taylor(sech(x), x)
ans =
(5*x^4)/24 - x^2/2 + 1
ans =
1/(exp(-x)/2 + exp(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 | atanh | cosh | coth | csch | sinh |
tanh
4-1243
4 Functions Alphabetical List
series
Puiseux series
Syntax
series(f,var)
series(f,var,a)
series( ___ ,Name,Value)
Description
series(f,var) approximates f with the Puiseux series expansion of f up to the fifth
order at the point var = 0. If you do not specify var, then series uses the default
variable determined by symvar(f,1).
Examples
syms x
series(1/sin(x), x)
ans =
4-1244
series
Find the Puiseux series expansion of this multivariate expression. If you do not specify
the expansion variable, series uses the default variable determined by symvar(f,1).
syms s t
f = sin(s)/sin(t);
symvar(f, 1)
series(f)
ans =
t
ans =
sin(s)/t + (7*t^3*sin(s))/360 + (t*sin(s))/6
syms s t
f = sin(s)/sin(t);
series(f, s)
ans =
s^5/(120*sin(t)) - s^3/(6*sin(t)) + s/sin(t)
ans =
log(x) - 1/(2*x) - 1/(12*x^2) + 1/(120*x^4)
syms x
series(psi(x), x, Inf)
ans =
log(x) - 1/(2*x) - 1/(12*x^2) + 1/(120*x^4)
4-1245
4 Functions Alphabetical List
syms x
f = exp(x)/x;
s6 = series(f, x)
s6 =
x/2 + 1/x + x^2/6 + x^3/24 + x^4/120 + 1
Use Order to control the truncation order. For example, approximate the same
expression up to the orders 7 and 8.
s7 = series(f, x, 'Order', 7)
s8 = series(f, x, 'Order', 8)
s7 =
x/2 + 1/x + x^2/6 + x^3/24 + x^4/120 + x^5/720 + 1
s8 =
x/2 + 1/x + x^2/6 + x^3/24 + x^4/120 + x^5/720 + x^6/5040 + 1
Plot the original expression f and its approximations s6, s7, and s8. Note how the
accuracy of the approximation depends on the truncation order.
fplot([s6 s7 s8 f])
legend('approximation up to O(x^6)','approximation up to O(x^7)',...
'approximation up to O(x^8)','exp(x)/x','Location', 'Best')
title('Puiseux Series Expansion')
4-1246
series
Find the Puiseux series approximation of this expression. By default, series finds
the approximation that is valid in a small open circle in the complex plane around the
expansion point.
syms x
series(sin(sqrt(-x)), x)
4-1247
4 Functions Alphabetical List
ans =
(-x)^(1/2) - (-x)^(3/2)/6 + (-x)^(5/2)/120
Find the Puiseux series approximation of the same expression that is valid in a small
interval to the left of the expansion point. Then, find an approximation that is valid in a
small interval to the right of the expansion point.
syms x
series(sin(sqrt(-x)), x)
series(sin(sqrt(-x)), x, 'Direction', 'left')
series(sin(sqrt(-x)), x, 'Direction', 'right')
ans =
(-x)^(1/2) - (-x)^(3/2)/6 + (-x)^(5/2)/120
ans =
- x^(1/2)*1i - (x^(3/2)*1i)/6 - (x^(5/2)*1i)/120
ans =
x^(1/2)*1i + (x^(3/2)*1i)/6 + (x^(5/2)*1i)/120
Try computing the Puiseux series approximation of this expression. By default, series
tries to find an approximation that is valid in the complex plane around the expansion
point. For this expression, such approximation does not exist.
series(real(sin(x)), x)
However, the approximation exists along the real axis, to both sides of x = 0.
ans =
x^5/120 - x^3/6 + x
Input Arguments
f Input to approximate
symbolic expression | symbolic function | symbolic vector | symbolic matrix | symbolic
multidimensional array
4-1248
series
Expansion variable, specified as a symbolic variable. If you do not specify var, then
series uses the default variable determined by symvar(f,1).
a Expansion point
0 (default) | number | symbolic number | symbolic variable | symbolic function |
symbolic expression
You also can specify the expansion point as a Name,Value pair argument. If you specify
the expansion point both ways, then the Name,Value pair argument takes precedence.
You can also specify the expansion point using the input argument a. If you specify the
expansion point both ways, then the Name,Value pair argument takes precedence.
4-1249
4 Functions Alphabetical List
series computes the Puiseux series approximation with the order n - 1. The
truncation order n is the exponent in the O-term: O(varn).
More About
Tips
If you use both the third argument a and the ExpansionPoint name-value pair to
specify the expansion point, the value specified via ExpansionPoint prevails.
See Also
pade | taylor
Introduced in R2015b
4-1250
setVar
setVar
Assign variable in MuPAD notebook
Syntax
setVar(nb,MATLABvar)
setVar(nb,'MuPADvar',MATLABexpr)
Description
setVar(nb,MATLABvar) copies the symbolic variable MATLABvar and its value in the
MATLAB workspace to the variable MATLABvar in the MuPAD notebook nb.
Examples
Copy Variable and Its Value from MATLAB to MuPAD
Copy a variable y with a value exp(-x) assigned to it from the MATLAB workspace to a
MuPAD notebook. Do all three steps in the MATLAB Command Window.
syms x
y = exp(-x);
Create a new MuPAD notebook and specify a handle mpnb to that notebook:
mpnb = mupad;
Copy the variable y and its value exp(-x) to the MuPAD notebook mpnb:
setVar(mpnb,'y',y)
4-1251
4 Functions Alphabetical List
After executing this statement, the MuPAD engine associated with the mpnb notebook
contains the variable y, with its value exp(-x).
syms t
Create a new MuPAD notebook and specify a handle mpnb to that notebook:
mpnb = mupad;
Assign the value t^2 + 1 to the variable g in the MuPAD notebook mpnb:
setVar(mpnb,'g',t^2 + 1)
After executing this statement, the MuPAD engine associated with the mpnb notebook
contains the variable g, with its value t^2 + 1.
Copy Variables and Expressions Between MATLAB and MuPAD on page 3-51
Input Arguments
nb Pointer to MuPAD notebook
handle to notebook | vector of handles to notebooks
4-1252
setVar
See Also
getVar | mupad | openmu
Introduced in R2008b
4-1253
4 Functions Alphabetical List
sign
Sign of real or complex value
Syntax
sign(z)
Description
sign(z) returns the sign of real or complex value z. The sign of a complex number z
is defined as z/abs(z). If z is a vector or a matrix, sign(z) returns the sign of each
element of z.
Examples
ans =
[ 1, 0, -1]
ans =
[ 5^(1/2)*(1/5 + 2i/5), -1]
[ 2^(1/2)*(- 1/2 + 1i/2), 5^(1/2)*18^(1/2)*(1/30 - 1i/10)]
4-1254
sign
syms x
assume(x < 0)
sign(5*x^3)
ans =
-1
syms x clear
Input Arguments
z Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
More About
Sign Function
The sign function of any number z is defined via the absolute value of z:
z
sign ( z ) =
z
-1 if x < 0
sign ( z ) = 0 if x = 0
1 if x > 0
4-1255
4 Functions Alphabetical List
Tips
Calling sign for a number that is not a symbolic object invokes the MATLAB sign
function.
See Also
abs | angle | imag | real | signIm
Introduced in R2013a
4-1256
signIm
signIm
Sign of the imaginary part of complex number
Syntax
signIm(z)
Description
signIm(z) returns the sign of the imaginary part of a complex number z. For all
complex numbers with a nonzero imaginary part, singIm(z) = sign(imag(z)). For
real numbers, signIm(z) = -sign(z).
Examples
Integrate this expression. For complex values a and x, this integral includes signIm.
syms a x
f = 1/(a^2 + x^2);
F = int(f, x, -Inf, Inf)
F =
4-1257
4 Functions Alphabetical List
(pi*signIm(1i/a))/a
Use signIm to find the signs of imaginary parts of these numbers. For complex numbers
with nonzero imaginary parts, signIm returns the sign of the imaginary part of the
number.
ans =
1 -1 1 -1 1 -1
ans =
-1 -1 -1 -1
ans =
1 1 1 1
signIm(0) is 0.
ans =
0 0 0
4-1258
signIm
Call signIm for these symbolic expressions without additional assumptions. Because
signIm cannot determine if the imaginary part of a symbolic expression is positive,
negative, or zero, it returns unresolved symbolic calls.
syms x y z
[signIm(z), signIm(x + y*i), signIm(x - 3*i)]
ans =
[ signIm(z), signIm(x + y*1i), signIm(x - 3i)]
Assume that x, y, and z are positive values. Find the signs of imaginary parts of the
same symbolic expressions.
syms x y z positive
[signIm(z), signIm(x + y*i), signIm(x - 3*i)]
ans =
[ -1, 1, -1]
syms x y z clear
Find the first derivative of the signIm function. signIm is a constant function, except
for the jump discontinuities along the real axis. The diff function ignores these
discontinuities.
syms z
diff(signIm(z), z)
ans =
0
Find the signs of imaginary parts of the real and complex elements of matrix A.
ans =
4-1259
4 Functions Alphabetical List
[ 1, 1]
[ 1, -1]
Input Arguments
z Input representing complex number
number | symbolic number | symbolic variable | symbolic expression | vector | matrix
More About
Tips
See Also
conj | imag | real | sign
Introduced in R2014b
4-1260
simplify
simplify
Algebraic simplification
Syntax
simplify(S)
simplify(S,Name,Value)
Description
simplify(S) performs algebraic simplification of S. If S is a symbolic vector or matrix,
this function simplifies each element of S.
Examples
Simplify Expressions
Simplify these symbolic expressions:
syms x a b c
simplify(sin(x)^2 + cos(x)^2)
simplify(exp(c*log(sqrt(a+b))))
ans =
1
ans =
(a + b)^(c/2)
4-1261
4 Functions Alphabetical List
syms x
simplify([(x^2 + 5*x + 6)/(x + 2),...
sin(x)*sin(2*x) + cos(x)*cos(2*x);
(exp(-x*i)*i)/2 - (exp(x*i)*i)/2, sqrt(16)])
ans =
[ x + 3, cos(x)]
[ sin(x), 4]
ans =
-(log(x + 1) - log((x + 1)^2))*(x^2)^(1/2)
To apply the simplification rules that let the simplify function combine powers and
logarithms, set IgnoreAnalyticConstraints to true:
simplify(s, 'IgnoreAnalyticConstraints', true)
ans =
x*log(x + 1)
ans =
-(exp(x*2i)*1i - 1i)/(exp(x*2i) + 1)
By default, simplify uses one internal simplification step. You can get different, often
shorter, simplification results by increasing the number of simplification steps:
simplify(f, 'Steps', 10)
simplify(f, 'Steps', 30)
4-1262
simplify
ans =
2i/(exp(x*2i) + 1) - 1i
ans =
((cos(x) - sin(x)*1i)*1i)/cos(x) - 1i
ans =
tan(x)
ans =
sin(sin(x))*cosh(x) + cos(sin(x))*sinh(x)*1i
If x is a real value, then this form of expression explicitly shows the real and imaginary
parts.
Although the result returned by simplify with the default setting for Criterion is
shorter, here the complex value is a parameter of the sine function:
simplify(f, 'Steps', 100)
ans =
sin(sin(x) + x*1i)
When you set Criterion to preferReal, the simplifier disfavors expression forms
where complex values appear inside subexpressions. In case of nested subexpressions,
the deeper the complex value appears inside an expression, the least preference this form
of an expression gets.
4-1263
4 Functions Alphabetical List
ans =
exp(-pi/2)
ans =
(-1)^(1/2 + 1i/2)
Now, simplify the second expression with the Criterion set to preferReal:
simplify(sym(i)^(i+1), 'Criterion', 'preferReal', 'Steps', 100)
ans =
exp(-pi/2)*1i
Input Arguments
S Input expression
symbolic expression | symbolic function | symbolic vector | symbolic matrix
4-1264
simplify
Time limit for the simplification process, specified as the comma-separated pair
consisting of 'Seconds' and a positive value that denotes the maximal time in seconds.
Alternative Functionality
Besides the general simplification function (simplify), the toolbox provides a set of
functions for transforming mathematical expressions to particular forms. For example,
4-1265
4 Functions Alphabetical List
you can use particular functions to expand or factor expressions, collect terms with
the same powers, find a nested (Horner) representation of an expression, or quickly
simplify fractions. If the problem that you want to solve requires a particular form of an
expression, the best approach is to choose the appropriate simplification function. These
simplification functions are often faster than simplify.
More About
Tips
Algorithms
log(a) + log(b)=log(ab) for all values of a and b. In particular, the following equality
is valid for all values of a, b, and c:
(ab)c=acbc.
log(ab)=blog(a) for all values of a and b. In particular, the following equality is valid
for all values of a, b, and c:
(ab)c=abc.
If f and g are standard mathematical functions and f(g(x))=x for all small positive
numbers, f(g(x))=x is assumed to be valid for all complex values of x. In particular:
log(ex)=x
asin(sin(x))=x, acos(cos(x))=x, atan(tan(x))=x
asinh(sinh(x))=x, acosh(cosh(x))=x, atanh(tanh(x))=x
Wk(xex)=x for all values of k
See Also
collect | combine | expand | factor | horner | numden | rewrite |
simplifyFraction
4-1266
simplify
4-1267
4 Functions Alphabetical List
simplifyFraction
Symbolic simplification of fractions
Syntax
simplifyFraction(expr)
simplifyFraction(expr,Name,Value)
Description
simplifyFraction(expr) represents the expression expr as a fraction where both the
numerator and denominator are polynomials whose greatest common divisor is 1.
Input Arguments
expr
'Expand'
Default: false
4-1268
simplifyFraction
Examples
Simplify these fractions:
syms x y
simplifyFraction((x^2 - 1)/(x + 1))
simplifyFraction(((y + 1)^3*x)/((x^3 - x*(x + 1)*(x - 1))*y))
ans =
x - 1
ans =
(y + 1)^3/y
Use Expand to expand the numerator and denominator in the resulting fraction:
syms x y
simplifyFraction(((y + 1)^3*x)/((x^3 - x*(x + 1)*(x - 1))*y),...
'Expand', true)
ans =
(y^3 + 3*y^2 + 3*y + 1)/y
syms x
simplifyFraction(((x^2 + 2*x + 1)/(x + 1))^(1/2))
ans =
(x + 1)^(1/2)
ans =
sin(x) + 1
simplifyFraction((1 - cos(x)^2)/sin(x))
ans =
4-1269
4 Functions Alphabetical List
-(cos(x)^2 - 1)/sin(x)
Alternatives
You also can simplify fractions using the general simplification function simplify. Note
that in terms of performance, simplifyFraction is significantly more efficient for
simplifying fractions than simplify.
More About
Tips
expr can contain irrational subexpressions, such as sin(x), x^(-1/3), and so on.
As a first step, simplifyFraction replaces these subexpressions with auxiliary
variables. Before returning results, simplifyFraction replaces these variables with
the original subexpressions.
simplifyFraction ignores algebraic dependencies of irrational subexpressions.
See Also
collect | combine | expand | factor | horner | numden | rewrite | simplify
Introduced in R2011b
4-1270
simscapeEquation
simscapeEquation
Convert symbolic expressions to Simscape language equations
Syntax
simscapeEquation(f)
simscapeEquation(LHS,RHS)
Description
simscapeEquation(f) converts the symbolic expression f to a Simscape language
equation. This function call converts any derivative with respect to the variable t to
the Simscape notation X.der. Here X is the time-dependent variable. In the resulting
Simscape equation, the variable time replaces all instances of the variable t except for
derivatives with respect to t.
Examples
Convert the following expressions to Simscape language equations.
ans =
129 char array
phi == sin(time)+y*5.0+x.der;
ans =
131 char array
4-1271
4 Functions Alphabetical List
y.der == sin(time)+y*5.0+x.der;
ans =
143 char array
x.der == x1;
eqn1 == sin(time)-x1+x1.der;
ans =
178 char array
x.der == x1;
x1.der == x2;
x2.der == x3;
eqn2 == sin(time)-x1+x2+x3.der;
More About
Tips
If you perform symbolic computations in the MuPAD Notebook app and want to convert
the results to Simscape equations, use the generate::Simscape function in MuPAD.
Generate Simscape Equations from Symbolic Expressions on page 2-228
4-1272
simscapeEquation
See Also
matlabFunctionBlock | matlabFunction | ccode | fortran
Introduced in R2010a
4-1273
4 Functions Alphabetical List
sin
Symbolic sine function
Syntax
sin(X)
Description
sin(X) returns the sine function of X.
Examples
Compute the sine function for these numbers. Because these numbers are not symbolic
objects, sin returns floating-point results.
A =
-0.9093 -0.0000 0.5000 0.7818 -1.0000
Compute the sine function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, sin returns unresolved symbolic calls.
symA =
[ -sin(2), 0, 1/2, sin((2*pi)/7), sin(11)]
4-1274
sin
vpa(symA)
ans =
[ -0.90929742682568169539601986591174,...
0,...
0.5,...
0.78183148246802980870844452667406,...
-0.99999020655070345705156489902552]
syms x
fplot(sin(x), [-4*pi, 4*pi])
grid on
4-1275
4 Functions Alphabetical List
syms x
diff(sin(x), x)
diff(sin(x), x, x)
ans =
cos(x)
4-1276
sin
ans =
-sin(x)
ans =
-cos(x)
taylor(sin(x), x)
ans =
x^5/120 - x^3/6 + x
ans =
(exp(-x*1i)*1i)/2 - (exp(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 | atan | cos | cot | csc | sec | tan
4-1277
4 Functions Alphabetical List
single
Convert symbolic matrix to single precision
Syntax
single(S)
Description
single(S) converts the symbolic matrix S to a matrix of single-precision floating-point
numbers. S must not contain any symbolic variables, except 'eps'.
See Also
sym | vpa | double
4-1278
sinh
sinh
Symbolic hyperbolic sine function
Syntax
sinh(X)
Description
sinh(X) returns the hyperbolic sine function of X.
Examples
Compute the hyperbolic sine function for these numbers. Because these numbers are not
symbolic objects, sinh returns floating-point results.
A =
-3.6269 + 0.0000i 0.0000 - 0.0000i 0.0000 + 0.5000i...
0.0000 + 0.7818i 0.0000 - 1.0000i
Compute the hyperbolic sine function for the numbers converted to symbolic objects. For
many symbolic (exact) numbers, sinh returns unresolved symbolic calls.
symA =
[ -sinh(2), 0, 1i/2, sinh((pi*2i)/7), -1i]
4-1279
4 Functions Alphabetical List
vpa(symA)
ans =
[ -3.6268604078470187676682139828013,...
0,...
0.5i,...
0.78183148246802980870844452667406i,...
-1.0i]
syms x
fplot(sinh(x), [-pi, pi])
grid on
4-1280
sinh
Find the first and second derivatives of the hyperbolic sine function:
syms x
diff(sinh(x), x)
diff(sinh(x), x, x)
ans =
cosh(x)
4-1281
4 Functions Alphabetical List
ans =
sinh(x)
ans =
cosh(x)
taylor(sinh(x), x)
ans =
x^5/120 + x^3/6 + x
ans =
exp(x)/2 - exp(-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 | atanh | cosh | coth | csch | sech |
tanh
4-1282
sinhint
sinhint
Hyperbolic sine integral function
Syntax
sinhint(X)
Description
sinhint(X) returns the hyperbolic sine integral function of X.
Examples
Compute the hyperbolic sine integral function for these numbers. Because these numbers
are not symbolic objects, sinhint returns floating-point results.
A =
-5.4696 -1.0573 0 1.8027 53.7368
Compute the hyperbolic sine integral function for the numbers converted to symbolic
objects. For many symbolic (exact) numbers, sinhint returns unresolved symbolic calls.
symA =
[ -sinhint(pi), -sinhint(1), 0, sinhint(pi/2), sinhint(2*pi)]
4-1283
4 Functions Alphabetical List
vpa(symA)
ans =
[ -5.4696403451153421506369580091277,...
-1.0572508753757285145718423548959,...
0,...
1.802743198288293882089794577617,...
53.736750620859153990408011863262]
syms x
fplot(sinhint(x), [-2*pi, 2*pi])
grid on
4-1284
sinhint
Find the first and second derivatives of the hyperbolic sine integral function:
syms x
diff(sinhint(x), x)
diff(sinhint(x), x, x)
ans =
sinh(x)/x
4-1285
4 Functions Alphabetical List
ans =
cosh(x)/x - sinh(x)/x^2
ans =
x*sinhint(x) - cosh(x)
ans =
x^5/600 + x^3/18 + x
Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
More About
Hyperbolic Sine Integral Function
x
sinh ( t )
Shi ( x ) = dt
t
0
References
[1] Gautschi, W. and W. F. Cahill. Exponential Integral and Related Functions.
Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical
Tables. (M. Abramowitz and I. A. Stegun, eds.). New York: Dover, 1972.
4-1286
sinhint
See Also
coshint | cosint | eulergamma | int | sin | sinint | ssinint
Introduced in R2014a
4-1287
4 Functions Alphabetical List
sinint
Sine integral function
Syntax
sinint(X)
Description
sinint(X) returns the sine integral function of X.
Examples
Compute the sine integral function for these numbers. Because these numbers are not
symbolic objects, sinint returns floating-point results.
A =
-1.8519 0 1.3708 1.8519 0.9461
Compute the sine integral function for the numbers converted to symbolic objects. For
many symbolic (exact) numbers, sinint returns unresolved symbolic calls.
symA =
[ -sinint(pi), 0, sinint(pi/2), sinint(pi), sinint(1)]
4-1288
sinint
vpa(symA)
ans =
[ -1.851937051982466170361053370158,...
0,...
1.3707621681544884800696782883816,...
1.851937051982466170361053370158,...
0.94608307036718301494135331382318]
syms x
fplot(sinint(x), [-4*pi, 4*pi])
grid on
4-1289
4 Functions Alphabetical List
Find the first and second derivatives of the sine integral function:
syms x
diff(sinint(x), x)
diff(sinint(x), x, x)
ans =
sin(x)/x
4-1290
sinint
ans =
cos(x)/x - sin(x)/x^2
ans =
cos(x) + x*sinint(x)
ans =
x^5/600 - x^3/18 + x
Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
More About
Sine Integral Function
x
sin ( t )
Si ( x ) = dt
t
0
References
[1] Gautschi, W. and W. F. Cahill. Exponential Integral and Related Functions.
Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical
Tables. (M. Abramowitz and I. A. Stegun, eds.). New York: Dover, 1972.
4-1291
4 Functions Alphabetical List
See Also
coshint | cosint | eulergamma | int | sin | sinhint | ssinint
4-1292
size
size
Symbolic matrix dimensions
Syntax
d = size(A)
[m, n] = size(A)
d = size(A, n)
Description
Suppose A is an m-by-n symbolic or numeric matrix. The statement d = size(A) returns
a numeric vector with two integer components, d = [m,n].
The multiple assignment statement [m, n] = size(A) returns the two integers in two
separate variables.
The statement d = size(A, n) returns the length of the dimension specified by the
scalar n. For example, size(A,1) is the number of rows of A and size(A,2) is the
number of columns of A.
Examples
The statements
syms a b c d
A = [a b c ; a b d; d c b; c b a];
d = size(A)
r = size(A, 2)
return
d =
4 3
r =
4-1293
4 Functions Alphabetical List
See Also
length | ndims
4-1294
smithForm
smithForm
Smith form of matrix
Syntax
S = smithForm(A)
[U,V,S] = smithForm(A)
___ = smithForm(A,var)
Description
S = smithForm(A) returns the Smith normal form of a square invertible matrix
A. The elements of A must be integers or polynomials in a variable determined by
symvar(A,1). The Smith form S is a diagonal matrix.
You can use the input argument var in any of the previous syntaxes.
If A does not contain var, then smithForm(A) and smithForm(A,var) return different
results.
Examples
A = sym(invhilb(5))
4-1295
4 Functions Alphabetical List
S = smithForm(A)
A =
[ 25, -300, 1050, -1400, 630]
[ -300, 4800, -18900, 26880, -12600]
[ 1050, -18900, 79380, -117600, 56700]
[ -1400, 26880, -117600, 179200, -88200]
[ 630, -12600, 56700, -88200, 44100]
S =
[ 5, 0, 0, 0, 0]
[ 0, 60, 0, 0, 0]
[ 0, 0, 420, 0, 0]
[ 0, 0, 0, 840, 0]
[ 0, 0, 0, 0, 2520]
syms x
A = [x^2 + 3, (2*x - 1)^2; (x + 2)^2, 3*x^2 + 5]
A =
[ x^2 + 3, (2*x - 1)^2]
[ (x + 2)^2, 3*x^2 + 5]
S = smithForm(A)
S =
[ 1, 0]
[ 0, x^4 + 12*x^3 - 13*x^2 - 12*x - 11]
syms x y
A = [2/x + y, x^2 - y^2; 3*sin(x) + y, x]
A =
4-1296
smithForm
Find the Smith form of this matrix. If you do not specify the polynomial variable,
smithForm uses symvar(A,1) and thus determines that the polynomial variable is x.
Because 3*sin(x) + y is not a polynomial in x, smithForm throws an error.
S = smithForm(A)
Find the Smith form of A specifying that all elements of A are polynomials in the variable
y.
S = smithForm(A,y)
S =
[ 1, 0]
[ 0, 3*y^2*sin(x) - 3*x^2*sin(x) + y^3 + y*(- x^2 + x) + 2]
A = sym(invhilb(3));
[U,V,S] = smithForm(A)
U =
[ 1, 1, 1]
[ -4, -1, 0]
[ 10, 5, 3]
V =
[ 1, -2, 0]
[ 0, 1, 5]
[ 0, 1, 4]
S =
[ 3, 0, 0]
[ 0, 12, 0]
[ 0, 0, 60]
4-1297
4 Functions Alphabetical List
isAlways(S == U*A*V)
ans =
33 logical array
1 1 1
1 1 1
1 1 1
Find the Smith form and transformation matrices for a matrix of polynomials.
syms x y
A = [2*(x - y), 3*(x^2 - y^2);
4*(x^3 - y^3), 5*(x^4 - y^4)];
[U,V,S] = smithForm(A,x)
U =
[ 0, 1]
[ 1, - x/(10*y^3) - 3/(5*y^2)]
V =
[ -x/(4*y^3), - (5*x*y^2)/2 - (5*x^2*y)/2 - (5*x^3)/2 - (5*y^3)/2]
[ 1/(5*y^3), 2*x^2 + 2*x*y + 2*y^2]
S =
[ x - y, 0]
[ 0, x^4 + 6*x^3*y - 6*x*y^3 - y^4]
isAlways(S == U*A*V)
ans =
22 logical array
1 1
1 1
4-1298
smithForm
A =
9 -36 30
-36 192 -180
30 -180 180
syms x
smithForm(A,x)
ans =
1 0 0
0 1 0
0 0 1
smithForm(A)
ans =
3 0 0
0 12 0
0 0 60
Input Arguments
A Input matrix
square invertible symbolic matrix
Input matrix, specified as a square invertible symbolic matrix, the elements of which are
integers or univariate polynomials. If the elements of A contain more than one variable,
use the var argument to specify a polynomial variable, and treat all other variables as
symbolic parameters. If A is multivariate, and you do not specify var, then smithForm
uses symvar(A,1) to determine a polynomial variable.
4-1299
4 Functions Alphabetical List
Output Arguments
S Smith normal form of input matrix
symbolic diagonal matrix
Smith normal form of input matrix, returned as a symbolic diagonal matrix. The first
diagonal element divides the second, the second divides the third, and so on.
U Transformation matrix
unimodular symbolic matrix
V Transformation matrix
unimodular symbolic matrix
More About
Smith Normal Form
Smith normal form of a an n-by-n matrix A is an n-by-n diagonal matrix S, such that Si, i
divides Si +1, i +1 for all i < n.
See Also
hermiteForm | jordan
Introduced in R2015b
4-1300
solve
solve
Equations and systems solver
Compatibility
Character vector inputs will be removed in a future release. Instead, use syms to declare
variables and replace inputs such as solve('2*x == 1','x') with solve(2*x ==
1,x).
Syntax
S = solve(eqn,var)
S = solve(eqn,var,Name,Value)
Y = solve(eqns,vars)
Y = solve(eqns,vars,Name,Value)
[y1,...,yN] = solve(eqns,vars)
[y1,...,yN] = solve(eqns,vars,Name,Value)
[y1,...,yN,parameters,conditions] = solve(eqns,vars,'
ReturnConditions',true)
Description
S = solve(eqn,var) solves the equation eqn for the variable var. If you do not specify
var, the symvar function determines the variable to solve for. For example, solve(x +
1 == 2, x) solves the equation x+1=2 for x.
Y = solve(eqns,vars) solves the system of equations eqns for the variables vars
and returns a structure that contains the solutions. If you do not specify vars, solve
uses symvar to find the variables to solve for. In this case, the number of variables that
symvar finds is equal to the number of equations eqns.
4-1301
4 Functions Alphabetical List
[y1,...,yN,parameters,conditions] = solve(eqns,vars,'
ReturnConditions',true) returns the additional arguments parameters and
conditions that specify the parameters in the solution and the conditions on the
solution.
Examples
Solve an Equation
Use the == operator to specify the equation sin(x) == 1 and solve it.
syms x
eqn = sin(x) == 1;
solx = solve(eqn,x)
solx =
pi/2
Find the complete solution of the same equation by specifying the ReturnConditions
option as true. Specify output variables for the solution, the parameters in the solution,
and the conditions on the solution.
solx =
pi/2 + 2*pi*k
params =
4-1302
solve
conds =
in(k, 'integer')
The solution pi/2 + 2*pi*k contains the parameter k which is valid under the
condition in(k, 'integer'). This condition means the parameter k must be an
integer.
If solve returns an empty object, then no solutions exist. If solve returns an empty
object with a warning, solutions might exist but solve did not find any solutions.
solve(3*x+2, 3*x+1, x)
ans =
Empty sym: 0-by-1
Solve the equation sin(x) = 0. Provide two additional output variables for output
arguments parameters and conditions.
syms x
[solx, param, cond] = solve(sin(x) == 0, x, 'ReturnConditions', true)
solx =
pi*k
param =
k
cond =
in(k, 'integer')
The solution pi*k contains the parameter k and is valid under the condition
in(k,'integer'). This condition means the parameter k must be an integer. k does
not exist in the MATLAB workspace and must be accessed using param.
Find a valid value of k for 0 < x < 2*pi by assuming the condition, cond, and using
solve to solve these conditions for k. Substitute the value of k found into the solution for
x.
4-1303
4 Functions Alphabetical List
assume(cond)
solk = solve([solx > 0, solx < 2*pi], param)
valx = subs(solx, param, solk)
solk =
1
valx =
pi
A valid value of k for 0 < x < 2*pi is 1. This produces the value x = pi.
Alternatively, find a solution for x by choosing a value of k. Check if the value chosen
satisfies the condition on k using isAlways.
ans =
logical
1
isAlways returns logical 1 (true), meaning 4 is a valid value for k. Substitute k with 4
to obtain a solution for x. Use vpa to obtain a numeric approximation.
valx =
4*pi
ans =
12.566370614359172953850573533118
syms a b c x
4-1304
solve
sol =
-(b + (b^2 - 4*a*c)^(1/2))/(2*a)
-(b - (b^2 - 4*a*c)^(1/2))/(2*a)
sola =
-(c + b*x)/x^2
When solving for more than one variable, the order in which you specify the variables
defines the order in which the solver returns the solutions.
Solve this system of equations and assign the solutions to variables solv and solu
by specifying the variables explicitly. The solver returns an array of solutions for each
variable.
syms u v
[solv, solu] = solve([2*u^2 + v^2 == 0, u - v == 1], [v, u])
solv =
- (2^(1/2)*1i)/3 - 2/3
(2^(1/2)*1i)/3 - 2/3
solu =
1/3 - (2^(1/2)*1i)/3
(2^(1/2)*1i)/3 + 1/3
solutions =
[ - (2^(1/2)*1i)/3 - 2/3, 1/3 - (2^(1/2)*1i)/3]
[ (2^(1/2)*1i)/3 - 2/3, (2^(1/2)*1i)/3 + 1/3]
4-1305
4 Functions Alphabetical List
syms u v
S = solve([2*u + v == 0, u - v == 1], [u, v])
S =
struct with fields:
u: [11 sym]
v: [11 sym]
S.u
S.v
ans =
1/3
ans =
-2/3
Using a structure array allows you to conveniently substitute solutions into expressions.
The subs function substitutes the correct values irrespective of which variables you
substitute.
subs(u^2, S)
subs(3*v+u, S)
ans =
1/9
ans =
-5/3
syms x y
S = solve([sin(x)^2 == cos(y), 2*x == y],...
[x, y], 'ReturnConditions', true);
S.x
4-1306
solve
S.y
S.conditions
S.parameters
ans =
pi*k - asin(3^(1/2)/3)
asin(3^(1/2)/3) + pi*k
ans =
2*pi*k - 2*asin(3^(1/2)/3)
2*asin(3^(1/2)/3) + 2*pi*k
ans =
in(k, 'integer')
in(k, 'integer')
ans =
k
A solution is formed by the elements of the same index in S.x, S.y, and S.conditions.
Any element of S.parameters can appear in any solution. For example, a solution is x
= pi*k - asin(3^(1/2)/3), and y = 2*pi*k - 2*asin(3^(1/2)/3), with the
parameter k under the condition in(k, 'integer'). This condition means k must be
an integer for the solution to be valid. k does not exist in the MATLAB workspace and
must be accessed with S.parameters.
For the first solution, find a valid value of k for 0 < x < pi by assuming the condition
S.conditions(1) and using solve to solve these conditions for k. Substitute the value
of k found into the solution for x.
assume(S.conditions(1))
solk = solve([S.x(1) > 0, S.x(1) < pi], S.parameters)
solx = subs(S.x(1), S.parameters, solk)
solk =
1
solx =
pi - asin(3^(1/2)/3)
Alternatively, find a solution for x by choosing a value of k. Check if the value chosen
satisfies the condition on k using isAlways.
4-1307
4 Functions Alphabetical List
ans =
logical
1
isAlways returns logical 1 (true) meaning 4 is a valid value for k. Substitute k with 4
to obtain a solution for x. Use vpa to obtain a numeric approximation.
valx =
4*pi - asin(3^(1/2)/3)
ans =
11.950890905688785612783108943994
syms x
solve(sin(x) == x^2 - 1, x)
Plot the left and the right sides of the equation in one graph. The graph shows that the
equation also has a positive solution.
4-1308
solve
Find this solution by calling the numeric solver vpasolve directly and specifying the
interval where this solution can be found.
vpasolve(sin(x) == x^2 - 1, x, [0 2])
ans =
1.4096240040025962492355939705895
Solve Inequalities
solve can solve inequalities to find a solution that satisfies the inequalities.
4-1309
4 Functions Alphabetical List
x >0
y>0
x2 + y2 + xy < 1
syms x y
S = solve(x^2 + y^2 + x*y < 1, x > 0, y > 0,...
[x, y], 'ReturnConditions', true);
solx = S.x
soly = S.y
params = S.parameters
conditions = S.conditions
solx =
(- 3*v^2 + u)^(1/2)/2 - v/2
soly =
v
params =
[ u, v]
conditions =
4*v^2 < u & u < 4 & 0 < v
The parameters u and v do not exist in the MATLAB workspace and must be accessed
using S.parameters.
Check if the values u = 7/2 and v = 1/2 satisfy the condition using subs and
isAlways.
isAlways(subs(S.conditions, S.parameters, [7/2,1/2]))
ans =
logical
1
isAlways returns logical 1 (true) indicating that these values satisfy the condition.
Substitute these parameter values into S.x and S.y to find a solution for x and y.
solx = subs(S.x, S.parameters, [7/2,1/2])
soly = subs(S.y, S.parameters, [7/2,1/2])
solx =
4-1310
solve
11^(1/2)/4 - 1/4
soly =
1/2
vpa(solx)
vpa(soly)
ans =
0.57915619758884996227873318416767
ans =
0.5
Return only real solutions by setting argument Real to true. The only real solution of
this equation is 5.
ans =
5
4-1311
4 Functions Alphabetical List
ans =
0
pi/6
(5*pi)/6
ans =
0
ans =
- 14.009379055223370038369334703094 - 2.9255310052111119036668717988769i
S =
(3^(1/2)*exp(-(log(256) + log(3)^2)^(1/2)/2))/3
(3^(1/2)*exp((log(256) + log(3)^2)^(1/2)/2))/3
solve applies simplifications that allow it to find a solution. The simplifications applied
do not always hold. Thus, the solutions in this mode might not be correct or complete,
and need verification.
4-1312
solve
syms x positive
When you solve an equation or a system of equations for a variable under assumptions,
the solver only returns solutions consistent with the assumptions. Solve this equation for
x.
solve(x^2 + 5*x - 6 == 0, x)
ans =
1
ans =
-6
1
For further computations, clear the assumption that you set on the variable x.
syms x clear
syms x
s = solve(x^4 + x^3 + 1 == 0, x)
s =
root(z^4 + z^3 + 1, z, 1)
root(z^4 + z^3 + 1, z, 2)
root(z^4 + z^3 + 1, z, 3)
root(z^4 + z^3 + 1, z, 4)
Because there are no parameters in this solution, use vpa to approximate it numerically.
vpa(s)
4-1313
4 Functions Alphabetical List
ans =
- 1.0189127943851558447865795886366 + 0.60256541999859902604398442197193i
- 1.0189127943851558447865795886366 - 0.60256541999859902604398442197193i
0.5189127943851558447865795886366 + 0.666609844932018579153758800733i
0.5189127943851558447865795886366 - 0.666609844932018579153758800733i
syms x a
solve(x^4 + x^3 + a == 0, x)
ans =
root(z^4 + z^3 + a, z, 1)
root(z^4 + z^3 + a, z, 2)
root(z^4 + z^3 + a, z, 3)
root(z^4 + z^3 + a, z, 4)
Try to get an explicit solution for such equations by calling the solver with MaxDegree.
The option specifies the maximum degree of polynomials for which the solver tries
to return explicit solutions. The default value is 2. Increasing this value, you can get
explicit solutions for higher order polynomials.
where
4-1314
solve
/ / 2 \ \1/3
| | a 1 | a |
#1 == | sqrt| -- + -- | - - |
\ \ 4 27 / 2 /
Input Arguments
eqn Equation to solve
symbolic expression | symbolic equation
Variable for which you solve an equation, specified as a symbolic variable. By default,
solve uses the variable determined by symvar.
Variables for which you solve an equation or system of equations, specified as symbolic
variables. By default, solve uses the variables determined by symvar.
The order in which you specify these variables defines the order in which the solver
returns the solutions.
4-1315
4 Functions Alphabetical List
Flag for returning parameters in solution and conditions under which the solution is
true, specified as the comma-separated pair consisting of 'ReturnConditions' and one
of these values.
4-1316
solve
Flag for returning solutions inconsistent with the properties of variables, specified as the
comma-separated pair consisting of 'IgnoreProperties' and one of these values.
'MaxDegree' Maximum degree of polynomial equations for which solver uses explicit
formulas
2 (default) | positive integer smaller than 5
Maximum degree of polynomial equations for which solver uses explicit formulas,
specified as a positive integer smaller than 5. The solver does not use explicit formulas
that involve radicals when solving polynomial equations of a degree larger than the
specified value.
Flag for returning one solution, specified as the comma-separated pair consisting of
'PrincipalValue' and one of these values.
Flag for returning only real solutions, specified as the comma-separated pair consisting of
'Real' and one of these values.
4-1317
4 Functions Alphabetical List
true Return only those solutions for which every subexpression of the
original equation represents a real number. Also, assume that all
symbolic parameters of an equation represent real numbers.
Output Arguments
S Solutions of equation
symbolic array
4-1318
solve
Conditions under which solutions are valid, returned as a vector of symbolic expressions.
This output argument is only returned if ReturnConditions is true. If a single output
argument is provided, conditions is returned as a field of a structure. If multiple
output arguments are provided, conditions is returned as the last output argument.
Example: [solx, params, conditions] = solve(sin(x) == 0,
'ReturnConditions', true) returns the condition in(k, 'integer') in
conditions. The solution in solx is valid only under this condition.
More About
Tips
4-1319
4 Functions Alphabetical List
the parameters in the MATLAB workspace use syms to initialize the parameter. For
example, if the parameter is k, use syms k.
The variable names parameters and conditions are not allowed as inputs to
solve.
The syntax S = solve(eqn,var,'ReturnConditions',true) returns S as a
structure instead of a symbolic array.
To solve differential equations, use the dsolve function.
When solving a system of equations, always assign the result to output arguments.
Output arguments let you access the values of the solutions of a system.
MaxDegree only accepts positive integers smaller than 5 because, in general, there
are no explicit expressions for the roots of polynomials of degrees higher than 4.
The output variables y1,...,yN do not specify the variables for which solve solves
equations or systems. If y1,...,yN are the variables that appear in eqns, that
does not guarantee that solve(eqns) will assign the solutions to y1,...,yN using
the correct order. Thus, when you run [b,a] = solve(eqns), you might get the
solutions for a assigned to b and vice versa.
To ensure the order of the returned solutions, specify the variables vars. For
example, the call [b,a] = solve(eqns,b,a) assigns the solutions for a to a and
the solutions for b to b.
Algorithms
When you use IgnoreAnalyticConstraints, the solver applies these rules to the
expressions on both sides of an equation.
log(a) + log(b)=log(ab) for all values of a and b. In particular, the following equality
is valid for all values of a, b, and c:
(ab)c=acbc.
log(ab)=blog(a) for all values of a and b. In particular, the following equality is valid
for all values of a, b, and c:
(ab)c=abc.
If f and g are standard mathematical functions and f(g(x))=x for all small positive
numbers, f(g(x))=x is assumed to be valid for all complex values x. In particular:
log(ex)=x
4-1320
solve
See Also
dsolve | linsolve | root | subs | symvar | vpasolve
4-1321
4 Functions Alphabetical List
sort
Sort elements of symbolic vectors or matrices
Syntax
Y = sort(X)
[Y,I] = sort( ___ )
___ = sort(X,dim)
___ = sort( ___ ,'descend')
Description
Y = sort(X) sorts the elements of a symbolic vector or matrix in ascending order. If
X is a vector, sort(X) sorts the elements of X in lexicographic order. If X is a matrix,
sort(X) sorts each column of X.
[Y,I] = sort( ___ ) shows the indices that each element of Y had in the original
vector or matrix X.
If X is an m-by-n matrix and you sort elements of each column (dim = 2), then each
column of I is a permutation vector of the corresponding column of X, such that
for j = 1:n
Y(:,j) = X(I(:,j),j);
end
If X is a two-dimensional matrix, and you sort the elements of each column, the array I
shows the row indices that the elements of Y had in the original matrix X. If you sort the
elements of each row, I shows the original column indices.
___ = sort(X,dim) sorts the elements of X along the dimension dim. Thus, if X is
a two-dimensional matrix, then sort(X,1) sorts elements of each column of X, and
sort(X,2) sorts elements of each row.
___ = sort( ___ ,'descend') sorts X in descending order. By default, sort uses
ascending order.
4-1322
sort
Examples
syms a b c d e
sort([7 e 1 c 5 d a b])
ans =
[ 1, 5, 7, a, b, c, d, e]
Sort the matrix X returning the matrix of indices that each element of the sorted matrix
had in X:
X = sym(magic(3));
[Y, I] = sort(X)
Y =
[ 3, 1, 2]
[ 4, 5, 6]
[ 8, 9, 7]
I =
2 1 3
3 2 1
1 3 2
4-1323
4 Functions Alphabetical List
X = sym(magic(3))
X =
[ 8, 1, 6]
[ 3, 5, 7]
[ 4, 9, 2]
sort(X)
ans =
[ 3, 1, 2]
[ 4, 5, 6]
[ 8, 9, 7]
To sort the elements of each row, use set the value of the dim option to 2:
sort(X,2)
ans =
[ 1, 6, 8]
[ 3, 5, 7]
[ 2, 4, 9]
syms a b c d e
sort([7 e 1 c 5 d a b], 'descend')
ans =
[ e, d, c, b, a, 7, 5, 1]
X = sym(magic(3))
sort(X,'descend')
X =
[ 8, 1, 6]
4-1324
sort
[ 3, 5, 7]
[ 4, 9, 2]
ans =
[ 8, 9, 7]
[ 4, 5, 6]
[ 3, 1, 2]
sort(X, 2, 'descend')
ans =
[ 8, 6, 1]
[ 7, 5, 3]
[ 9, 4, 2]
Input Arguments
X Input that needs to be sorted
symbolic vector | symbolic matrix
Dimension to operate along, specified as a positive integer. The default value is 1. If dim
exceeds the number of dimensions of X, then sort(X,dim) returns X, and [Y,I] =
sort(X,dim) returns Y = X and I = ones(size(X)).
Output Arguments
Y Sorted output
symbolic vector | symbolic matrix
4-1325
4 Functions Alphabetical List
More About
Tips
Calling sort for vectors or matrices of numbers that are not symbolic objects invokes
the MATLAB sort function.
For complex input X, sort compares elements by their magnitudes (complex moduli),
computed with abs(X). If complex numbers have the same complex modulus, sort
compares their phase angles, angle(X).
If you use 'ascend' instead of 'descend', then sort returns elements in ascending
order, as it does by default.
sort uses the following rules:
See Also
max | min
4-1326
sqrtm
sqrtm
Matrix square root
Syntax
X = sqrtm(A)
[X,resnorm] = sqrtm(A)
Description
X = sqrtm(A) returns a matrix X, such that X2 = A and the eigenvalues of X are the
square roots of the eigenvalues of A.
Input Arguments
A
Symbolic matrix.
Output Arguments
X
resnorm
4-1327
4 Functions Alphabetical List
Examples
Compute the square root of this matrix. Because these numbers are not symbolic objects,
you get floating-point results.
A = [2 -2 0; -1 3 0; -1/3 5/3 2];
X = sqrtm(A)
X =
1.3333 -0.6667 0.0000
-0.3333 1.6667 -0.0000
-0.0572 0.5286 1.4142
Now, convert this matrix to a symbolic object, and compute its square root again:
A = sym([2 -2 0; -1 3 0; -1/3 5/3 2]);
X = sqrtm(A)
X =
[ 4/3, -2/3, 0]
[ -1/3, 5/3, 0]
[ (2*2^(1/2))/3 - 1, 1 - 2^(1/2)/3, 2^(1/2)]
ans =
33 logical array
1 1 1
1 1 1
1 1 1
Use the syntax with two output arguments to return the square root of a matrix and the
residual:
A = vpa(sym([0 0; 0 5/3]), 100);
[X,resnorm] = sqrtm(A)
X =
[ 0, 0]
[ 0, 1.2909944487358056283930884665941]
resnorm =
2.9387358770557187699218413430556e-40
4-1328
sqrtm
More About
Square Root of Matrix
The square root of a matrix A is a matrix X, such that X2 = A and the eigenvalues of X are
the square roots of the eigenvalues of A.
Tips
Calling sqrtm for a matrix that is not a symbolic object invokes the MATLAB sqrtm
function.
If A has an eigenvalue 0 of algebraic multiplicity larger than its geometric
multiplicity, the square root of A does not exist.
See Also
cond | eig | expm | funm | jordan | logm | norm
Introduced in R2013a
4-1329
4 Functions Alphabetical List
ssinint
Shifted sine integral function
Syntax
ssinint(X)
Description
ssinint(X) returns the shifted sine integral function ssinint(X) = sinint(X)
pi/2.
Examples
Compute the shifted sine integral function for these numbers. Because these numbers
are not symbolic objects, ssinint returns floating-point results.
A =
-3.4227 -1.5708 -0.2000 0.2811 -0.6247
Compute the shifted sine integral function for the numbers converted to symbolic objects.
For many symbolic (exact) numbers, ssinint returns unresolved symbolic calls.
symA =
[ - pi - ssinint(pi), -pi/2, ssinint(pi/2), ssinint(pi), ssinint(1)]
4-1330
ssinint
vpa(symA)
ans =
[ -3.4227333787773627895923750617977,...
-1.5707963267948966192313216916398,...
-0.20003415864040813916164340325818,...
0.28114072518756955112973167851824,...
-0.62471325642771360428996837781657]
syms x
fplot(ssinint(x), [-4*pi, 4*pi])
grid on
4-1331
4 Functions Alphabetical List
Find the first and second derivatives of the shifted sine integral function:
syms x
diff(ssinint(x), x)
diff(ssinint(x), x, x)
ans =
sin(x)/x
4-1332
ssinint
ans =
cos(x)/x - sin(x)/x^2
int(ssinint(x), x)
ans =
cos(x) + x*ssinint(x)
taylor(ssinint(x), x)
ans =
x^5/600 - x^3/18 + x - pi/2
Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
More About
Sine Integral Function
x
sin ( t )
Si ( x ) = dt
t
0
4-1333
4 Functions Alphabetical List
References
[1] Gautschi, W. and W. F. Cahill. Exponential Integral and Related Functions.
Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical
Tables. (M. Abramowitz and I. A. Stegun, eds.). New York: Dover, 1972.
See Also
coshint | cosint | eulergamma | int | sin | sinhint | sinhint | sinint
Introduced in R2014a
4-1334
subexpr
subexpr
Rewrite symbolic expression in terms of common subexpressions
Syntax
[r,sigma] = subexpr(expr)
[r,var] = subexpr(expr,'var')
[r,var] = subexpr(expr,var)
Description
[r,sigma] = subexpr(expr) rewrites the symbolic expression expr in terms of
a common subexpression, substituting this common subexpression with the symbolic
variable sigma. The input expression expr cannot contain the variable sigma.
This syntax overwrites the value of the variable var with the common subexpression
found in expr. To avoid overwriting the value of var, use another variable name as the
second output argument. For example, use [r,var1] = subexpr(expr,var).
Examples
syms a b c d x
4-1335
4 Functions Alphabetical List
sigma =
((d/(2*a) + b^3/(27*a^3) - (b*c)/(6*a^2))^2 + (- b^2/(9*a^2) +...
c/(3*a))^3)^(1/2) - b^3/(27*a^3) - d/(2*a) + (b*c)/(6*a^2)
solutions =
-(b + (b^2 - 4*a*c)^(1/2))/(2*a)
-(b - (b^2 - 4*a*c)^(1/2))/(2*a)
Use syms to create the symbolic variable s, and then replace common subexpressions in
the result with this variable.
syms s
[abbrSolutions,s] = subexpr(solutions,s)
abbrSolutions =
-(b + s)/(2*a)
-(b - s)/(2*a)
s =
(b^2 - 4*a*c)^(1/2)
4-1336
subexpr
-(b + s)/(2*a)
-(b - s)/(2*a)
s =
(b^2 - 4*a*c)^(1/2)
Both syntaxes overwrite the value of the variable s with the common subexpression.
Therefore, you cannot, for example, substitute s with some value.
subs(abbrSolutions,s,0)
ans =
-(b + s)/(2*a)
-(b - s)/(2*a)
To avoid overwriting the value of the variable s, use another variable name for the
second output argument.
syms s
[abbrSolutions,t] = subexpr(solutions,'s')
abbrSolutions =
-(b + s)/(2*a)
-(b - s)/(2*a)
t =
(b^2 - 4*a*c)^(1/2)
subs(abbrSolutions,s,0)
ans =
-b/(2*a)
-b/(2*a)
Input Arguments
expr Long expression containing common subexpressions
symbolic expression | symbolic function
subexpr throws an error if the input expression expr already contains var.
4-1337
4 Functions Alphabetical List
Output Arguments
r Expression with common subexpressions replaced by abbreviations
symbolic expression | symbolic function
See Also
children | pretty | simplify | subs
4-1338
subs
subs
Symbolic substitution
Syntax
subs(s,old,new)
subs(s,new)
subs(s)
Description
subs(s,old,new) returns a copy of s replacing all occurrences of old with new, and
then evaluating s.
subs(s) returns a copy of s replacing symbolic variables in s with their values obtained
from the calling function and the MATLAB workspace, and then evaluating s. Variables
with no assigned values remain as variables.
Examples
Single Substitution
Replace a with 4 in this expression.
syms a b
subs(a + b, a, 4)
ans =
b + 4
4-1339
4 Functions Alphabetical List
ans =
5*b
ans =
x
ans =
a + y
Single Input
Solve this ordinary differential equation.
syms a y(t)
y = dsolve(diff(y) == -a*y)
y =
C3*exp(-a*t)
Although the values a and C2 are now in the MATLAB workspace, y is not evaluated
with the account of these values.
y
y =
C3*exp(-a*t)
4-1340
subs
To evaluate y taking into account the new values of a and C2, use subs.
subs(y)
ans =
C3*exp(-980*t)
Multiple Substitutions
Make multiple substitutions by specifying the old and new values as vectors.
syms a b
subs(cos(a) + sin(b), [a, b], [sym('alpha'), 2])
ans =
sin(2) + cos(alpha)
ans =
sin(2) + cos(alpha)
syms a t
subs(exp(a*t) + 1, a, -magic(3))
ans =
[ exp(-8*t) + 1, exp(-t) + 1, exp(-6*t) + 1]
[ exp(-3*t) + 1, exp(-5*t) + 1, exp(-7*t) + 1]
[ exp(-4*t) + 1, exp(-9*t) + 1, exp(-2*t) + 1]
You can also replace an element of a vector, matrix, or array with a nonscalar value. For
example, create these 2-by-2 matrices.
A = sym('A', [2,2])
B = sym('B', [2,2])
A =
4-1341
4 Functions Alphabetical List
[ A1_1, A1_2]
[ A2_1, A2_2]
B =
[ B1_1, B1_2]
[ B2_1, B2_2]
Replace the first element of the matrix A with the matrix B. While making this
substitution, subs expands the 2-by-2 matrix A into this 4-by-4 matrix.
A44 = subs(A, A(1,1), B)
A44 =
[ B1_1, B1_2, A1_2, A1_2]
[ B2_1, B2_2, A1_2, A1_2]
[ A2_1, A2_1, A2_2, A2_2]
[ A2_1, A2_1, A2_2, A2_2]
ans =
[ 0, -1]
[ 2, 0]
ans =
0 -1
2 0
Substitutions in Equations
Replace sin(x + 1) with a in this equation.
4-1342
subs
syms x a
subs(sin(x + 1) + 1 == x, sin(x + 1), a)
ans =
a + 1 == x
Substitutions in Functions
Replace x with a in this symbolic function.
syms x y a
syms f(x, y)
f(x, y) = x + y;
f = subs(f, x, a)
f(x, y) =
a + y
subs replaces the values in the symbolic function formula, but does not replace input
arguments of the function.
formula(f)
argnames(f)
ans =
a + y
ans =
[ x, y]
syms x y
f(x, y) = x + y;
f(a, y) = subs(f, x, a);
f
f(a, y) =
a + y
Original Expression
Assign the expression x + y to s.
4-1343
4 Functions Alphabetical List
syms x y
s = x + y;
Replace y in this expression with the value 1. Here, s itself does not change.
subs(s, y, 1);
s
s =
x + y
To replace the value of s with the new expression, assign the result returned by subs to
s.
s = subs(s, y, 1);
s
s =
x + 1
Structure Array
Suppose you want to verify the solutions of this system of equations.
syms x y
eqs = [x^2 + y^2 == 1, x == y];
S = solve(eqs, x, y);
S.x
S.y
ans =
-2^(1/2)/2
2^(1/2)/2
ans =
-2^(1/2)/2
2^(1/2)/2
To verify the correctness of the returned solutions, substitute the solutions into the
original system.
isAlways(subs(eqs, S))
ans =
22 logical array
1 1
4-1344
subs
1 1
Input Arguments
s Input
symbolic variable | symbolic expression | symbolic equation | symbolic function |
symbolic array | symbolic vector | symbolic matrix
New element specified as a number, variable, expression, character vectors, array, vector,
matrix, or structure array.
More About
Tips
4-1345
4 Functions Alphabetical List
See Also
double | eval | simplify | subexpr | vpa
4-1346
svd
svd
Singular value decomposition of symbolic matrix
Syntax
sigma = svd(X)
[U,S,V] = svd(X)
[U,S,V] = svd(X,0)
[U,S,V] = svd(X,'econ')
Description
sigma = svd(X) returns a vector sigma containing the singular values of a symbolic
matrix A.
[U,S,V] = svd(X) returns numeric unitary matrices U and V with the columns
containing the singular vectors, and a diagonal matrix S containing the singular values.
The matrices satisfy the condition A = U*S*V', where V' is the Hermitian transpose
(the complex conjugate of the transpose) of V. The singular vector computation uses
variable-precision arithmetic. svd does not compute symbolic singular vectors. Therefore,
the input matrix X must be convertible to floating-point numbers. For example, it can be
a matrix of symbolic numbers.
Examples
Symbolic Singular Values
Compute the singular values of the symbolic 4-by-4 magic square:
4-1347
4 Functions Alphabetical List
A = sym(magic(4));
sigma = svd(A)
sigma =
34
8*5^(1/2)
2*5^(1/2)
0
Now, compute singular values of the matrix whose elements are symbolic expressions:
syms t real
A = [0 1; -1 0];
E = expm(t*A)
sigma = svd(E)
E =
[ cos(t), sin(t)]
[ -sin(t), cos(t)]
sigma =
(cos(t)^2 + sin(t)^2)^(1/2)
(cos(t)^2 + sin(t)^2)^(1/2)
sigma =
1
1
sigma =
34.0
4-1348
svd
17.88854381999831757127338934985
4.4721359549995793928183473374626
0.0000000000000000000042127245515076439434819165724023i
old = digits(10);
A = sym(magic(4))
[U, S, V] = svd(A)
digits(old)
A =
[ 16, 2, 3, 13]
[ 5, 11, 10, 8]
[ 9, 7, 6, 12]
[ 4, 14, 15, 1]
U =
[ 0.5, 0.6708203932, 0.5, -0.2236067977]
[ 0.5, -0.2236067977, -0.5, -0.6708203932]
[ 0.5, 0.2236067977, -0.5, 0.6708203932]
[ 0.5, -0.6708203932, 0.5, 0.2236067977]
S =
[ 34.0, 0, 0, 0]
[ 0, 17.88854382, 0, 0]
[ 0, 0, 4.472135955, 0]
[ 0, 0, 0, 1.108401846e-15]
V =
[ 0.5, 0.5, 0.6708203932, 0.2236067977]
[ 0.5, -0.5, -0.2236067977, 0.6708203932]
[ 0.5, -0.5, 0.2236067977, -0.6708203932]
[ 0.5, 0.5, -0.6708203932, -0.2236067977]
Compute the product of U, S, and the Hermitian transpose of V with the 10-digit
accuracy. The result is the original matrix A with all its elements converted to floating-
point numbers:
vpa(U*S*V',10)
ans =
4-1349
4 Functions Alphabetical List
old = digits(10);
A = sym([1 1;2 2; 2 2]);
[U, S, V] = svd(A, 0)
U =
[ 0.3333333333, -0.6666666667]
[ 0.6666666667, 0.6666666667]
[ 0.6666666667, -0.3333333333]
S =
[ 4.242640687, 0]
[ 0, 0]
V =
[ 0.7071067812, 0.7071067812]
[ 0.7071067812, -0.7071067812]
Now, use the second input argument 'econ' to compute the "economy size"
decomposition of matrix B. Here, the 3-by-2 matrix B is the transpose of A.
B = A';
[U, S, V] = svd(B, 'econ')
digits(old)
U =
[ 0.7071067812, -0.7071067812]
[ 0.7071067812, 0.7071067812]
S =
[ 4.242640687, 0]
[ 0, 0]
V =
[ 0.3333333333, 0.6666666667]
4-1350
svd
[ 0.6666666667, -0.6666666667]
[ 0.6666666667, 0.3333333333]
Input Arguments
X Input matrix
symbolic matrix
Input matrix specified as a symbolic matrix. For syntaxes with one output argument, the
elements of X can be symbolic numbers, variables, expressions, or functions. For syntaxes
with three output arguments, the elements of X must be convertible to floating-point
numbers.
Output Arguments
sigma Singular values
symbolic vector | vector of symbolic numbers
U Singular vectors
matrix of symbolic numbers
Singular vectors, returned as a unitary matrix. Each column of this matrix is a singular
vector.
S Singular values
matrix of symbolic numbers
Singular values, returned as a diagonal matrix. Diagonal elements of this matrix appear
in descending order.
V Singular vectors
matrix of symbolic numbers
Singular vectors, returned as a unitary matrix. Each column of this matrix is a singular
vector.
4-1351
4 Functions Alphabetical List
More About
Tips
The second arguments 0 and 'econ' only affect the shape of the returned matrices.
These arguments do not affect the performance of the computations.
Calling svd for numeric matrices that are not symbolic objects invokes the MATLAB
svd function.
See Also
chol | digits | eig | inv | lu | qr | svd | vpa
4-1352
sym
sym
Create symbolic variables, expressions, functions, matrices
Compatibility
The syntaxes sym(A,set) and sym(A,'clear') for a symbolic object A in the MATLAB
workspace have been removed. Use assume(A,set) and assume(A,'clear') instead.
Syntax
x = sym('x')
A = sym('a', [n1 ... nM])
A = sym('a', n)
sym(num)
sym(num, flag)
symexpr = sym(h)
Description
x = sym('x') creates symbolic variable x.
A = sym('a', [n1 ... nM]) creates an n1-by-...-by-nM symbolic array filled with
automatically generated elements. For example, A = sym('a',[1 3]) creates the row
vector A = [a1 a2 a3]. The auto-generated elements do not appear in the MATLAB
4-1353
4 Functions Alphabetical List
workspace. For arrays, these elements have the prefix a followed by the elements index
using _ as a delimiter, such as a1_3_2.
sym( ___ , set) creates a symbolic variable or array and sets the assumption that the
variable or all array elements belong to a set. Here, set can be 'real', 'positive',
'integer', or 'rational'.
sym( ___ , 'clear') clears assumptions set on a symbolic variable or array. You
can specify 'clear' after the input arguments in any of the previous syntaxes, except
combining 'clear' and set. You cannot set and clear an assumption in the same
function call to sym.
sym(num, flag) uses the technique specified by flag for converting floating-point
numbers to symbolic numbers.
Examples
Create Symbolic Variables
Create the symbolic variables x and y.
x = sym('x');
y = sym('y');
a =
4-1354
sym
Format the names of elements of a by using a format character vector as the first
argument. sym replaces %d in the format character vector with the index of the element
to generate the element names.
a = sym('x_%d', [1 4])
a =
[ x_1, x_2, x_3, x_4]
This syntax does not create symbolic variables x_1, ..., x_4 in the MATLAB workspace.
Access elements of a using standard indexing methods.
a(1)
a(2:3)
ans =
x_1
ans =
[ x_2, x_3]
A =
[ A1_1, A1_2, A1_3, A1_4]
[ A2_1, A2_2, A2_3, A2_4]
[ A3_1, A3_2, A3_3, A3_4]
Create a 4-by-4 matrix with the element names x_1_1, ..., x_4_4 by using a format
character vector as the first argument. sym replaces %d in the format character vector
with the index of the element to generate the element names.
B = sym('x_%d_%d',4)
B =
[ x_1_1, x_1_2, x_1_3, x_1_4]
[ x_2_1, x_2_2, x_2_3, x_2_4]
[ x_3_1, x_3_2, x_3_3, x_3_4]
[ x_4_1, x_4_2, x_4_3, x_4_4]
4-1355
4 Functions Alphabetical List
This syntax does not create symbolic variables A1_1, ..., A3_4, x_1_1, ..., x_4_4 in the
MATLAB workspace. To access an element of a matrix, use parentheses.
A(2,3)
B(4,2)
ans =
A2_3
ans =
x_4_2
A(:,:,1) =
[ a1_1_1, a1_2_1]
[ a2_1_1, a2_2_1]
A(:,:,2) =
[ a1_1_2, a1_2_2]
[ a2_1_2, a2_2_2]
inaccurate2 = sym(sqrt(1234567))
accurate2 = sqrt(sym(1234567))
inaccurate3 = sym(exp(pi))
accurate3 = exp(sym(pi))
inaccurate1 =
7650239286923505/9444732965739290427392
4-1356
sym
accurate1 =
1/1234567
inaccurate2 =
4886716562018589/4398046511104
accurate2 =
1234567^(1/2)
inaccurate3 =
6513525919879993/281474976710656
accurate3 =
exp(pi)
inaccurateNum =
11111111111111110656
accurateNum =
11111111111111111111
When you use quotation marks to create symbolic complex numbers, specify the
imaginary part of a number as 1i, 2i, and so on.
sym('1234567 + 1i')
ans =
1234567 + 1i
sym_expr =
cos(x) + sin(x)
4-1357
4 Functions Alphabetical List
h_matrix = @(x)(x*pascal(3));
sym_matrix = sym(h_matrix)
sym_matrix =
[ x, x, x]
[ x, 2*x, 3*x]
[ x, 3*x, 6*x]
ans =
[ in(t, 'rational'), in(x, 'real'), 0 < y, in(z, 'integer')]
ans =
Empty sym: 1-by-0
A =
[ A11, A12]
[ A21, A22]
Solve an equation involving the first element of A. MATLAB assumes that this element is
positive.
4-1358
sym
ans =
1
ans =
[ 0 < A21, 0 < A11, 0 < A22, 0 < A12]
Clear all previously set assumptions on elements of a symbolic matrix by using assume.
assume(A,'clear');
assumptions(A)
ans =
Empty sym: 1-by-0
ans =
-1
1
Choose the conversion technique by specifying the optional second argument, which can
be 'r', 'f', 'd', or 'e'. The default is 'r'. See the Input Arguments section for the
details about conversion techniques.
r = sym(pi)
f = sym(pi,'f')
d = sym(pi,'d')
e = sym(pi,'e')
r =
pi
f =
4-1359
4 Functions Alphabetical List
884279719003555/281474976710656
d =
3.1415926535897931159979634685442
e =
pi - (198*eps)/359
Input Arguments
x Variable name
character vector
Variable name, specified as a character vector. Argument x must a valid variable name.
That is, x must begin with a letter and can contain only alphanumeric characters and
underscores. To verify that the name is a valid variable name, use isvarname.
Example: x, y123, z_1
h Anonymous function
MATLAB function handle
4-1360
sym
'r' When sym uses the rational mode, it converts floating-point numbers obtained
by evaluating expressions of the form p/q, p*pi/q, sqrt(p), 2^q, and
10^q for modest sized integers p and q to the corresponding symbolic form.
This effectively compensates for the round-off error involved in the original
evaluation, but might not represent the floating-point value precisely. If sym
cannot find simple rational approximation, then it uses the same technique as
it would use with the flag 'f'.
'd' When sym uses the decimal mode, it takes the number of digits from the
current setting of digits. Conversions with fewer than 16 digits lose some
accuracy, while more than 16 digits might not be warranted. For example,
sym(4/3,'d') with the 10-digit accuracy returns 1.333333333, while with
the 20-digit accuracy it returns 1.3333333333333332593. The latter does
not end in 3s, but it is an accurate decimal representation of the floating-point
number nearest to 4/3.
'e' When sym uses the estimate error mode, it supplements a result obtained in
the rational mode by a term involving the variable eps. This term estimates
the difference between the theoretical rational expression and its actual
floating-point value. For example, sym(3*pi/4,'e') returns (3*pi)/4 -
(103*eps)/249.
4-1361
4 Functions Alphabetical List
'f' When sym uses the floating-point mode, it represents all values in the
form N*2^e or -N*2^e, where N >= 0 and e are integers. For example,
sym(1/10,'f') returns 3602879701896397/36028797018963968 . The
returned rational value is the exact value of the floating-point number that
you convert to a symbolic number.
Output Arguments
x Variable
symbolic variable
Alternative Functionality
Alternative Approaches for Creating Symbolic Variables
To create several symbolic variables in one function call, use syms.
More About
Tips
4-1362
sym
and 1/10. The pi created in this way temporarily replaces the built-in numeric
function with the same name.
sym always treats i in character vector input as an identifier. To input the imaginary
number i, use 1i instead.
clear x does not clear the symbolic object of its assumptions, such as real, positive,
or any assumptions set by assume, sym, or syms. To remove assumptions, use one of
these options:
A =
3.1416 0 0
0 1.0000 0
0 0 1.0000
You cannot replace elements of a numeric vector or matrix with a symbolic variable,
expression, or function because these elements cannot be converted to double-
precision numbers. For example, A(1,1) = sym('a') throws an error.
See Also
assume | assumeAlso | assumptions | clear | clear all | double | eps | reset
| symfun | syms | symvar
4-1363
4 Functions Alphabetical List
sym2cell
Convert symbolic array to cell array
Syntax
C = sym2cell(S)
Description
C = sym2cell(S) converts a symbolic array S to a cell array C. The resulting cell array
has the same size and dimensions as the input symbolic array.
Examples
syms x y
S = [x 2 3 4; y 6 7 8; 9 10 11 12]
S =
[ x, 2, 3, 4]
[ y, 6, 7, 8]
[ 9, 10, 11, 12]
Convert this matrix to a cell array by using sym2cell. The size of the resulting cell
array corresponds to the size of the input matrix. Each cell contains an element of the
symbolic matrix S.
C = sym2cell(S)
C =
34 cell array
4-1364
sym2cell
ans =
[ x, 2, 3, 4]
[C{1:3,1}]
ans =
[ x, y, 9]
Input Arguments
S Input symbolic array
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix | symbolic multidimensional array
Output Arguments
C Resulting cell array
cell array
Resulting cell array, returned as a cell array such that size(C) = size(S). Each
element of the input symbolic array S is enclosed in a separate cell.
See Also
cell2mat | cell2sym | mat2cell | num2cell
Introduced in R2016a
4-1365
4 Functions Alphabetical List
sym2poly
Extract vector of all numeric coefficients, including zeros, from symbolic polynomial
Syntax
c = sym2poly(p)
Description
c = sym2poly(p) returns the numeric vector of coefficients c of the symbolic
polynomial p. The returned vector c includes all coefficients, including those equal 0.
Examples
Extract Numeric Coefficients of Polynomial
Create row vectors of coefficients of symbolic polynomials.
c =
1 0 -2 -5
Extract rational and integer coefficients of a symbolic polynomial into a vector. Because
sym2poly returns numeric double-precision results, it approximates exact rational
coefficients with double-precision numbers.
c = sym2poly(1/2*x^3 - 2/3*x - 5)
c =
4-1366
sym2poly
Input Arguments
p Polynomial
symbolic expression
Output Arguments
c Polynomial coefficients
numeric row vector
More About
Tips
See Also
coeffs | poly2sym
4-1367
4 Functions Alphabetical List
symengine
Return symbolic engine
Syntax
s = symengine
Description
s = symengine returns the currently active symbolic engine.
Examples
To see which symbolic computation engine is currently active, enter:
s = symengine
s =
MuPAD symbolic engine
Now you can use the variable s in function calls that require symbolic engine:
syms a b c x
p = a*x^2 + b*x + c;
feval(s,'polylib::discrim', p, x)
ans =
b^2 - 4*a*c
See Also
evalin | feval | read
Introduced in R2008b
4-1368
symfun
symfun
Create symbolic functions
Syntax
f = symfun(formula,inputs)
Description
f = symfun(formula,inputs) creates the symbolic function f. The symbolic variables
inputs represent its input arguments. The symbolic expression formula defines the
body of the function f.
Examples
Create Symbolic Functions
Use syms to create symbolic variables. Then use symfun to create a symbolic function
with these variables as its input arguments.
syms x y
f = symfun(x + y, [x y])
f(x, y) =
x + y
ans =
3
Input Arguments
formula Function body
symbolic expression | vector of symbolic expressions | matrix of symbolic expressions
4-1369
4 Functions Alphabetical List
Output Arguments
f Function
symbolic function (symfun data type)
Alternative Functionality
syms x y
f(x,y) = x + y
Use syms to create an abstract symbolic function f(x,y) and its arguments. The
following command creates the symbolic function f and the symbolic variables x and
y. Using syms, you also can create multiple symbolic functions in one function call.
syms f(x,y)
4-1370
symfun
More About
Tips
When you replace one or more elements of a numeric vector or matrix with a symbolic
number, MATLAB converts that number to a double-precision number.
A = eye(3);
A(1,1) = sym('pi')
A =
3.1416 0 0
0 1.0000 0
0 0 1.0000
You cannot replace elements of a numeric vector or matrix with a symbolic variable,
expression, or function because these elements cannot be converted to double-
precision numbers. For example, syms f(t); A(1,1) = f throws an error.
Symbolic functions are always scalars, therefore, you cannot index into a function. To
access x^2 and x^4 in this example, use formula to get the expression that defines f,
and then index into that expression.
syms x
f = symfun([x^2, x^4], x);
expr = formula(f);
expr(1)
expr(2)
ans =
x^2
ans =
x^4
See Also
argnames | dsolve | formula | matlabFunction | odeToVectorField | sym |
syms | symvar
Introduced in R2012a
4-1371
4 Functions Alphabetical List
sympref
Set symbolic preferences
Syntax
sympref(pref,value)
sympref(pref,'default')
sympref(pref)
sympref()
sympref('default')
sympref(allPref)
Description
sympref(pref,value) sets the symbolic preference pref to value and returns
the previous value of pref. Symbolic preferences can affect the functions fourier,
ifourier, and heaviside. These preferences persist between successive MATLAB
sessions.
sympref(pref,'default') sets pref to its default value and returns the previous
value of pref.
sympref('default') sets all symbolic preferences to their default values and returns
the previous values in a structure.
Note: Symbolic preferences persist between successive MATLAB sessions. MATLAB does
not restore them for a new session.
4-1372
sympref
Examples
Change Parameter Values of Fourier Transform
The Fourier transform F(w) of f=f(t) is
F ( w) = c f ( t ) eiswt dt,
-
where c and s are parameters with default values 1 and -1. Other common values for c
are 1/2 and 1 2p , and for s are 1, -2, and 2.
ans =
-pi*(dirac(w - 1) - dirac(w + 1))*1i
Find the same Fourier transform for c = 1/(2) and s = 1. Set these parameter
values by using the FourierParameter preference of sympref. Represent exactly
using sym. The values of c and s are specified as the vector [1/(2*sym(pi)) 1]. Store
the previous values returned by sympref to restore them later.
oldparam = sympref('FourierParameters',[1/(2*sym(pi)) 1])
fourier(sin(t),t,w)
oldparam =
[ 1, -1]
ans =
(dirac(w - 1)*1i)/2 - (dirac(w + 1)*1i)/2
The preferences set by sympref persist through your current and future MATLAB
sessions. Restore the old values of c and s using the previous parameter values stored in
oldparam.
sympref('FourierParameters',oldparam);
Alternatively, you can restore the default values of c and s by specifying the 'default'
option.
4-1373
4 Functions Alphabetical List
sympref('FourierParameters','default');
syms x
heaviside(sym(0))
ztrans(heaviside(x))
ans =
1/2
ans =
1/(z - 1) + 1/2
Other common values for the Heaviside function at the origin are 0 and 1. Set
heaviside(0) to 1 using the 'HeavisideAtOrigin' preference of sympref. Store the
old parameter value returned by sympref to restore it later.
oldparam = sympref('HeavisideAtOrigin',1)
oldparam =
1/2
Check the new value of heaviside(0). Find the Z-Transform of heaviside(x) for this
value.
heaviside(sym(0))
ztrans(heaviside(x))
ans =
1
ans =
1/(z - 1) + 1
The preferences set by sympref persist throughout your current and future MATLAB
sessions. Restore the previous value of heaviside(0) by loading the old parameter
stored in oldparam.
4-1374
sympref
sympref('HeavisideAtOrigin',oldparam);
Turn off abbreviated output and display the same expression again.
sympref('AbbreviateOutput',false);
outputLong = sin(f) + cos(f) + tan(f) + log(f) + 1/f
Turn off rendered output and use ASCII output instead by setting the preference
'TypesetOutput' to false. First, show the typeset output.
4-1375
4 Functions Alphabetical List
syms a b c d x
f = exp(a^b)+pi
Turn off typeset output and display the same expression again.
sympref('TypesetOutput',false);
f = exp(a^b)+pi
The preferences set by sympref persist throughout your current and future MATLAB
sessions. Restore the default values of 'AbbreviateOutput' and 'TypesetOutput' by
using the option 'default'.
sympref('AbbreviateOutput','default');
sympref('TypesetOutput','default');
Return the values of all symbolic preferences using sympref. The sympref function
returns a structure of values of preferences. Access individual preferences by addressing
the fields of the structure.
S = sympref;
S.FourierParameters
S.HeavisideAtOrigin
ans =
[ 1, -1]
ans =
1/2
4-1376
sympref
Assume that you have changed the preferences. Since the preferences persist through
your current and future MATLAB sessions, you want to restore your previous
preferences in S. Restore the saved preferences using sympref(S).
sympref(S);
Alternatively, you can set all symbolic preferences to their defaults by specifying the
option 'default'.
sympref('default');
Input Arguments
pref Symbolic preference
character vector
More About
Tips
See Also
fourier | heaviside | ifourier
4-1377
4 Functions Alphabetical List
Introduced in R2015a
4-1378
symprod
symprod
Product of series
Syntax
F = symprod(f,k,a,b)
F = symprod(f,k)
Description
F = symprod(f,k,a,b) returns the product of the series with terms that expression f
specifies, which depend on symbolic variable k. The value of k ranges from a to b. If you
do not specify k, symprod uses the variable that symvar determines. If f is a constant,
then the default variable is x.
F = symprod(f,k) returns the product of the series that expression f specifies, which
depend on symbolic variable k. The value of k starts at 1 with an unspecified upper
bound. The product F is returned in terms of k where k represents the upper bound. This
product F differs from the indefinite product. If you do not specify k, symprod uses the
variable that symvar determines. If f is a constant, then the default variable is x.
Examples
1
P1 = 1 - ,
k= 2 k2
k2
P2 = .
2
k= 2 k -1
4-1379
4 Functions Alphabetical List
syms k
P1 = symprod(1 - 1/k^2, k, 2, Inf)
P2 = symprod(k^2/(k^2 - 1), k, 2, Inf)
P1 =
1/2
P2 =
2
syms k
P1 = symprod(1 - 1/k^2, k, [2 Inf])
P2 = symprod(k^2/(k^2 - 1), k, [2; Inf])
P1 =
1/2
P2 =
2
10000 kx
e
P= x
.
k =1
syms k x
P = symprod(exp(k*x)/x, k, 1, 10000)
P =
exp(50005000*x)/x^10000
4-1380
symprod
P1 = k,
k
2k - 1
P2 = k2
.
k
syms k
P1 = symprod(k, k)
P2 = symprod((2*k - 1)/k^2, k)
P1 =
factorial(k)
P2 =
(1/2^(2*k)*2^(k + 1)*factorial(2*k))/(2*factorial(k)^3)
Input Arguments
f Expression defining terms of series
symbolic expression | symbolic function | symbolic vector | symbolic matrix | symbolic
number
k Product index
symbolic variable
Product index, specified as a symbolic variable. If you do not specify this variable,
symprod uses the default variable that symvar(expr,1) determines. If f is a constant,
then the default variable is x.
4-1381
4 Functions Alphabetical List
More About
Definite Product
b
xi = xa xa +1 xb
i= a
Indefinite Product
f ( i) = xi
i
is called the indefinite product of xi over i, if the following identity holds for all values of
i:
f ( i + 1)
= xi
f ( i)
See Also
cumprod | cumsum | int | syms | symsum | symvar
Introduced in R2011b
4-1382
symReadSSCParameters
symReadSSCParameters
Load parameters from Simscape component
Syntax
[names,values,units] = symReadSSCParameters(componentName)
Description
[names,values,units] = symReadSSCParameters(componentName) returns cell
arrays containing the names, values, and units of all parameters from the Simscape
component called componentName.
Examples
Parameters of Simscape Component
Load the names, values, and units of the parameters of a Simscape component.
Suppose you have the Simscape component friction.ssc in your current folder.
type('friction.ssc');
parameters
brkwy_trq = { 25, 'N*m' }; % Breakaway friction torque
Col_trq = { 20, 'N*m' }; % Coulomb friction torque
visc_coef = { 0.001, 'N*m*s/rad' }; % Viscous friction coefficient
trans_coef = { 10, 's/rad' }; % Transition approximation coefficient
vel_thr = { 1e-4, 'rad/s' }; % Linear region velocity threshold
end
parameters (Access=private)
brkwy_trq_th = { 24.995, 'N*m' }; % Breakaway torque at threshold velocity
end
4-1383
4 Functions Alphabetical List
function setup
% Parameter range checking
if brkwy_trq <= 0
pm_error('simscape:GreaterThanZero','Breakaway friction torque' )
end
if Col_trq <= 0
pm_error('simscape:GreaterThanZero','Coulomb friction torque' )
end
if Col_trq > brkwy_trq
pm_error('simscape:LessThanOrEqual','Coulomb friction torque',...
'Breakaway friction torque')
end
if visc_coef < 0
pm_error('simscape:GreaterThanOrEqualToZero','Viscous friction coefficient')
end
if trans_coef <= 0
pm_error('simscape:GreaterThanZero','Transition approximation coefficient')
end
if vel_thr <= 0
pm_error('simscape:GreaterThanZero','Linear region velocity threshold')
end
equations
if (abs(w) <= vel_thr)
% Linear region
t == brkwy_trq_th * w / vel_thr;
elseif w > 0
t == visc_coef * w + Col_trq + ...
(brkwy_trq - Col_trq) * exp(-trans_coef * w);
else
t == visc_coef * w - Col_trq - ...
(brkwy_trq - Col_trq) * exp(-trans_coef * abs(w));
end
end
end
Load the names, values, and units of the parameters of the component friction.ssc.
[names,values,units] = symReadSSCParameters('friction.ssc');
4-1384
symReadSSCParameters
In this example, all elements of the resulting cell arrays are scalars. You can convert the
cell arrays to symbolic vectors.
names_sym = cell2sym(names)
names_sym =
[ Col_trq, brkwy_trq, brkwy_trq_th, trans_coef, vel_thr, visc_coef]
values_sym = cell2sym(values)
values_sym =
[ 20, 25, 4999/200, 10, 1/10000, 1/1000]
Create individual symbolic variables from the elements of the cell array names in
the MATLAB workspace. This command creates the symbolic variables Col_trq,
brkwy_trq, brkwy_trq_th, trans_coef, vel_thr, and visc_coef as sym objects in
the workspace.
syms(names)
Input Arguments
componentName Simscape component name
file name enclosed in single quotes
Output Arguments
names Names of all parameters of Simscape component
cell array
4-1385
4 Functions Alphabetical List
See Also
symReadSSCVariables | symWriteSSC
Introduced in R2016a
4-1386
symReadSSCVariables
symReadSSCVariables
Load variables from Simscape component
Syntax
[names,values,units] = symReadSSCVariables(componentName)
[names,values,units] = symReadSSCVariables(componentName,Name,Value)
Description
[names,values,units] = symReadSSCVariables(componentName) returns
cell arrays containing the names, values, and units of all variables from the Simscape
component called componentName.
[names,values,units] = symReadSSCVariables(componentName,Name,Value)
uses additional options specified by Name,Value pair arguments.
Examples
Variables of Simscape Component
Load the names, values, and units of the variables of a Simscape component.
Suppose you have the Simscape component friction.ssc in your current folder.
type('friction.ssc');
parameters
brkwy_trq = { 25, 'N*m' }; % Breakaway friction torque
Col_trq = { 20, 'N*m' }; % Coulomb friction torque
visc_coef = { 0.001, 'N*m*s/rad' }; % Viscous friction coefficient
trans_coef = { 10, 's/rad' }; % Transition approximation coefficient
vel_thr = { 1e-4, 'rad/s' }; % Linear region velocity threshold
end
parameters (Access=private)
brkwy_trq_th = { 24.995, 'N*m' }; % Breakaway torque at threshold velocity
4-1387
4 Functions Alphabetical List
end
function setup
% Parameter range checking
if brkwy_trq <= 0
pm_error('simscape:GreaterThanZero','Breakaway friction torque' )
end
if Col_trq <= 0
pm_error('simscape:GreaterThanZero','Coulomb friction torque' )
end
if Col_trq > brkwy_trq
pm_error('simscape:LessThanOrEqual','Coulomb friction torque',...
'Breakaway friction torque')
end
if visc_coef < 0
pm_error('simscape:GreaterThanOrEqualToZero','Viscous friction coefficient')
end
if trans_coef <= 0
pm_error('simscape:GreaterThanZero','Transition approximation coefficient')
end
if vel_thr <= 0
pm_error('simscape:GreaterThanZero','Linear region velocity threshold')
end
equations
if (abs(w) <= vel_thr)
% Linear region
t == brkwy_trq_th * w / vel_thr;
elseif w > 0
t == visc_coef * w + Col_trq + ...
(brkwy_trq - Col_trq) * exp(-trans_coef * w);
else
t == visc_coef * w - Col_trq - ...
(brkwy_trq - Col_trq) * exp(-trans_coef * abs(w));
end
end
end
4-1388
symReadSSCVariables
Load the names, values, and units of the variables of the component friction.ssc.
[names,values,units] = symReadSSCVariables('friction.ssc');
In this example, all elements of the resulting cell arrays are scalars. You can convert the
cell arrays to symbolic vectors.
names_sym = cell2sym(names)
names_sym =
[ t, w]
values_sym = cell2sym(values)
values_sym =
[ 0, 0]
Create individual symbolic variables from the elements of the cell array names in the
MATLAB workspace. This command creates the symbolic variables t and w as sym
objects in the workspace.
syms(names)
Load the names of the variables of a Simscape component while converting them to
symbolic functions of the variable t.
Suppose you have the Simscape component source.ssc in your current folder.
type('source.ssc');
component source
% Electrical Source
% Defines an electrical source with positive and negative external nodes.
% Also defines associated through and across variables.
nodes
p = foundation.electrical.electrical; % :top
n = foundation.electrical.electrical; % :bottom
end
variables(Access=protected)
i = { 0, 'A' }; % Current
v = { 0, 'V' }; % Voltage
4-1389
4 Functions Alphabetical List
end
branches
i : p.i -> n.i;
end
equations
v == p.v - n.v;
end
end
Load the names the variables of the component source.ssc setting ReturnFunction
to true.
[names,~,~] = symReadSSCVariables('source.ssc','ReturnFunction',true);
In this example, all elements of the resulting cell arrays are scalars. You can convert the
cell arrays to symbolic vectors.
names_symfun = cell2sym(names)
names_symfun =
[ i(t), v(t)]
Create individual symbolic functions from the elements of the cell array names in the
MATLAB workspace. This command creates the symbolic functions i and v as symfun
objects, and their variable t as a sym object in the workspace.
syms(names)
Input Arguments
componentName Simscape component name
file name enclosed in single quotes
4-1390
symReadSSCVariables
Output Arguments
names Names of all variables of Simscape component
cell array
See Also
symReadSSCParameters | symWriteSSC
4-1391
4 Functions Alphabetical List
Introduced in R2016a
4-1392
syms
syms
Create symbolic variables and functions
Syntax
syms var1 ... varN
syms var1 ... varN set
syms var1 ... varN clear
syms f(var1,...,varN)
syms(symArray)
syms
Description
syms var1 ... varN creates symbolic variables var1 ... varN. Separate variables
by spaces.
syms var1 ... varN set sets an assumption that the created symbolic variables
belong to a set.
syms var1 ... varN clear clears assumptions set on a symbolic variables var1 ...
varN.
syms without input arguments lists all symbolic variables, functions, vectors, and
matrices currently existing in the MATLAB workspace.
4-1393
4 Functions Alphabetical List
Examples
syms x y
syms x y integer
Check assumptions.
assumptions
ans =
[ in(x, 'integer'), in(y, 'integer')]
Alternatively, check assumptions on each variable. For example, check assumptions set
on the variable x.
assumptions(x)
ans =
in(x, 'integer')
assume([x y],'clear')
assumptions
ans =
Empty sym: 1-by-0
4-1394
syms
Both s and f are abstract symbolic functions. They do not have symbolic expressions
assigned to them, so the bodies of these functions are s(t) and f(x,y), respectively.
f(x,y) = x + 2*y
f(x, y) =
x + 2*y
f(1,2)
ans =
5
syms x
f(x) = [x x^3; x^2 x^4]
f(x) =
[ x, x^3]
[ x^2, x^4]
f(2)
ans =
[ 2, 8]
[ 4, 16]
Compute the value of this function for x = [1 2 3; 4 5 6]. The result is a cell array
of symbolic matrices.
y = f([1 2 3; 4 5 6])
y =
4-1395
4 Functions Alphabetical List
22 cell array
[23 sym] [23 sym]
[23 sym] [23 sym]
y{1}
ans =
[ 1, 2, 3]
[ 4, 5, 6]
Solve the equation sin(x) == 1 by using solve. The parameter k in the solution does
not appear in the MATLAB workspace.
syms x
[sol, parameter, condition] = solve(sin(x) == 1, x, 'ReturnConditions', true);
parameter
parameter =
k
Create the parameter k by using syms. The parameter k now appears in the MATLAB
workspace.
syms(parameter)
Similarly, use syms to create the symbolic objects contained in a vector or cell
array. Examples of functions that return a cell array of symbolic objects are
symReadSSCVariables and symReadSSCParameters.
4-1396
syms
Use syms without input arguments to print a list of all symbolic objects that currently
exist in the MATLAB workspace.
syms
'A' 'B' 'a' 'b' 'c' 'f' 'g' 's' 't' 'x' 'y'
Input Arguments
var1 ... varN Symbolic variables
valid variable names separated by spaces
Symbolic variables, specified as valid variable names separated by spaces. Each variable
name must begin with a letter and can contain only alphanumeric characters and
underscores. To verify that the name is a valid variable name, use isvarname.
Example: x y123 z_1
Symbolic function with its input arguments, specified as an expression with parentheses.
The function name f and the variable names var1...varN must be valid variable
names. That is, they must begin with a letter and can contain only alphanumeric
characters and underscores. To verify that the name is a valid variable name, use
isvarname.
Example: s(t), f(x,y)
4-1397
4 Functions Alphabetical List
More About
Tips
syms is a shortcut for sym. This shortcut lets you create several symbolic variables in
one function call. Alternatively, you can use sym and create each variable separately.
You also can use symfun to create symbolic functions.
In functions and scripts, do not use syms to create symbolic variables with the same
names as MATLAB functions. For these names MATLAB does not create symbolic
variables, but keeps the names assigned to the functions. If you want to create a
symbolic variable with the same name as a MATLAB function inside a function or a
script, use sym. For example, use alpha = sym('alpha').
The following variable names are invalid with syms: integer, real, rational,
positive and clear. To create variables with these names use sym. For example,
real = sym('real').
clear x does not clear the symbolic object of its assumptions, such as real, positive,
or any assumptions set by assume, sym, or syms. To remove assumptions, use one of
these options:
A = eye(3);
A(1,1) = sym('pi')
A =
3.1416 0 0
0 1.0000 0
0 0 1.0000
4-1398
syms
You cannot replace elements of a numeric vector or matrix with a symbolic variable,
expression, or function because these elements cannot be converted to double-
precision numbers. For example, syms a; A(1,1) = a throws an error.
See Also
assume | assumeAlso | assumptions | clear all | reset | sym | symfun |
symvar
4-1399
4 Functions Alphabetical List
symsum
Sum of series
Syntax
F = symsum(f,k,a,b)
F = symsum(f,k)
Description
F = symsum(f,k,a,b) returns the sum of the series with terms that expression f
specifies, which depend on symbolic variable k. The value of k ranges from a to b. If you
do not specify the variable, symsum uses the variable that symvar determines. If f is a
constant, then the default variable is x.
F = symsum(f,k) returns the indefinite sum F of the series with terms that expression
f specifies, which depend on variable k. The f argument defines the series such that the
indefinite sum F is given by F(k+1) - F(k) = f(k). If you do not specify the variable,
symsum uses the variable that symvar determines. If f is a constant, then the default
variable is x.
Examples
Find Sum of Series Specifying Bounds
Find the following sums of series.
10
S1 = k2
k= 0
1
S2 = k2
k= 1
k
x
S3 = k!
k= 1
4-1400
symsum
syms k x
S1 = symsum(k^2, k, 0, 10)
S2 = symsum(1/k^2, k, 1, Inf)
S3 = symsum(x^k/factorial(k), k, 0, Inf)
S1 =
385
S2 =
pi^2/6
S3 =
exp(x)
S1 = symsum(k^2, k, [0 10])
S2 = symsum(1/k^2, k, [1; Inf])
S3 = symsum(x^k/factorial(k), k, [0 Inf])
S1 =
385
S2 =
pi^2/6
S3 =
exp(x)
syms k
symsum(k, k)
symsum(1/k^2, k)
ans =
k^2/2 - k/2
ans =
-psi(1, k)
4-1401
4 Functions Alphabetical List
10
1
S= k2 .
k= 1
Contrast symsum and sum by summing this definite sum using both functions.
syms k
S_sum = sum(subs(1/k^2, k, 1:10))
S_symsum = symsum(1/k^2, k, 1, 10)
S_sum =
1968329/1270080
S_symsum =
1968329/1270080
For details on sum, see the information on the MATLAB sum page.
Input Arguments
f Expression defining terms of series
symbolic expression | symbolic function | symbolic vector | symbolic matrix | symbolic
number
k Summation index
symbolic variable
Summation index, specified as a symbolic variable. If you do not specify this variable,
symsum uses the default variable determined by symvar(expr,1). If f is a constant,
then the default variable is x.
4-1402
symsum
More About
Definite Sum
b
xk = xa + xa+1 + + xb.
k =a
Indefinite Sum
F( x) = f ( x ),
x
such that
F ( x + 1 ) - F ( x ) = f ( x) .
See Also
cumsum | int | sum | symprod | syms | symvar
4-1403
4 Functions Alphabetical List
symvar
Find symbolic variables in symbolic expression, matrix, or function
Syntax
symvar(s)
symvar(s,n)
Description
Input Arguments
s
Examples
Find all symbolic variables in the sum:
syms wa wb wx yx ya yb
symvar(wa + wb + wx + ya + yb + yx)
4-1404
symvar
ans =
[ wa, wb, wx, ya, yb, yx]
syms x y a b
f(a, b) = a*x^2/(sin(3*y - b));
symvar(f)
ans =
[ a, b, x, y]
Now find the first three symbolic variables in f. For a symbolic function, symvar with
two arguments returns the function inputs in front of other variables:
symvar(f, 3)
ans =
[ a, b, x]
For a symbolic expression or matrix, symvar with two arguments returns variables
sorted by their proximity to x:
symvar(a*x^2/(sin(3*y - b)), 3)
ans =
[ x, y, b]
syms v z
g = v + z;
symvar(g, 1)
ans =
z
ans =
aaa
syms X1 x2 xa xb
g = X1 + x2 + xa + xb;
4-1405
4 Functions Alphabetical List
symvar(g, 1)
ans =
x2
More About
Tips
Algorithms
When sorting the symbolic variables by their proximity to x, symvar uses this algorithm:
1 The variables are sorted by the first letter in their names. The ordering is
x y w z v u ... a X Y W Z V U ... A. The name of a symbolic variable cannot begin with
a number.
2 For all subsequent letters, the ordering is alphabetical, with all uppercase letters
having precedence over lowercase: 0 1 ... 9 A B ... Z a b ... z.
See Also
sym | symfun | syms
Introduced in R2008b
4-1406
symWriteSSC
symWriteSSC
Create new Simscape component
Syntax
symWriteSSC(newComponentName,templateComponentName,eqns)
symWriteSSC(newComponentName,templateComponentName,eqns,Name,Value)
Description
symWriteSSC(newComponentName,templateComponentName,eqns) creates
a new Simscape component newComponentName using an existing component
templateComponentName as a template and adding eqns. Thus, the new component
has both the existing equations taken from the template component and the added
equations.
symWriteSSC(newComponentName,templateComponentName,eqns,Name,Value)
uses additional options specified by one or more Name,Value pair arguments.
Examples
Create Component with Additional Equation
Suppose you have the Simscape component spring.ssc in your current folder.
type('spring.ssc');
parameters
spr_rate = { 10, 'N*m/rad' };
end
variables
4-1407
4 Functions Alphabetical List
function setup
if spr_rate <= 0
pm_error('simscape:GreaterThanZero','Spring rate' )
end
end
equations
w == phi.der;
t == spr_rate*phi;
end
end
Create symbolic variables with names of the parameters and variables of the component
you are going to use when creating new equations. Also create a symbolic variable, u, to
denote the energy of the rotational spring.
syms spr_rate phi u
component myRotationalSpring
parameters
spr_rate = { 10, 'N*m/rad' };
end
variables
phi = { value = { 0, 'rad'}, priority = priority.high };
4-1408
symWriteSSC
end
function setup
if spr_rate <= 0
pm_error('simscape:GreaterThanZero','Spring rate' )
end
end
equations
w == phi.der;
t == spr_rate*phi;
u == phi^2*spr_rate*(1.0/2.0);
end
end
Create a Simscape component with the title and descriptive text different from those of
the template component.
Suppose you have the Simscape component spring.ssc in your current folder. This
component does not have any title or descriptive text.
type('spring.ssc');
parameters
spr_rate = { 10, 'N*m/rad' };
end
variables
phi = { value = { 0, 'rad'}, priority = priority.high };
end
function setup
if spr_rate <= 0
pm_error('simscape:GreaterThanZero','Spring rate' )
end
end
equations
w == phi.der;
t == spr_rate*phi;
4-1409
4 Functions Alphabetical List
end
end
Create symbolic variables with names of the parameters and variables of the component
you are going to use when creating new equations. Also create a symbolic variable, u, to
denote the energy of the rotational spring.
syms spr_rate phi u
eq = u == spr_rate*phi^2/2;
type('myRotationalSpring.ssc');
component myRotationalSpring
% Rotational Spring
% The block represents an ideal mechanical rotational linear spring.
% Connections R and C are mechanical rotational conserving ports.
% The block positive direction is from port R to port C. This means
% that the torque is positive if it acts in the direction from R to C.
parameters
spr_rate = { 10, 'N*m/rad' };
end
variables
phi = { value = { 0, 'rad'}, priority = priority.high };
4-1410
symWriteSSC
end
function setup
if spr_rate <= 0
pm_error('simscape:GreaterThanZero','Spring rate' )
end
end
equations
w == phi.der;
t == spr_rate*phi;
u == phi^2*spr_rate*(1.0/2.0);
end
end
Input Arguments
newComponentName Name of Simscape component to create
file name enclosed in single quotes
Name of Simscape component to create, specified as a file name enclosed in single quotes.
File must have the extension .ssc. If you do not provide file extension, symWriteSSC
assumes it to be .ssc. If you do not specify the absolute path, symWriteSSC creates the
new component in the current folder.
Example: 'MyNewComponent.ssc'
4-1411
4 Functions Alphabetical List
'H1Header' Title
row vector of characters
Title specified as a row vector of characters (type char) starting with %. If the first
character is not %, then symWriteSSC adds %.
If the template component has a title and you use H1Header, the new component will
have the title specified by H1Header. If the template component has a title and you call
symWriteSSC without H1Header, the new component will have the same title as the
template component.
Example: 'H1Header','% New title'
Descriptive text, specified as a cell array of row vectors of characters. Each row vector
must start with %. If the first character is not %, then symWriteSSC adds %.
If the template component has descriptive text and you use HelpText, the new
component will have only the text specified by HelpText. In this case, symWriteSSC
does not copy the descriptive text of the template component to the new component. If the
template component has a title and you call symWriteSSC without HelpText, the new
component will have the same descriptive text as the template component.
Example: 'HelpText',{'% Description of the','% new component'}
See Also
symReadSSCParameters | symReadSSCVariables
4-1412
symWriteSSC
Introduced in R2016a
4-1413
4 Functions Alphabetical List
tan
Symbolic tangent function
Syntax
tan(X)
Description
tan(X) returns the tangent function of X.
Examples
Compute the tangent function for these numbers. Because these numbers are not
symbolic objects, tan returns floating-point results.
A =
2.1850 0.0000 0.5774 -1.2540 -225.9508
Compute the tangent function for the numbers converted to symbolic objects. For many
symbolic (exact) numbers, tan returns unresolved symbolic calls.
symA =
[ -tan(2), 0, 3^(1/2)/3, -tan((2*pi)/7), tan(11)]
4-1414
tan
vpa(symA)
ans =
[ 2.1850398632615189916433061023137,...
0,...
0.57735026918962576450914878050196,...
-1.2539603376627038375709109783365,...
-225.95084645419514202579548320345]
syms x
fplot(tan(x), [-pi, pi])
grid on
4-1415
4 Functions Alphabetical List
syms x
diff(tan(x), x)
diff(tan(x), x, x)
ans =
tan(x)^2 + 1
4-1416
tan
ans =
2*tan(x)*(tan(x)^2 + 1)
ans =
-log(cos(x))
ans =
(2*x^5)/15 + x^3/3 + x
Rewrite the tangent function in terms of the sine and cosine functions:
rewrite(tan(x), 'sincos')
ans =
sin(x)/cos(x)
ans =
-(exp(x*2i)*1i - 1i)/(exp(x*2i) + 1)
Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
See Also
acos | acot | acsc | asec | asin | atan | cos | cot | csc | sec | sin
4-1417
4 Functions Alphabetical List
4-1418
tanh
tanh
Symbolic hyperbolic tangent function
Syntax
tanh(X)
Description
tanh(X) returns the hyperbolic tangent function of X.
Examples
Compute the hyperbolic tangent function for these numbers. Because these numbers are
not symbolic objects, tanh returns floating-point results.
A =
-0.9640 + 0.0000i 0.0000 + 0.0000i 0.0000 + 0.5774i...
0.0000 + 1.7321i 0.0000 - 1.2540i
Compute the hyperbolic tangent function for the numbers converted to symbolic objects.
For many symbolic (exact) numbers, tanh returns unresolved symbolic calls.
symA =
[ -tanh(2), 0, (3^(1/2)*1i)/3, 3^(1/2)*1i, -tanh((pi*2i)/7)]
4-1419
4 Functions Alphabetical List
vpa(symA)
ans =
[ -0.96402758007581688394641372410092,...
0,...
0.57735026918962576450914878050196i,...
1.7320508075688772935274463415059i,...
-1.2539603376627038375709109783365i]
syms x
fplot(tanh(x), [-pi, pi])
grid on
4-1420
tanh
Find the first and second derivatives of the hyperbolic tangent function:
syms x
diff(tanh(x), x)
diff(tanh(x), x, x)
ans =
1 - tanh(x)^2
4-1421
4 Functions Alphabetical List
ans =
2*tanh(x)*(tanh(x)^2 - 1)
ans =
log(cosh(x))
taylor(tanh(x), x)
ans =
(2*x^5)/15 - x^3/3 + x
ans =
(exp(2*x) - 1)/(exp(2*x) + 1)
Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix
See Also
acosh | acoth | acsch | asech | asinh | atanh | cosh | coth | csch | sech |
sinh
4-1422
taylor
taylor
Taylor series
Syntax
taylor(f,var)
taylor(f,var,a)
taylor( ___ ,Name,Value)
Description
taylor(f,var) approximates f with the Taylor series expansion of f up to the fifth
order at the point var = 0. If you do not specify var, then taylor uses the default
variable determined by symvar(f,1).
Examples
Find Maclaurin Series of Univariate Expressions
Find the Maclaurin series expansions of these functions.
syms x
taylor(exp(x))
taylor(sin(x))
taylor(cos(x))
ans =
x^5/120 + x^4/24 + x^3/6 + x^2/2 + x + 1
ans =
4-1423
4 Functions Alphabetical List
x^5/120 - x^3/6 + x
ans =
x^4/24 - x^2/2 + 1
ans =
x - (x - 1)^2/2 + (x - 1)^3/3 - (x - 1)^4/4 + (x - 1)^5/5 - 1
ans =
pi/4 - x/2 + (x - 1)^2/4 - (x - 1)^3/12 + (x - 1)^5/40 + 1/2
t6 =
x^4/120 - x^2/6 + 1
Use Order to control the truncation order. For example, approximate the same
expression up to the orders 8 and 10:
t8 = taylor(f, x, 'Order', 8)
t10 = taylor(f, x, 'Order', 10)
t8 =
- x^6/5040 + x^4/120 - x^2/6 + 1
t10 =
4-1424
taylor
Plot the original expression f and its approximations t6, t8, and t10. Note how the
accuracy of the approximation depends on the truncation order.
4-1425
4 Functions Alphabetical List
ans =
-x^3/3
Fnd the Taylor series expansion with a relative truncation order by using
OrderMode. For some expressions, a relative truncation order provides more accurate
approximations.
taylor(1/(exp(x)) - exp(x) + 2*x, x, 'Order', 5, 'OrderMode', 'relative')
ans =
- x^7/2520 - x^5/60 - x^3/3
ans =
x^5/120 - x^3/6 + x + cos(y) + exp(z)
ans =
x^5/120 - x^3/6 + x + y^4/24 - y^2/2 + z^5/120 + z^4/24 + z^3/6 + z^2/2 + z + 2
4-1426
taylor
f = y*exp(x - 1) - x*log(y);
taylor(f, [x, y], [1, 1], 'Order', 3)
ans =
x + (x - 1)^2/2 + (y - 1)^2/2
If you specify the expansion point as a scalar a, taylor transforms that scalar into a
vector of the same length as the vector of variables. All elements of the expansion vector
equal a:
taylor(f, [x, y], 1, 'Order', 3)
ans =
x + (x - 1)^2/2 + (y - 1)^2/2
Input Arguments
f Input to approximate
symbolic expression | symbolic function | symbolic vector | symbolic matrix | symbolic
multidimensional array
Expansion variable, specified as a symbolic variable. If you do not specify var, then
taylor uses the default variable determined by symvar(f,1).
a Expansion point
0 (default) | number | symbolic number | symbolic variable | symbolic function |
symbolic expression
4-1427
4 Functions Alphabetical List
quotes (' '). You can specify several name and value pair arguments in any order as
Name1,Value1,...,NameN,ValueN.
Example: taylor(log(x),x,'ExpansionPoint',1,'Order',9)
Absolute order is the truncation order of the computed series. Relative order n means
that the exponents of var in the computed series range from the leading order m to
the highest exponent m + n - 1. Here m + n is the exponent of var in the O-term:
O(varm+n).
More About
Taylor Series Expansion
Taylor series expansion represents an analytic function f(x) as an infinite sum of terms
around the expansion point x=a:
4-1428
taylor
f ( a) ( f ( a) ( 2 f ( m) ( a) ( m
f ( x) = f ( a) + x - a) + x - a) + = x - a)
1! 2! m =0 m !
f (0) f ( 0 ) 2 f (m ) (0) m
f ( x) = f ( 0 ) + x+ x + = x
1! 2! m =0 m!
Tips
If you use both the third argument a and ExpansionPoint to specify the expansion
point, the value specified via ExpansionPoint prevails.
If var is a vector, then the expansion point a must be a scalar or a vector of the same
length as var. If var is a vector and a is a scalar, then a is expanded into a vector of
the same length as var with all elements equal to a.
If the expansion point is infinity or negative infinity, then taylor computes the
Laurent series expansion, which is a power series in 1/var.
See Also
pade | series | symvar
4-1429
4 Functions Alphabetical List
taylortool
Taylor series calculator
Syntax
taylortool
taylortool('f')
Description
taylortool initiates a GUI that graphs a function against the Nth partial sum of its
Taylor series about a base point x = a. The default function, value of N, base point,
and interval of computation for taylortool are f = x*cos(x), N = 7, a = 0, and
[-2*pi,2*pi], respectively.
Examples
Open Taylor Series Calculator For Particular Expression
taylortool('sin(tan(x)) - tan(sin(x))')
4-1430
taylortool
More About
Taylor Series on page 2-33
See Also
funtool | rsums
4-1431
4 Functions Alphabetical List
4-1432
texlabel
texlabel
TeX representation of symbolic expression
Syntax
texlabel(expr)
texlabel(expr,'literal')
Description
texlabel(expr) converts the symbolic expression expr into the TeX equivalent for
use in character vectors. texlabel converts Greek variable names, such as delta, into
Greek letters. Annotation functions, such as title, xlabel, and text can use the TeX
character vector as input. To obtain the LaTeX representation, use latex.
Examples
ans =
120 char array
{sin}({x}) + {x}^{3}
ans =
154 char array
4-1433
4 Functions Alphabetical List
ans =
157 char array
{\lambda_{12}}^{{3}/{2}}/{\pi} - {\delta}^{{2}/{3}} {\pi}
To make texlabel interpret Greek variable names literally, include the argument
'literal'.
texlabel(lambda12,'literal')
ans =
110 char array
{lambda12}
syms x
y = x^2;
fplot(y)
ylabel = texlabel(y);
text(1, 15, ['y = ' ylabel]);
4-1434
texlabel
Input Arguments
expr Expression to be converted
symbolic expression
See Also
latex | text | title | xlabel | ylabel | zlabel
4-1435
4 Functions Alphabetical List
times, .*
Symbolic array multiplication
Syntax
A.*B
times(A,B)
Description
A.*B performs elementwise multiplication of A and B.
Examples
A = sym('a', [2 3])
A =
[ a1_1, a1_2, a1_3]
[ a2_1, a2_2, a2_3]
Multiply the matrix by the symbolic expression sin(b). Multiplying a matrix by a scalar
means multiplying each element of the matrix by that scalar.
syms b
A.*sin(b)
ans =
[ a1_1*sin(b), a1_2*sin(b), a1_3*sin(b)]
[ a2_1*sin(b), a2_2*sin(b), a2_3*sin(b)]
4-1436
times, .*
H =
[ 1, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]
d =
[ 1, 0, 0]
[ 0, 2, 0]
[ 0, 0, 3]
Multiply the matrices by using the elementwise multiplication operator .*. This operator
multiplies each element of the first matrix by the corresponding element of the second
matrix. The dimensions of the matrices must be the same.
H.*d
ans =
[ 1, 0, 0]
[ 0, 2/3, 0]
[ 0, 0, 3/5]
f1(x) =
x^2*(x^2 + 5*x + 6)
Input Arguments
A Input
number | symbolic number | symbolic variable | symbolic vector | symbolic matrix |
symbolic multidimensional array | symbolic function | symbolic expression
4-1437
4 Functions Alphabetical List
B Input
number | symbolic number | symbolic variable | symbolic vector | symbolic matrix |
symbolic multidimensional array | symbolic function | symbolic expression
See Also
ctranspose | ldivide | minus | mldivide | mpower | mrdivide | mtimes | plus
| power | rdivide | transpose
4-1438
toeplitz
toeplitz
Symbolic Toeplitz matrix
Syntax
toeplitz(c,r)
toeplitz(r)
Description
Input Arguments
c
Examples
Generate the Toeplitz matrix from these vectors. Because these vectors are not symbolic
objects, you get floating-point results.
4-1439
4 Functions Alphabetical List
c = [1 2 3 4 5 6];
r = [1 3/2 3 7/2 5];
toeplitz(c,r)
ans =
1.0000 1.5000 3.0000 3.5000 5.0000
2.0000 1.0000 1.5000 3.0000 3.5000
3.0000 2.0000 1.0000 1.5000 3.0000
4.0000 3.0000 2.0000 1.0000 1.5000
5.0000 4.0000 3.0000 2.0000 1.0000
6.0000 5.0000 4.0000 3.0000 2.0000
Now, convert these vectors to a symbolic object, and generate the Toeplitz matrix:
c = sym([1 2 3 4 5 6]);
r = sym([1 3/2 3 7/2 5]);
toeplitz(c,r)
ans =
[ 1, 3/2, 3, 7/2, 5]
[ 2, 1, 3/2, 3, 7/2]
[ 3, 2, 1, 3/2, 3]
[ 4, 3, 2, 1, 3/2]
[ 5, 4, 3, 2, 1]
[ 6, 5, 4, 3, 2]
T =
[ a, b, c, d]
[ conj(b), a, b, c]
[ conj(c), conj(b), a, b]
[ conj(d), conj(c), conj(b), a]
If you specify that all elements are real, then the resulting Toeplitz matrix is symmetric:
syms a b c d real
T = toeplitz([a b c d])
T =
[ a, b, c, d]
[ b, a, b, c]
[ c, b, a, b]
4-1440
toeplitz
[ d, c, b, a]
T =
[ 1, 2, 1i]
[ 2, 1, 2]
[ -1i, 2, 1]
If the first element of the vector is real, then the resulting Toeplitz matrix is Hermitian:
isAlways(T == T')
ans =
33 logical array
1 1 1
1 1 1
1 1 1
If the first element is not real, then the resulting Toeplitz matrix is Hermitian off the
main diagonal:
T = toeplitz(sym([i, 2, 1]))
T =
[ 1i, 2, 1]
[ 2, 1i, 2]
[ 1, 2, 1i]
isAlways(T == T')
ans =
33 logical array
0 1 1
1 0 1
1 1 0
Generate a Toeplitz matrix using these vectors to specify the first column and the first
row. Because the first elements of these vectors are different, toeplitz issues a warning
and uses the first element of the column:
4-1441
4 Functions Alphabetical List
syms a b c
toeplitz([a b c], [1 b/2 a/2])
Warning: First element of input column does not match first element of input row.
Column wins diagonal conflict.
ans =
[ a, b/2, a/2]
[ b, a, b/2]
[ c, b, a]
More About
Toeplitz Matrix
A Toeplitz matrix is a matrix that has constant values along each descending diagonal
from left to right. For example, matrix T is a symmetric Toeplitz matrix:
t0 t1 t2 tk
t-1 t0 t1 L
t-2 t-1 t0
T = M O M
t0 t1 t2
L t-1 t0 t1
t t-2 t-1 t0
-k
Tips
Calling toeplitz for numeric arguments that are not symbolic objects invokes the
MATLAB toeplitz function.
See Also
toeplitz
Introduced in R2013a
4-1442
transpose, .'
transpose, .'
Symbolic matrix transpose
Syntax
A.'
transpose(A)
Description
A.' computes the nonconjugate transpose of A.
Examples
Transpose of Real Matrix
Create a 2-by-3 matrix, the elements of which represent real numbers.
syms x y real
A = [x x x; y y y]
A =
[ x, x, x]
[ y, y, y]
ans =
[ x, y]
[ x, y]
[ x, y]
If all elements of a matrix represent real numbers, then its complex conjugate transform
equals its nonconjugate transform.
4-1443
4 Functions Alphabetical List
isAlways(A' == A.')
ans =
32 logical array
1 1
1 1
1 1
A =
[ x + y*1i, x - y*1i]
[ y + x*1i, y - x*1i]
Find the nonconjugate transpose of this matrix. The nonconjugate transpose operator,
A.', performs a transpose without conjugation. That is, it does not change the sign of the
imaginary parts of the elements.
A.'
ans =
[ x + y*1i, y + x*1i]
[ x - y*1i, y - x*1i]
For a matrix of complex numbers with nonzero imaginary parts, the nonconjugate
transform is not equal to the complex conjugate transform.
isAlways(A.' == A','Unknown','false')
ans =
22 logical array
0 0
0 0
Input Arguments
A Input
number | symbolic number | symbolic variable | symbolic expression | symbolic vector |
symbolic matrix | symbolic multidimensional array
4-1444
transpose, .'
More About
Nonconjugate Transpose
The nonconjugate transpose of a matrix interchanges the row and column index for
each element, reflecting the elements across the main diagonal. The diagonal elements
themselves remain unchanged. This operation does not affect the sign of the imaginary
parts of complex elements.
For example, if B = A.' and A(3,2) is 1+1i, then the element B(2,3) is 1+1i.
See Also
ctranspose | ldivide | minus | mldivide | mpower | mrdivide | mtimes | plus
| power | rdivide | times
4-1445
4 Functions Alphabetical List
triangularPulse
Triangular pulse function
Syntax
triangularPulse(a,b,c,x)
triangularPulse(a,c,x)
triangularPulse(x)
Description
triangularPulse(a,b,c,x) returns the triangular pulse function.
Input Arguments
a
Default: -1
4-1446
triangularPulse
Default: 1
Examples
[triangularPulse(-2, 0, 2, -3)
triangularPulse(-2, 0, 2, -1/2)
triangularPulse(-2, 0, 2, 0)
triangularPulse(-2, 0, 2, 3/2)
triangularPulse(-2, 0, 2, 3)]
ans =
0
0.7500
1.0000
0.2500
0
Compute the triangular pulse function for the numbers converted to symbolic objects:
[triangularPulse(sym(-2), 0, 2, -3)
triangularPulse(-2, 0, 2, sym(-1/2))
triangularPulse(-2, sym(0), 2, 0)
triangularPulse(-2, 0, 2, sym(3/2))
triangularPulse(-2, 0, sym(2), 3)]
ans =
0
3/4
1
1/4
0
4-1447
4 Functions Alphabetical List
ans =
(a - x)/(a - b)
ans =
-(c - x)/(b - c)
ans =
-((c - x)*rectangularPulse(b, c, x))/(b - c)
ans =
((a - x)*rectangularPulse(a, b, x))/(a - b)
4-1448
triangularPulse
syms x
triangularPulse(x)
ans =
triangularPulse(-1, 0, 1, x)
[triangularPulse(sym(-10))
triangularPulse(sym(-3/4))
triangularPulse(sym(0))
triangularPulse(sym(2/3))
triangularPulse(sym(1))]
ans =
0
1/4
1
1/3
0
syms a c x
triangularPulse(a, c, x)
ans =
triangularPulse(a, a/2 + c/2, c, x)
[triangularPulse(sym(-10), 10, 3)
triangularPulse(sym(-1/2), -1/4, -2/3)
triangularPulse(sym(2), 4, 3)
triangularPulse(sym(2), 4, 6)
triangularPulse(sym(-1), 4, 0)]
ans =
7/10
0
4-1449
4 Functions Alphabetical List
1
0
2/5
4-1450
triangularPulse
syms x
triangularPulse(-1, 0, inf, x)
triangularPulse(-inf, 0, 1, x)
triangularPulse(-inf, 0, inf, x)
ans =
heaviside(x) + (x + 1)*rectangularPulse(-1, 0, x)
ans =
heaviside(-x) - (x - 1)*rectangularPulse(0, 1, x)
ans =
1
More About
Triangular Pulse Function
If a < x < b, then the triangular pulse function equals (x - a)/(b - a).
If b < x < c, then the triangular pulse function equals (c - x)/(c - b).
The triangular pulse function is also called the triangle function, hat function, tent
function, or sawtooth function.
Tips
See Also
dirac | heaviside | rectangularPulse
Introduced in R2012b
4-1451
4 Functions Alphabetical List
tril
Return lower triangular part of symbolic matrix
Syntax
tril(A)
tril(A,k)
Description
tril(A) returns a triangular matrix that retains the lower part of the matrix A. The
upper triangle of the resulting matrix is padded with zeros.
tril(A,k) returns a matrix that retains the elements of A on and below the k-th
diagonal. The elements above the k-th diagonal equal to zero. The values k = 0, k > 0,
and k < 0 correspond to the main, superdiagonals, and subdiagonals, respectively.
Examples
Display the matrix retaining only the lower triangle of the original symbolic matrix:
syms a b c
A = [a b c; 1 2 3; a + 1 b + 2 c + 3];
tril(A)
ans =
[ a, 0, 0]
[ 1, 2, 0]
[ a + 1, b + 2, c + 3]
Display the matrix that retains the elements of the original symbolic matrix on and
below the first superdiagonal:
syms a b c
A = [a b c; 1 2 3; a + 1 b + 2 c + 3];
tril(A, 1)
4-1452
tril
ans =
[ a, b, 0]
[ 1, 2, 3]
[ a + 1, b + 2, c + 3]
Display the matrix that retains the elements of the original symbolic matrix on and
below the first subdiagonal:
syms a b c
A = [a b c; 1 2 3; a + 1 b + 2 c + 3];
tril(A, -1)
ans =
[ 0, 0, 0]
[ 1, 0, 0]
[ a + 1, b + 2, 0]
See Also
diag | triu
4-1453
4 Functions Alphabetical List
triu
Return upper triangular part of symbolic matrix
Syntax
triu(A)
triu(A,k)
Description
triu(A) returns a triangular matrix that retains the upper part of the matrix A. The
lower triangle of the resulting matrix is padded with zeros.
triu(A,k) returns a matrix that retains the elements of A on and above the k-th
diagonal. The elements below the k-th diagonal equal to zero. The values k = 0, k > 0,
and k < 0 correspond to the main, superdiagonals, and subdiagonals, respectively.
Examples
Display the matrix retaining only the upper triangle of the original symbolic matrix:
syms a b c
A = [a b c; 1 2 3; a + 1 b + 2 c + 3];
triu(A)
ans =
[ a, b, c]
[ 0, 2, 3]
[ 0, 0, c + 3]
Display the matrix that retains the elements of the original symbolic matrix on and
above the first superdiagonal:
syms a b c
A = [a b c; 1 2 3; a + 1 b + 2 c + 3];
triu(A, 1)
4-1454
triu
ans =
[ 0, b, c]
[ 0, 0, 3]
[ 0, 0, 0]
Display the matrix that retains the elements of the original symbolic matrix on and
above the first subdiagonal:
syms a b c
A = [a b c; 1 2 3; a + 1 b + 2 c + 3];
triu(A, -1)
ans =
[ a, b, c]
[ 1, 2, 3]
[ 0, b + 2, c + 3]
See Also
diag | tril
4-1455
4 Functions Alphabetical List
uint8uint16uint32uint64
Convert symbolic matrix to unsigned integers
Syntax
uint8(S)
uint16(S)
uint32(S)
uint64(S)
Description
uint8(S) converts a symbolic matrix S to a matrix of unsigned 8-bit integers.
Note The output of uint8, uint16, uint32, and uint64 does not have type symbolic.
4-1456
uint8uint16uint32uint64
See Also
sym | vpa | single | int8 | int16 | int32 | int64 | double
4-1457
4 Functions Alphabetical List
vectorPotential
Vector potential of vector field
Syntax
vectorPotential(V,X)
vectorPotential(V)
Description
vectorPotential(V,X) computes the vector potential of the vector field V with respect
to the vector X in Cartesian coordinates. The vector field V and the vector X are both
three-dimensional.
Input Arguments
V
Three-dimensional vector with respect to which you compute the vector potential.
Examples
Compute the vector potential of this row vector field with respect to the vector [x, y,
z]:
syms x y z
vectorPotential([x^2*y, -1/2*y^2*x, -x*y*z], [x y z])
4-1458
vectorPotential
ans =
-(x*y^2*z)/2
-x^2*y*z
0
Compute the vector potential of this column vector field with respect to the vector [x,
y, z]:
syms x y z
f(x,y,z) = 2*y^3 - 4*x*y;
g(x,y,z) = 2*y^2 - 16*z^2+18;
h(x,y,z) = -32*x^2 - 16*x*y^2;
A = vectorPotential([f; g; h], [x y z])
A(x, y, z) =
z*(2*y^2 + 18) - (16*z^3)/3 + (16*x*y*(y^2 + 6*x))/3
2*y*z*(- y^2 + 2*x)
0
To check whether the vector potential exists for a particular vector field, compute the
divergence of that vector field:
syms x y z
V = [x^2 2*y z];
divergence(V, [x y z])
ans =
2*x + 3
If the divergence is not equal to 0, the vector potential does not exist. In this case,
vectorPotential returns the vector with all three components equal to NaN:
vectorPotential(V, [x y z])
ans =
NaN
NaN
NaN
More About
Vector Potential of a Vector Field
4-1459
4 Functions Alphabetical List
V = A = curl( A)
Tips
The vector potential exists if and only if the divergence of a vector field V with respect
to X equals 0. If vectorPotential cannot verify that V has a vector potential, it
returns the vector with all three components equal to NaN.
See Also
curl | diff | divergence | gradient | hessian | jacobian | laplacian |
potential
Introduced in R2012a
4-1460
vertcat
vertcat
Concatenate symbolic arrays vertically
Syntax
vertcat(A1,...,AN)
[A1;...;AN]
Description
vertcat(A1,...,AN) vertically concatenates the symbolic arrays A1,...,AN.
For vectors and matrices, all inputs must have the same number of columns. For
multidimensional arrays, vertcat concatenates inputs along the first dimension. The
remaining dimensions must match.
Examples
A = sym('a%d',[1 4]);
B = sym('b%d',[1 4]);
vertcat(A,B)
ans =
[ a1, a2, a3, a4]
[ b1, b2, b3, b4]
[A;B]
ans =
4-1461
4 Functions Alphabetical List
A = sym('a%d',[1 3]);
B = sym('b%d%d',[4 3]);
C = sym('c%d%d',[2 3]);
vertcat(C,A,B)
ans =
[ c11, c12, c13]
[ c21, c22, c23]
[ a1, a2, a3]
[ b11, b12, b13]
[ b21, b22, b23]
[ b31, b32, b33]
[ b41, b42, b43]
A = [2 4; 1 7; 3 3];
A(:,:,2) = [8 9; 4 5; 6 2];
A = sym(A)
B = [8 3; 0 2];
B(:,:,2) = [6 2; 3 3];
B = sym(B)
A(:,:,1) =
[ 2, 4]
[ 1, 7]
[ 3, 3]
A(:,:,2) =
[ 8, 9]
[ 4, 5]
[ 6, 2]
B(:,:,1) =
[ 8, 3]
4-1462
vertcat
[ 0, 2]
B(:,:,2) =
[ 6, 2]
[ 3, 3]
vertcat(A,B)
ans(:,:,1) =
[ 2, 4]
[ 1, 7]
[ 3, 3]
[ 8, 3]
[ 0, 2]
ans(:,:,2) =
[ 8, 9]
[ 4, 5]
[ 6, 2]
[ 6, 2]
[ 3, 3]
Input Arguments
A1,...,AN Input arrays
symbolic variable | symbolic vector | symbolic matrix | symbolic multidimensional array
See Also
cat | horzcat
4-1463
4 Functions Alphabetical List
vpa
Variable-precision arithmetic
Compatibility
Support of character vectorsthatarenot valid variable names and do not define a
number will be removed in a future release. Instead of character vectors, use symbolic
expressions. To create symbolic expressions, first create symbolic numbers and variables,
and then use operations on them. For example, use vpa((1 + sqrt(sym(5)))/2)
instead of vpa('(1 + sqrt(5))/2').
Syntax
vpa(x)
vpa(x,d)
Description
vpa(x) uses variable-precision floating-point arithmetic (VPA) to evaluate each element
of the symbolic input x to at least d significant digits, where d is the value of the digits
function. The default value of digits is 32.
Examples
a = sym(pi);
4-1464
vpa
b = 1/sym(3);
vpa(a)
vpa(a - exp(b))
ans =
3.1415926535897932384626433832795
ans =
1.7459802285037037098345180636769
V = [a b];
M = [sin(a) cos(b); exp(b) log(a)];
vpa(V)
vpa(M)
ans =
[ 3.1415926535897932384626433832795, 0.33333333333333333333333333333333]
ans =
[ 0, 0.94495694631473766438828400767588]
[ 1.3956124250860895286281253196026, 1.1447298858494001741434273513531]
Note: You must wrap all inner inputs with vpa, such as exp(vpa(200)). Otherwise the
inputs are automatically converted to double by MATLAB.
Approximate the expression 100001/10001 with seven significant digits using digits.
Save the old value of digits returned by digits(7). The vpa function returns only five
significant digits, which can mean the remaining digits are zeros.
digitsOld = digits(7);
y = sym(100001)/10001;
vpa(y)
ans =
9.9991
4-1465
4 Functions Alphabetical List
Check if the remaining digits are zeros by using a higher precision value of 25. The result
shows that the remaining digits are in fact a repeating decimal.
digits(25)
vpa(y)
ans =
9.999100089991000899910009
Alternatively, to override digits for a single vpa call, change the precision by specifying
the second argument.
vpa(pi,100)
ans =
3.141592653589793238462643383279502884197169...
39937510582097494459230781640628620899862803...
4825342117068
digits(digitsOld)
Solve a high-degree polynomial for its roots using solve. The solve function cannot
symbolically solve the high-degree polynomial and represents the roots using root.
syms x
y = solve(x^4 - x + 1, x)
y =
root(z^4 - z + 1, z, 1)
root(z^4 - z + 1, z, 2)
root(z^4 - z + 1, z, 3)
root(z^4 - z + 1, z, 4)
4-1466
vpa
yVpa = vpa(y)
yVpa =
0.72713608449119683997667565867496 + 0.43001428832971577641651985839602i
0.72713608449119683997667565867496 - 0.43001428832971577641651985839602i
- 0.72713608449119683997667565867496 + 0.93409928946052943963903028710582i
- 0.72713608449119683997667565867496 - 0.93409928946052943963903028710582i
a = vpa(1/3, 4)
a =
0.3333
Approximate the result a using 20 digits. The result shows that the toolbox internally
used more than four digits when computing a. The last digits in the result are incorrect
because of the round-off error.
vpa(a, 20)
ans =
0.33333333333303016843
Evaluate 1/10 with the default 32-digit precision, and then with the 10 digits precision.
a = vpa(1/10, 32)
b = vpa(1/10, 10)
a =
0.1
4-1467
4 Functions Alphabetical List
b =
0.1
a - b
ans =
0.000000000000000000086736173798840354720600815844403
The difference is not equal to zero because b was calculated with only 10 digits of
precision and contains a larger round-off error than a. When you find a - b, vpa
approximates b with 32 digits. Demonstrate this behavior.
a - vpa(b, 32)
ans =
0.000000000000000000086736173798840354720600815844403
First, demonstrate that vpa cannot restore precision for a double-precision input. Call
vpa on a double-precision result and the same symbolic result.
dp = log(3);
s = log(sym(3));
dpVpa = vpa(dp)
sVpa = vpa(s)
d = sVpa - dpVpa
dpVpa =
1.0986122886681095600636126619065
sVpa =
1.0986122886681096913952452369225
d =
4-1468
vpa
0.00000000000000013133163257501600766255995767652
As expected, the double-precision result differs from the exact result at the 16th decimal
place.
Demonstrate that vpa restores precision for expressions of the form p/q, p/q, (p/q)1/2, 2q,
and 10q, where p and q are modest sized integers, by finding the difference between the
vpa call on the double-precision result and on the exact symbolic result. The differences
are 0.0 showing that vpa restores lost precision in the double-precision input.
vpa(1/3) - vpa(1/sym(3))
vpa(pi) - vpa(sym(pi))
vpa(1/sqrt(2)) - vpa(1/sqrt(sym(2)))
vpa(2^66) - vpa(2^sym(66))
vpa(10^25) - vpa(10^sym(25))
ans =
0.0
ans =
0.0
ans =
0.0
ans =
0.0
ans =
0.0
Input Arguments
x Input to evaluate
number | vector | matrix | multidimensional array | symbolic number | symbolic vector
| symbolic matrix | symbolic multidimensional array | symbolic expression | symbolic
function | symbolic character vector
4-1469
4 Functions Alphabetical List
Number of significant digits, specified as an integer. d must be greater than 1 and lesser
than 2 29 + 1 .
More About
Tips
vpa does not convert fractions in the exponent to floating point. For example,
vpa(a^sym(2/5)) returns a^(2/5).
vpa uses more digits than the number of digits specified by digits. These extra
digits guard against round-off errors in subsequent calculations and are called guard
digits.
When you call vpa on a numeric input, such as 1/3, 2^(-5), or sin(pi/4), the
numeric expression is evaluated to a double-precision number that contains round-
off errors. Then, vpa is called on that double-precision number. For accurate results,
convert numeric expressions to symbolic expressions with sym. For example, to
approximate exp(1), use vpa(exp(sym(1))).
If the second argument d is not an integer, vpa rounds it to the nearest integer with
round.
vpa restores precision for numeric inputs that match the forms p/q, p/q, (p/q)1/2, 2q,
and 10q, where p and q are modest-sized integers.
See Also
digits | double | root | vpaintegral
4-1470
vpaintegral
vpaintegral
Numerical integration using variable precision
Syntax
vpaintegral(f,a,b)
vpaintegral(f,x,a,b)
vpaintegral( ___ ,Name,Value)
Description
b
vpaintegral(f,a,b) numerically approximates a f ( x)dx . The default variable x in f
is found by symvar.
Examples
syms x
vpaintegral(x^2, 1, 2)
ans =
2.33333
4-1471
4 Functions Alphabetical List
ans =
2.33333
usingVpaintegral =
0.688424
4-1472
vpaintegral
ans =
1.3475263146739901712314731279612
ans =
1.11022e-16 - 3.14159i
Reversing the direction of the integral, by changing the order of the waypoints and
exchanging the limits, changes the sign of the result.
Multiple Integrals
Perform multiple integration by nesting calls to vpaintegral. Integrate
2 3
xy dx dy.
-1 1
syms x y
vpaintegral(vpaintegral(x*y, x, [1 3]), y, [-1 2])
ans =
4-1473
4 Functions Alphabetical List
6.0
The limits of integration can be symbolic expressions or functions. Integrate over the
triangular region 0x1 and |y|<x by specifying the limits of the integration over y
in terms of x.
vpaintegral(vpaintegral(sin(x-y)/(x-y), y, [-x x]), x, [0 1])
ans =
0.89734
Input Arguments
f Expression or function to integrate
symbolic number | symbolic variable | symbolic vector | symbolic matrix | symbolic
multidimensional array | symbolic function | symbolic expression
x Integration variable
symbolic variable
4-1474
vpaintegral
Relative error tolerance, specified as a positive real number. The default is 1e-6. The
RelTol argument determines the accuracy of the integration only if RelTol Q > AbsTol ,
where Q is the calculated integral. In this case, vpaintegral satisfies the condition
Q - I RelTol Q , where I is the exact integral value. To use only RelTol and turn off
AbsTol, set AbsTol to 0.
Example: 1e-8
Absolute error tolerance, specified as a non-negative real number. The default is 1e-10.
AbsTol determines the accuracy of the integration if AbsTol > RelTol Q , where Q is the
calculated integral. In this case, vpaintegral satisfies the condition Q - I AbsTol ,
where I is the exact integral value. To turn off AbsTol and use only RelTol, set AbsTol
to 0.
Example: 1e-12
4-1475
4 Functions Alphabetical List
More About
Tips
Ensure that the input is integrable. If the input is not integrable, the output of
vpaintegral is unpredictable.
The digits function does not affect vpaintegral. To increase precision, use the
RelTol and AbsTol arguments instead.
See Also
diff | int | integral | vpa
Introduced in R2016b
4-1476
vpasolve
vpasolve
Numeric solver
Syntax
S = vpasolve(eqn)
S = vpasolve(eqn,var)
S = vpasolve(eqn,var,init_guess)
Y = vpasolve(eqns)
Y = vpasolve(eqns,vars)
Y = vpasolve(eqns,vars,init_guess)
[y1,...,yN] = vpasolve(eqns)
[y1,...,yN] = vpasolve(eqns,vars)
[y1,...,yN] = vpasolve(eqns,vars,init_guess)
Description
S = vpasolve(eqn) numerically solves the equation eqn for the variable determined
by symvar.
S = vpasolve(eqn,var) numerically solves the equation eqn for the variable specified
by var.
4-1477
4 Functions Alphabetical List
Examples
Solve Polynomial Equation
For polynomial equations, vpasolve returns all solutions:
syms x
vpasolve(4*x^4 + 3*x^3 + 2*x^2 + x + 5 == 0, x)
ans =
- 0.88011377126068169817875190457835 + 0.76331583387715452512978468102263i
- 0.88011377126068169817875190457835 - 0.76331583387715452512978468102263i
0.50511377126068169817875190457835 + 0.81598965068946312853227067890656i
0.50511377126068169817875190457835 - 0.81598965068946312853227067890656i
ans =
-226.94447241941511682716953887638
4-1478
vpasolve
S =
struct with fields:
x: [61 sym]
y: [61 sym]
S.y
ans =
0.48638903593454300001655725369801
0
0.70187356885586188630668751791218 + 0.87969719792982402287026727381769i
0.70187356885586188630668751791218 - 0.87969719792982402287026727381769i
- 0.94506808682313338631496614476119 + 0.85451751443904587692179191887616i
- 0.94506808682313338631496614476119 - 0.85451751443904587692179191887616i
sol_x =
88.90707209659114864849280774681
sol_y =
4-1479
4 Functions Alphabetical List
0.00000000000013470479710676694388973703681918
4-1480
vpasolve
This equation has three solutions. If you do not specify the initial guess (zero-
approximation), vpasolve returns the first solution that it finds:
vpasolve(200*sin(x) == x^3 - 1, x)
ans =
-0.0050000214585835715725440675982988
Find one of the other solutions by specifying the initial point that is close to that solution:
vpasolve(200*sin(x) == x^3 - 1, x, -4)
ans =
-3.0009954677086430679926572924945
vpasolve(200*sin(x) == x^3 - 1, x, 3)
ans =
3.0098746383859522384063444361906
Suppose you need only real solutions of this equation. You cannot use assumptions on
variables because vpasolve ignores them.
assume(x, 'real')
vpasolve(x^8 - x^2 == 3, x)
ans =
-1.2052497163799060695888397264341
4-1481
4 Functions Alphabetical List
1.2052497163799060695888397264341
- 0.77061431370803029127495426747428 + 0.85915207603993818859321142757163i
- 0.77061431370803029127495426747428 - 0.85915207603993818859321142757164i
-1.0789046020338265308047436284205i
1.0789046020338265308047436284205i
0.77061431370803029127495426747428 + 0.85915207603993818859321142757164i
0.77061431370803029127495426747428 - 0.85915207603993818859321142757163i
Specify the search range to restrict the returned results to particular ranges. For
example, to return only real solutions of this equation, specify the search interval as [-
Inf Inf]:
vpasolve(x^8 - x^2 == 3, x, [-Inf Inf])
ans =
-1.2052497163799060695888397264341
1.2052497163799060695888397264341
ans =
1.2052497163799060695888397264341
The search range can contain complex numbers. In this case, vpasolve uses a
rectangular search area in the complex plane:
vpasolve(x^8 - x^2 == 3, x, [-1, 1 + i])
ans =
- 0.77061431370803029127495426747428 + 0.85915207603993818859321142757164i
0.77061431370803029127495426747428 + 0.85915207603993818859321142757164i
If random is not specified, vpasolve returns the same solution on every call.
syms x
f = x-tan(x);
for n = 1:3
vpasolve(f,x)
end
4-1482
vpasolve
ans =
0
ans =
0
ans =
0
When random is set to true, vpasolve returns a distinct solution on every call.
syms x
f = x-tan(x);
for n = 1:3
vpasolve(f,x,'random',true)
end
ans =
-227.76107684764829218924973598808
ans =
102.09196646490764333652956578441
ans =
61.244730260374400372753016364097
ans =
10.904121659428899827148702790189
Input Arguments
eqn Equation to solve
symbolic equation | symbolic expression
Variable to solve equation for, specified as a symbolic variable. If var is not specified,
symvar determines the variables.
4-1483
4 Functions Alphabetical List
Variables to solve system of equations for, specified as a symbolic vector. These variables
are specified as a vector or comma-separated list. If vars is not specified, symvar
determines the variables.
Initial guess for a solution, specified as a numeric value, vector, or matrix with two
columns.
If init_guess is a matrix with two columns, then the two entries of the rows specify the
bounds of a search range for the corresponding variables. To specify a starting point in a
matrix of search ranges, specify both columns as the starting point value.
To omit a search range for a variable, set the search range for that variable to [NaN,
NaN] in init_guess. All other uses of NaN in init_guess will error.
By default, vpasolve uses its own internal choices for starting points and search ranges.
4-1484
vpasolve
Use a random starting point for finding solutions, specified as a comma-separated pair
consisting of random and a value, which is either true or false. This is useful when you
solve nonpolynomial equations where there is no general method to find all the solutions.
If the value is false, vpasolve uses the same starting value on every call. Hence,
multiple calls to vpasolve with the same inputs always find the same solution, even
if several solutions exist. If the value is true, however, starting values for the internal
search are chosen randomly in the search range. Hence, multiple calls to vpasolve with
the same inputs might lead to different solutions. Note that if you specify starting points
for all variables, setting random to true has no effect.
Output Arguments
S Solutions of univariate equation
symbolic value | symbolic array
Solutions of univariate equation, returned as symbolic value or symbolic array. The size
of a symbolic array corresponds to the number of the solutions.
More About
Tips
vpasolve returns all solutions only for polynomial equations. For nonpolynomial
equations, there is no general method of finding all solutions. When you look for
4-1485
4 Functions Alphabetical List
To ensure the order of the returned solutions, specify the variables vars. For
example, the call [b,a] = vpasolve(eqns,b,a) assigns the solutions for a
assigned to a and the solutions for b assigned to b.
Place equations and expressions to the left of the argument list, and the variables
to the right. vpasolve checks for variables starting on the right, and on reaching
the first equation or expression, assumes everything to the left is an equation or
expression.
If possible, solve equations symbolically using solve, and then approximate the
obtained symbolic results numerically using vpa. Using this approach, you get
numeric approximations of all solutions found by the symbolic solver. Using the
symbolic solver and postprocessing its results requires more time than using the
numeric methods directly. This can significantly decrease performance.
4-1486
vpasolve
Algorithms
When you set random to true and specify a search range for a variable, random
starting points within the search range are chosen using the internal random number
generator. The distribution of starting points within finite search ranges is uniform.
When you set random to true and do not specify a search range for a variable,
random starting points are generated using a Cauchy distribution with a half-width of
100. This means the starting points are real valued and have a large spread of values
on repeated calls.
See Also
dsolve | equationsToMatrix | fzero | linsolve | solve | symvar | vpa
Introduced in R2012b
4-1487
4 Functions Alphabetical List
whittakerM
Whittaker M function
Syntax
whittakerM(a,b,z)
Description
whittakerM(a,b,z) returns the value of the Whittaker M function.
Input Arguments
a
Examples
Solve this second-order differential equation. The solutions are given in terms of the
Whittaker functions.
4-1488
whittakerM
syms a b w(z)
dsolve(diff(w, 2) + (-1/4 + a/z + (1/4 - b^2)/z^2)*w == 0)
ans =
C2*whittakerM(-a,-b,-z) + C3*whittakerW(-a,-b,-z)
Verify that the Whittaker M function is a valid solution of this differential equation:
syms a b z
isAlways(diff(whittakerM(a,b,z), z, 2) +...
(-1/4 + a/z + (1/4 - b^2)/z^2)*whittakerM(a,b,z) == 0)
ans =
logical
1
ans =
logical
1
Compute the Whittaker M function for these numbers. Because these numbers are not
symbolic objects, you get floating-point results.
[whittakerM(1, 1, 1), whittakerM(-2, 1, 3/2 + 2*i),...
whittakerM(2, 2, 2), whittakerM(3, -0.3, 1/101)]
ans =
0.7303 -9.2744 + 5.4705i 2.6328 0.3681
Compute the Whittaker M function for the numbers converted to symbolic objects. For
most symbolic (exact) numbers, whittakerM returns unresolved symbolic calls.
[whittakerM(sym(1), 1, 1), whittakerM(-2, sym(1), 3/2 + 2*i),...
whittakerM(2, 2, sym(2)), whittakerM(sym(3), -0.3, 1/101)]
ans =
[ whittakerM(1, 1, 1), whittakerM(-2, 1, 3/2 + 2i),
whittakerM(2, 2, 2), whittakerM(3, -3/10, 1/101)]
For symbolic variables and expressions, whittakerM also returns unresolved symbolic
calls:
4-1489
4 Functions Alphabetical List
syms a b x y
[whittakerM(a, b, x), whittakerM(1, x, x^2),...
whittakerM(2, x, y), whittakerM(3, x + y, x*y)]
ans =
[ whittakerM(a, b, x), whittakerM(1, x, x^2),...
whittakerM(2, x, y), whittakerM(3, x + y, x*y)]
whittakerM(sym(-3/2), 1, 1)
ans =
exp(1/2)
syms a b x
whittakerM(0, b, x)
ans =
4^b*x^(1/2)*gamma(b + 1)*besseli(b, x/2)
whittakerM(a + 1/2, a, x)
ans =
x^(a + 1/2)*exp(-x/2)
whittakerM(a, a - 5/2, x)
ans =
(2*x^(a - 2)*exp(-x/2)*(2*a^2 - 7*a + x^2/2 -...
x*(2*a - 3) + 6))/pochhammer(2*a - 4, 2)
syms a b z
diff(whittakerM(a,b,z), z)
ans =
(whittakerM(a + 1, b, z)*(a + b + 1/2))/z -...
(a/z - 1/2)*whittakerM(a, b, z)
syms x
A = [-1, x^2; 0, x];
whittakerM(-1/2, 0, A)
4-1490
whittakerM
ans =
[ exp(-1/2)*1i, exp(x^2/2)*(x^2)^(1/2)]
[ 0, x^(1/2)*exp(x/2)]
More About
Whittaker M Function
The Whittaker functions Ma,b(z) and Wa,b(z) are linearly independent solutions of this
differential equation:
d2 w 1 a 1 4 - b 2
+ - + + w = 0
dz2 4 z z2
1
M a,b ( z) = e- z 2
zb+1 2
M b - a + , 1 + 2b, z
2
Tips
All non-scalar arguments must have the same size. If one or two input arguments are
non-scalar, then whittakerM expands the scalars into vectors or matrices of the same
size as the non-scalar arguments, with all elements equal to the corresponding scalar.
References
Slater, L. J. Cofluent Hypergeometric Functions. Handbook of Mathematical Functions
with Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun,
eds.). New York: Dover, 1972.
See Also
hypergeom | kummerU | whittakerW
Introduced in R2012a
4-1491
4 Functions Alphabetical List
whittakerW
Whittaker W function
Syntax
whittakerW(a,b,z)
Description
whittakerW(a,b,z) returns the value of the Whittaker W function.
Input Arguments
a
Examples
Solve this second-order differential equation. The solutions are given in terms of the
Whittaker functions.
4-1492
whittakerW
syms a b w(z)
dsolve(diff(w, 2) + (-1/4 + a/z + (1/4 - b^2)/z^2)*w == 0)
ans =
C2*whittakerM(-a, -b, -z) + C3*whittakerW(-a, -b, -z)
Verify that the Whittaker W function is a valid solution of this differential equation:
syms a b z
isAlways(diff(whittakerW(a, b, z), z, 2) +...
(-1/4 + a/z + (1/4 - b^2)/z^2)*whittakerW(a, b, z) == 0)
ans =
logical
1
Verify that whittakerW(-a, -b, -z) also is a valid solution of this differential
equation:
syms a b z
isAlways(diff(whittakerW(-a, -b, -z), z, 2) +...
(-1/4 + a/z + (1/4 - b^2)/z^2)*whittakerW(-a, -b, -z) == 0)
ans =
logical
1
Compute the Whittaker W function for these numbers. Because these numbers are not
symbolic objects, you get floating-point results.
ans =
1.1953 -0.0156 - 0.0225i 4.8616 -0.1692
Compute the Whittaker W function for the numbers converted to symbolic objects. For
most symbolic (exact) numbers, whittakerW returns unresolved symbolic calls.
ans =
[ whittakerW(1, 1, 1), whittakerW(-2, 1, 3/2 + 2i),
whittakerW(2, 2, 2), whittakerW(3, -3/10, 1/101)]
4-1493
4 Functions Alphabetical List
For symbolic variables and expressions, whittakerW also returns unresolved symbolic
calls:
syms a b x y
[whittakerW(a, b, x), whittakerW(1, x, x^2),...
whittakerW(2, x, y), whittakerW(3, x + y, x*y)]
ans =
[ whittakerW(a, b, x), whittakerW(1, x, x^2),
whittakerW(2, x, y), whittakerW(3, x + y, x*y)]
ans =
4/(3*pi^(1/2))
syms a b x
whittakerW(0, b, x)
ans =
(x^(b + 1/2)*besselk(b, x/2))/(x^b*pi^(1/2))
whittakerW(a, -a + 1/2, x)
ans =
x^(1 - a)*x^(2*a - 1)*exp(-x/2)
whittakerW(a - 1/2, a, x)
ans =
(x^(a + 1/2)*exp(-x/2)*exp(x)*igamma(2*a, x))/x^(2*a)
ans =
- (a/z - 1/2)*whittakerW(a, b, z) -...
whittakerW(a + 1, b, z)/z
4-1494
whittakerW
whittakerW(-1/2, 0, A)
ans =
[ -exp(-1/2)*(ei(1) + pi*1i)*1i,...
exp(x^2)*exp(-x^2/2)*expint(x^2)*(x^2)^(1/2)]
[ 0,...
x^(1/2)*exp(-x/2)*exp(x)*expint(x)]
More About
Whittaker W Function
The Whittaker functions Ma,b(z) and Wa,b(z) are linearly independent solutions of this
differential equation:
d2 w 1 a 1 4 - b 2
+ - + + w = 0
dz2 4 z z2
1
Wa,b ( z ) = e- z 2 zb+1 2U b - a + ,1 + 2 b, z
2
Tips
All non-scalar arguments must have the same size. If one or two input arguments are
non-scalar, then whittakerW expands the scalars into vectors or matrices of the same
size as the non-scalar arguments, with all elements equal to the corresponding scalar.
References
Slater, L. J. Cofluent Hypergeometric Functions. Handbook of Mathematical Functions
with Formulas, Graphs, and Mathematical Tables. (M. Abramowitz and I. A. Stegun,
eds.). New York: Dover, 1972.
See Also
hypergeom | kummerU | whittakerM
4-1495
4 Functions Alphabetical List
Introduced in R2012a
4-1496
wrightOmega
wrightOmega
Wright omega function
Syntax
wrightOmega(x)
wrightOmega(A)
Description
wrightOmega(x) computes the Wright omega function of x.
Input Arguments
x
Examples
Compute the Wright omega function for these numbers. Because these numbers are not
symbolic objects, you get floating-point results:
wrightOmega(1/2)
ans =
0.7662
wrightOmega(pi)
4-1497
4 Functions Alphabetical List
ans =
2.3061
wrightOmega(-1+i*pi)
ans =
-1.0000 + 0.0000
Compute the Wright omega function for the numbers converted to symbolic objects. For
most symbolic (exact) numbers, wrightOmega returns unresolved symbolic calls:
wrightOmega(sym(1/2))
ans =
wrightOmega(1/2)
wrightOmega(sym(pi))
ans =
wrightOmega(pi)
wrightOmega(-1+i*sym(pi))
ans =
-1
Compute the Wright omega function for x and sin(x) + x*exp(x). For symbolic
variables and expressions, wrightOmega returns unresolved symbolic calls:
syms x
wrightOmega(x)
wrightOmega(sin(x) + x*exp(x))
ans =
wrightOmega(x)
ans =
wrightOmega(sin(x) + x*exp(x))
diff(wrightOmega(x), x, 2)
diff(wrightOmega(sin(x) + x*exp(x)), x)
4-1498
wrightOmega
ans =
wrightOmega(x)/(wrightOmega(x) + 1)^2 -...
wrightOmega(x)^2/(wrightOmega(x) + 1)^3
ans =
(wrightOmega(sin(x) + x*exp(x))*(cos(x) +...
exp(x) + x*exp(x)))/(wrightOmega(sin(x) + x*exp(x)) + 1)
Compute the Wright omega function for elements of matrix M and vector V:
ans =
0.5671 2.3061
0.6959 0.0415
ans =
lambertw(0, 1)
-1
More About
Wright omega Function
w ( x ) = W Im ( x ) -p ( e x )
2p
References
Corless, R. M. and D. J. Jeffrey. The Wright omega Function. Artificial Intelligence,
Automated Reasoning, and Symbolic Computation (J. Calmet, B. Benhamou, O. Caprotti,
L. Henocque, and V. Sorge, eds.). Berlin: Springer-Verlag, 2002, pp. 76-89.
4-1499
4 Functions Alphabetical List
See Also
lambertW | log
Introduced in R2011b
4-1500
xor
xor
Logical XOR for symbolic expressions
Syntax
xor(A,B)
Description
xor(A,B) represents the logical exclusive disjunction. xor(A,B) is true when either A
or B are true. If both A and B are true or false, xor(A,B) is false.
Input Arguments
A
Examples
Combine two symbolic inequalities into the logical expression using xor:
syms x
range = xor(x > -10, x < 10);
Replace variable x with these numeric values. If you replace x with 11, then inequality x
> -10 is valid and x < 10 is invalid. If you replace x with 0, both inequalities are valid.
Note that subs does not evaluate these inequalities to logical 1 or 0.
4-1501
4 Functions Alphabetical List
x1 = subs(range, x, 11)
x2 = subs(range, x, 0)
x1 =
-10 < 11 xor 11 < 10
x2 =
-10 < 0 xor 0 < 10
isAlways(x1)
isAlways(x2)
ans =
logical
1
ans =
logical
0
Note that simplify does not simplify these logical expressions to logical 1 or 0. Instead,
they return symbolic values TRUE or FALSE.
s1 = simplify(x1)
s2 = simplify(x2)
s1 =
TRUE
s2 =
FALSE
isAlways(s1)
isAlways(s2)
ans =
logical
1
4-1502
xor
ans =
logical
0
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.
assume and assumeAlso do not accept assumptions that contain xor.
See Also
all | and | any | isAlways | not | or
Introduced in R2012a
4-1503
4 Functions Alphabetical List
zeta
Riemann zeta function
Syntax
zeta(z)
zeta(n,z)
Description
zeta(z) evaluates the Riemann zeta function at the elements of z, where z is a numeric
or symbolic input.
Examples
zeta([0.7 i 4 11/3])
ans =
-2.7784 + 0.0000i 0.0033 - 0.4182i 1.0823 + 0.0000i 1.1094 + 0.0000i
Find the Riemann zeta function symbolically by converting the inputs to symbolic objects
using sym. The zeta function returns exact results.
zeta(sym([0.7 i 4 11/3]))
ans =
[ zeta(7/10), zeta(i), pi^4/90, zeta(11/3)]
zeta returns unevaluated function calls for symbolic inputs that do not have results
implemented. The implemented results are listed in Algorithms on page 4-1508.
4-1504
zeta
syms x y
Z = zeta([x sin(x); 8*x/11 x + y])
Z =
[ zeta(x), zeta(sin(x))]
[ zeta((8*x)/11), zeta(x + y)]
zeta(sym(1002))
expand(zeta(sym(1002)))
ans =
zeta(1002)
ans =
(1087503...312*pi^1002)/15156647...375
syms x
expr = zeta(3,x)
expr =
zeta(3, x)
expr = subs(expr,x,4)
expr =
zeta(3, 4)
expr = vpa(expr)
4-1505
4 Functions Alphabetical List
expr =
-0.07264084989132137196244616781177
syms y
fplot(abs(zeta(1/2+1i*y)),[0 30])
grid on
4-1506
zeta
Input Arguments
z Input
number | vector | matrix | multidimensional array | symbolic number | symbolic
variable | symbolic vector | symbolic matrix | symbolic multidimensional array |
symbolic function | symbolic expression
n Order of derivative
nonnegative integer
4-1507
4 Functions Alphabetical List
More About
Riemann Zeta Function
1
z ( s) = ks
k=1
The series converges only if the real part of z is greater than 1. The definition of the
function is extended to the entire complex plane, except for a simple pole z = 1, by
analytic continuation.
Tips
Algorithms
1
z ( 0) = -
2
ln ( p ) ln ( 2 )
z ( 0,1 ) = - -
2 2
z ( ) = 1
If z < 0 and z is an even integer, z ( z) = 0.
bernoulli (1 - z )
z ( z) = -
1- z
4-1508
zeta
For z < -1000 , zeta(z) returns an unevaluated function call. To force evaluation,
use expand(zeta(z)).
If z > 0 and z is an even integer
( 2p ) z |bernoulli ( z ) |
z ( z) =
2 z!
For z > 1000 , zeta(z) returns an unevaluated function call. To force evaluation, use
expand(zeta(z)).
If n > 0 , z ( n, ) = 0.
If the argument does not evaluate to a listed special value, zeta returns the symbolic
function call.
See Also
bernoulli
4-1509
4 Functions Alphabetical List
ztrans
Z-transform
Syntax
ztrans(f)
ztrans(f,transVar)
ztrans(f,var,transVar)
Description
ztrans(f) finds the Z-Transform on page 4-1513 of f using the default independent
variable n and the default transformation variable z. If f does not contain z, ztrans
uses symvar.
Input Arguments
f
var
Symbolic variable representing the independent variable. This variable is often called the
discrete time variable.
Default: The variable n. If f does not contain n, then the default variable is determined
by symvar.
4-1510
ztrans
transVar
Examples
Compute the Z-transform of this expression with respect to the variable k for the
transformation variable x:
syms k x
f = sin(k);
ztrans(f, k, x)
ans =
(x*sin(1))/(x^2 - 2*cos(1)*x + 1)
Compute the Z-transform of this expression calling the ztrans function with one
argument. If you do not specify the independent variable, ztrans uses the variable n.
syms a n x
f = a^n;
ztrans(f, x)
ans =
-x/(a - x)
If you also do not specify the transformation variable, ztrans uses the variable z:
ztrans(f)
ans =
-z/(a - z)
Compute the following Z-transforms that involve the Heaviside function and the
binomial coefficient:
syms n z
ztrans(heaviside(n - 3), n, z)
ans =
4-1511
4 Functions Alphabetical List
(1/(z - 1) + 1/2)/z^3
ans =
z/(z - 1)^3 + 5/z^5 + (6*z - z^6/(z - 1)^3 + 3*z^2 + z^3)/z^5
F =
ztrans(f(n), n, z)
ans =
f(n)
Find the Z-transform of this matrix. Use matrices of the same size to specify the
independent variables and transformation variables.
syms a b c d w x y z
ztrans([exp(x), 1; sin(y), i*z],[w, x; y, z],[a, b; c, d])
ans =
[ (a*exp(x))/(a - 1), b/(b - 1)]
[ (c*sin(1))/(c^2 - 2*cos(1)*c + 1), (d*1i)/(d - 1)^2]
When the input arguments are nonscalars, ztrans acts on them element-wise. If
ztrans is called with both scalar and nonscalar arguments, then ztrans expands
the scalar arguments into arrays of the same size as the nonscalar arguments with all
elements of the array equal to the scalar.
syms w x y z a b c d
ztrans(x,[x, w; y, z],[a, b; c, d])
ans =
[ a/(a - 1)^2, (b*x)/(b - 1)]
[ (c*x)/(c - 1), (d*x)/(d - 1)]
Note that nonscalar input arguments must have the same size.
4-1512
ztrans
When the first argument is a symbolic function, the second argument must be a scalar.
syms f1(x) f2(x) a b
f1(x) = exp(x);
f2(x) = x;
ztrans([f1, f2],x,[a, b])
ans =
[ a/(a - exp(1)), b/(b - 1)^2]
More About
Z-Transform
f ( n)
F ( z) = .
n =0 zn
Tips
See Also
fourier | ifourier | ilaplace | iztrans | kroneckerDelta | laplace
4-1513