0% found this document useful (0 votes)
640 views1,864 pages

Symbolic Math Toolbox User's Guide

Math simbolica

Uploaded by

Henry Mancheno
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
640 views1,864 pages

Symbolic Math Toolbox User's Guide

Math simbolica

Uploaded by

Henry Mancheno
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1864

Symbolic Math Toolbox

User's Guide

R2016b
How to Contact MathWorks

Latest news: www.mathworks.com

Sales and services: www.mathworks.com/sales_and_services

User community: www.mathworks.com/matlabcentral

Technical support: www.mathworks.com/support/contact_us

Phone: 508-647-7000

The MathWorks, Inc.


3 Apple Hill Drive
Natick, MA 01760-2098
Symbolic Math Toolbox User's Guide
COPYRIGHT 19932016 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or
reproduced in any form without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation
by, for, or through the federal government of the United States. By accepting delivery of the Program
or Documentation, the government hereby agrees that this software or documentation qualifies as
commercial computer software or commercial computer software documentation as such terms are used
or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and
conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and
govern the use, modification, reproduction, release, performance, display, and disclosure of the Program
and Documentation by the federal government (or other entity acquiring for or through the federal
government) and shall supersede any conflicting contractual terms or conditions. If this License fails
to meet the government's needs or is inconsistent in any respect with federal procurement law, the
government agrees to return the Program and Documentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
August 1993 First printing
October 1994 Second printing
May 1997 Third printing Revised for Version 2
May 2000 Fourth printing Minor changes
June 2001 Fifth printing Minor changes
July 2002 Online only Revised for Version 2.1.3 (Release 13)
October 2002 Online only Revised for Version 3.0.1
December 2002 Sixth printing
June 2004 Seventh printing Revised for Version 3.1 (Release 14)
October 2004 Online only Revised for Version 3.1.1 (Release 14SP1)
March 2005 Online only Revised for Version 3.1.2 (Release 14SP2)
September 2005 Online only Revised for Version 3.1.3 (Release 14SP3)
March 2006 Online only Revised for Version 3.1.4 (Release 2006a)
September 2006 Online only Revised for Version 3.1.5 (Release 2006b)
March 2007 Online only Revised for Version 3.2 (Release 2007a)
September 2007 Online only Revised for Version 3.2.2 (Release 2007b)
March 2008 Online only Revised for Version 3.2.3 (Release 2008a)
October 2008 Online only Revised for Version 5.0 (Release 2008a+)
October 2008 Online only Revised for Version 5.1 (Release 2008b)
November 2008 Online only Revised for Version 4.9 (Release 2007b+)
March 2009 Online only Revised for Version 5.2 (Release 2009a)
September 2009 Online only Revised for Version 5.3 (Release 2009b)
March 2010 Online only Revised for Version 5.4 (Release 2010a)
September 2010 Online only Revised for Version 5.5 (Release 2010b)
April 2011 Online only Revised for Version 5.6 (Release 2011a)
September 2011 Online only Revised for Version 5.7 (Release 2011b)
March 2012 Online only Revised for Version 5.8 (Release 2012a)
September 2012 Online only Revised for Version 5.9 (Release 2012b)
March 2013 Online only Revised for Version 5.10 (Release 2013a)
September 2013 Online only Revised for Version 5.11 (Release 2013b)
March 2014 Online only Revised for Version 6.0 (Release 2014a)
October 2014 Online only Revised for Version 6.1 (Release 2014b)
March 2015 Online only Revised for Version 6.2 (Release 2015a)
September 2015 Online only Revised for Version 6.3 (Release 2015b)
March 2016 Online only Revised for Version 7.0 (Release 2016a)
September 2016 Online only Revised for Version 7.1 (Release 2016b)
Contents

Getting Started
1
Symbolic Math Toolbox Product Description . . . . . . . . . . . . 1-2
Key Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2

Create Symbolic Numbers, Variables, and Expressions . . . . 1-3


Create Symbolic Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3
Create Symbolic Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4
Create Symbolic Expressions . . . . . . . . . . . . . . . . . . . . . . . . 1-4
Reuse Names of Symbolic Objects . . . . . . . . . . . . . . . . . . . . . 1-5

Create Symbolic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7

Create Symbolic Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9


Use Existing Symbolic Variables . . . . . . . . . . . . . . . . . . . . . . 1-9
Generate Elements While Creating a Matrix . . . . . . . . . . . . 1-10
Create Matrix of Symbolic Numbers . . . . . . . . . . . . . . . . . . 1-10

Perform Symbolic Computations . . . . . . . . . . . . . . . . . . . . . . 1-12


Differentiate Symbolic Expressions . . . . . . . . . . . . . . . . . . . 1-12
Integrate Symbolic Expressions . . . . . . . . . . . . . . . . . . . . . . 1-13
Solve Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-15
Simplify Symbolic Expressions . . . . . . . . . . . . . . . . . . . . . . 1-17
Substitutions in Symbolic Expressions . . . . . . . . . . . . . . . . 1-18
Plot Symbolic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-21

Use Assumptions on Symbolic Variables . . . . . . . . . . . . . . . 1-27


Default Assumption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-27
Set Assumptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-27
Check Existing Assumptions . . . . . . . . . . . . . . . . . . . . . . . . 1-28
Delete Symbolic Objects and Their Assumptions . . . . . . . . . 1-28

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

Functional Derivatives Tutorial . . . . . . . . . . . . . . . . . . . . . . 2-11

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

Symbolic Summation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-30


Comparing symsum and sum . . . . . . . . . . . . . . . . . . . . . . . . 2-30
Computational Speed of symsum versus sum . . . . . . . . . . . . 2-31
Output Format Differences Between symsum and sum . . . . 2-31

Taylor Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-33

Pad Approximant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-36

Find Asymptotes, Critical and Inflection Points . . . . . . . . . 2-45


Define a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-45
Find Asymptotes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-46
Find Maximum and Minimum . . . . . . . . . . . . . . . . . . . . . . 2-47
Find Inflection Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-49

Simplify Symbolic Expressions . . . . . . . . . . . . . . . . . . . . . . . 2-52


Simplify Using Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-54
Simplify Using Assumptions . . . . . . . . . . . . . . . . . . . . . . . . 2-56
Simplify Fractions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-56

vi Contents
Abbreviate Common Terms in Long Expressions . . . . . . . . 2-58

Choose Function to Rearrange Expression . . . . . . . . . . . . . 2-60


Combine Terms of Same Algebraic Structures . . . . . . . . . . . 2-60
Expand Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-62
Factor Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-63
Extract Subexpressions from Expression . . . . . . . . . . . . . . . 2-65
Collect Terms with Same Powers . . . . . . . . . . . . . . . . . . . . 2-66
Rewrite Expressions in Terms of Other Functions . . . . . . . . 2-67
Compute Partial Fraction Decompositions of Expressions . . 2-68
Compute Normal Forms of Rational Expressions . . . . . . . . . 2-69
Represent Polynomials Using Horner Nested Forms . . . . . . 2-69

Extract Numerators and Denominators of Rational


Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-71

Substitute Variables in Symbolic Expressions . . . . . . . . . . . 2-73

Substitute Elements in Symbolic Matrices . . . . . . . . . . . . . . 2-75

Substitute Scalars with Matrices . . . . . . . . . . . . . . . . . . . . . . 2-77

Use subs to Evaluate Expressions and Functions . . . . . . . . 2-79


Evaluate Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-79
Evaluate Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-80

Choose Symbolic or Numeric Arithmetic . . . . . . . . . . . . . . . 2-82


Symbolic Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-82
Variable-Precision Arithmetic . . . . . . . . . . . . . . . . . . . . . . . 2-82
Double-Precision Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . 2-83

Increase Precision of Numeric Calculations . . . . . . . . . . . . 2-84

Recognize and Avoid Round-Off Errors . . . . . . . . . . . . . . . . 2-86


Use Symbolic Computations When Possible . . . . . . . . . . . . 2-86
Perform Calculations with Increased Precision . . . . . . . . . . 2-87
Compare Symbolic and Numeric Results . . . . . . . . . . . . . . . 2-89
Plot the Function or Expression . . . . . . . . . . . . . . . . . . . . . 2-89

Increase Speed by Reducing Precision . . . . . . . . . . . . . . . . . 2-91

Numeric to Symbolic Conversion . . . . . . . . . . . . . . . . . . . . . 2-93


Conversion to Rational Symbolic Form . . . . . . . . . . . . . . . . 2-95

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

Basic Algebraic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . 2-97

Linear Algebraic Operations . . . . . . . . . . . . . . . . . . . . . . . . . 2-99

Eigenvalues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-105

Jordan Canonical Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-110

Singular Value Decomposition . . . . . . . . . . . . . . . . . . . . . . . 2-112

Solve Algebraic Equation . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-114


Solve an Equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-114
Return the Full Solution to an Equation . . . . . . . . . . . . . . 2-115
Work with the Full Solution, Parameters, and Conditions
Returned by solve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-115
Visualize and Plot Solutions Returned by solve . . . . . . . . . 2-116
Simplify Complicated Results and Improve Performance . . 2-118

Select Numeric or Symbolic Solver . . . . . . . . . . . . . . . . . . . 2-119

Solve System of Algebraic Equations . . . . . . . . . . . . . . . . . 2-121


Handle the Output of solve . . . . . . . . . . . . . . . . . . . . . . . . 2-121
Solve a Linear System of Equations . . . . . . . . . . . . . . . . . 2-123
Return the Full Solution of a System of Equations . . . . . . 2-124
Solve a System of Equations Under Conditions . . . . . . . . . 2-126
Work with Solutions, Parameters, and Conditions Returned by
solve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-127
Convert Symbolic Results to Numeric Values . . . . . . . . . . 2-130
Simplify Complicated Results and Improve Performance . . 2-131

Troubleshoot Equation Solutions from solve Function . . 2-132


Return Only Real Solutions . . . . . . . . . . . . . . . . . . . . . . . . 2-132
Apply Simplification Rules . . . . . . . . . . . . . . . . . . . . . . . . 2-132
Use Assumptions to Narrow Results . . . . . . . . . . . . . . . . . 2-133
Simplify Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-135
Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-135

Solve System of Linear Equations . . . . . . . . . . . . . . . . . . . . 2-137


Solve System of Linear Equations Using linsolve . . . . . . . 2-137

viii Contents
Solve System of Linear Equations Using solve . . . . . . . . . 2-138

Solve Equations Numerically . . . . . . . . . . . . . . . . . . . . . . . . 2-140


Find All Roots of a Polynomial Function . . . . . . . . . . . . . . 2-140
Find Zeros of a Nonpolynomial Function Using Search Ranges
and Starting Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-141
Obtain Solutions to Arbitrary Precision . . . . . . . . . . . . . . . 2-145
Solve Multivariate Equations Using Search Ranges . . . . . 2-146

Solve a Single Differential Equation . . . . . . . . . . . . . . . . . . 2-151


First-Order Linear ODE . . . . . . . . . . . . . . . . . . . . . . . . . . 2-151
Nonlinear ODE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-152
Second-Order ODE with Initial Conditions . . . . . . . . . . . . 2-152
Third-Order ODE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-152
More ODE Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-153

Solve a System of Differential Equations . . . . . . . . . . . . . . 2-155


Solve System of Differential Equations . . . . . . . . . . . . . . . 2-155
Solve Differential Equations in Matrix Form . . . . . . . . . . . 2-157

Differential Algebraic Equations . . . . . . . . . . . . . . . . . . . . . 2-161

Set Up Your DAE Problem . . . . . . . . . . . . . . . . . . . . . . . . . . 2-162


Step 1: Equations and Variables . . . . . . . . . . . . . . . . . . . . 2-163
Step 2: Differential Order . . . . . . . . . . . . . . . . . . . . . . . . . 2-164
Step 3: Differential Index . . . . . . . . . . . . . . . . . . . . . . . . . 2-164
Step 4: MATLAB Function Handles . . . . . . . . . . . . . . . . . 2-164
Step 5: Consistent Initial Conditions . . . . . . . . . . . . . . . . . 2-165
Step 6: ODE Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-165
Solving DAE Systems Flow Chart . . . . . . . . . . . . . . . . . . . 2-165

Reduce Differential Order of DAE Systems . . . . . . . . . . . . 2-167

Check and Reduce Differential Index . . . . . . . . . . . . . . . . . 2-169


Reduce Differential Index to 1 . . . . . . . . . . . . . . . . . . . . . . 2-169
Reduce Differential Index to 0 . . . . . . . . . . . . . . . . . . . . . . 2-171

Convert DAE Systems to MATLAB Function Handles . . . . 2-173


DAEs to Function Handles for ode15i . . . . . . . . . . . . . . . . 2-173
ODEs to Function Handles for ode15i . . . . . . . . . . . . . . . . 2-175
DAEs to Function Handles for ode15s and ode23t . . . . . . . 2-176
ODEs to Function Handles for ode15s and ode23t . . . . . . . 2-177

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

Solve DAE Systems Using MATLAB ODE Solvers . . . . . . . 2-186


Solve a DAE System with ode15i . . . . . . . . . . . . . . . . . . . 2-186
Solve an ODE System with ode15i . . . . . . . . . . . . . . . . . . 2-187
Solve a DAE System with ode15s . . . . . . . . . . . . . . . . . . . 2-188
Solve an ODE System with ode15s . . . . . . . . . . . . . . . . . . 2-189

Fourier Transforms and Inverse . . . . . . . . . . . . . . . . . . . . . 2-191

Laplace Transform and Inverse . . . . . . . . . . . . . . . . . . . . . . 2-197

Z-Transform and Inverse . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-204


References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-206

Create Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-208


Plot with Symbolic Plotting Functions . . . . . . . . . . . . . . . . 2-208
Plot Functions Numerically . . . . . . . . . . . . . . . . . . . . . . . . 2-210
Plot Multiple Symbolic Functions in One Graph . . . . . . . . 2-211
Plot Multiple Symbolic Functions in One Figure . . . . . . . . 2-213
Combine Symbolic Function Plots and Numeric Data Plots 2-215
Combine Numeric and Symbolic Plots in 3-D . . . . . . . . . . . 2-217

Generate C or Fortran Code from Symbolic Expressions . 2-220

Generate MATLAB Functions from Symbolic Expressions 2-222


Generating a Function Handle . . . . . . . . . . . . . . . . . . . . . 2-222
Control the Order of Variables . . . . . . . . . . . . . . . . . . . . . 2-223
Generate a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-223
Name Output Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 2-225

Generate MATLAB Function Blocks from Symbolic


Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-226
Generate and Edit a Block . . . . . . . . . . . . . . . . . . . . . . . . 2-226
Control the Order of Input Ports . . . . . . . . . . . . . . . . . . . . 2-227
Name the Output Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-227

Generate Simscape Equations from Symbolic Expressions 2-228


Convert Algebraic and Differential Equations . . . . . . . . . . 2-228

x Contents
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-230

MuPAD in Symbolic Math Toolbox


3
MuPAD Engines and MATLAB Workspace . . . . . . . . . . . . . . . 3-2

Create MuPAD Notebooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3


If You Need Communication Between Interfaces . . . . . . . . . . 3-3
If You Use MATLAB to Access MuPAD . . . . . . . . . . . . . . . . 3-4

Open MuPAD Notebooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6


If You Need Communication Between Interfaces . . . . . . . . . . 3-7
If You Use MATLAB to Access MuPAD . . . . . . . . . . . . . . . . 3-7
Open MuPAD Program Files and Graphics . . . . . . . . . . . . . . 3-9

Save MuPAD Notebooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-12

Evaluate MuPAD Notebooks from MATLAB . . . . . . . . . . . . 3-13

Close MuPAD Notebooks from MATLAB . . . . . . . . . . . . . . . 3-17

Convert MuPAD Notebooks to MATLAB Live Scripts . . . . . 3-19


Convert a MuPAD Notebook .mn to a MATLAB Live Script
.mlx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-19
Known Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-20

Troubleshoot MuPAD to MATLAB Translation Errors . . . . 3-25

Troubleshoot MuPAD to MATLAB Translation Warnings . 3-34

Edit MuPAD Code in MATLAB Editor . . . . . . . . . . . . . . . . . 3-42


Comments in MuPAD Procedures . . . . . . . . . . . . . . . . . . . . 3-43

Notebook Files and Program Files . . . . . . . . . . . . . . . . . . . . 3-45

Source Code of the MuPAD Library Functions . . . . . . . . . . 3-47

Differences Between MATLAB and MuPAD Syntax . . . . . . 3-48

xi
Copy Variables and Expressions Between MATLAB and
MuPAD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-51
Copy and Paste Using the System Clipboard . . . . . . . . . . . . 3-53

Reserved Variable and Function Names . . . . . . . . . . . . . . . . 3-55

Call Built-In MuPAD Functions from MATLAB . . . . . . . . . . 3-57


evalin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-57
feval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-57
evalin vs. feval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-58
Floating-Point Arguments of evalin and feval . . . . . . . . . . . 3-59

Use Your Own MuPAD Procedures . . . . . . . . . . . . . . . . . . . . 3-61


Write MuPAD Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . 3-61
Steps to Take Before Calling a Procedure . . . . . . . . . . . . . . 3-62
Call Your Own MuPAD Procedures . . . . . . . . . . . . . . . . . . . 3-63

Clear Assumptions and Reset the Symbolic Engine . . . . . . 3-66


Check Assumptions Set On Variables . . . . . . . . . . . . . . . . . 3-67
Effects of Assumptions on Computations . . . . . . . . . . . . . . . 3-68

Create MATLAB Functions from MuPAD Expressions . . . . 3-70


Copy MuPAD Variables to the MATLAB Workspace . . . . . . 3-71
Generate MATLAB Code in a MuPAD Notebook . . . . . . . . . 3-72

Create MATLAB Function Blocks from MuPAD


Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-74

Create Simscape Equations from MuPAD Expressions . . . . 3-76


GenerateSimscape Equations in the MuPAD Notebook App . 3-77
Generate Simscape Equations in the MATLAB Command
Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-77

Functions Alphabetical List


4

xii Contents
1

Getting Started

Symbolic Math Toolbox Product Description on page 1-2


Create Symbolic Numbers, Variables, and Expressions on page 1-3
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 Getting Started

Symbolic Math Toolbox Product Description


Perform symbolic math computations

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.

Symbolic Math Toolbox lets you analytically perform differentiation, integration,


simplification, transforms, and equation solving. Your computations can be performed
either analytically or using variable precision arithmetic, with the results displayed
in mathematical typeset. You can share your symbolic work as live scripts with other
MATLAB users or convert them to HTML or PDF for publication. You can generate
MATLAB functions, Simulink function blocks, and Simscape equations directly from
symbolic expressions.

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 Symbolic Numbers, Variables, and Expressions


This page shows how to create symbolic numbers, variables, and expressions. To learn
how to work with symbolic math, see Perform Symbolic Computations on page 1-12.

Create Symbolic Numbers


You can create symbolic numbers by using sym. Symbolic numbers are exact
representations, unlike floating-point numbers.

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.

Calculations on symbolic numbers are exact. Demonstrate this exactness by finding


sin(pi) symbolically and numerically. The symbolic result is exact, while the numeric
result is an approximation.

sin(sym(pi))
sin(pi)

ans =
0
ans =
1.2246e-16

To learn more about symbolic representation of numbers, see Numeric to Symbolic


Conversion on page 2-93.

1-3
1 Getting Started

Create Symbolic Variables


You can use two ways to create symbolic variables, syms and sym. The syms syntax is a
shorthand for sym.

Create symbolic variables x and y using syms and sym respectively.


syms x
y = sym('y')

The first command creates a symbolic variable x in the MATLAB workspace with the
value x assigned to the variable x. The second command creates a symbolic variable y
with 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.

Create the variables a1, ..., a20.


A = sym('a', [1 20])

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).

Create Symbolic Expressions


Suppose you want to use a symbolic variable to represent the golden ratio

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

Then, assign the expression to f:

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.

Reuse Names of Symbolic Objects


If you set a variable equal to a symbolic expression, and then apply the syms command
to the variable, MATLAB software removes the previously defined expression from the
variable. For example,

syms a b
f = a + b

returns

f =
a + b

If later you enter

1-5
1 Getting Started

syms f
f

then MATLAB removes the value a + b from the expression 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

Create Symbolic Functions


You also can use sym and syms to create symbolic functions. For example, you can create
an arbitrary function f(x, y) where x and y are function variables. The simplest way to
create an arbitrary symbolic function is to use syms:

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

Now evaluate f(x, y) for x = y + 1:

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

Create Symbolic Matrices


In this section...
Use Existing Symbolic Variables on page 1-9
Generate Elements While Creating a Matrix on page 1-10
Create Matrix of Symbolic Numbers on page 1-10

Use Existing Symbolic Variables


A circulant matrix has the property that each row is obtained from the previous one
by cyclically permuting the entries one step forward. For example, create the symbolic
circulant matrix whose elements are a, b, and c, using the commands:
syms a b c
A = [a b c; c a b; b c a]

A =
[ a, b, c]
[ c, a, b]
[ b, c, a]

Since matrix A is circulant, the sum of elements over each row and each column is the
same. Find the sum of all the elements of the first row:
sum(A(1,:))

ans =
a + b + c

To check if the sum of the elements of the first row equals the sum of the elements of the
second column, use the isAlways function:
isAlways(sum(A(1,:)) == sum(A(:,2)))

The sums are equal:


ans =
logical
1

From this example, you can see that using symbolic objects is very similar to using
regular MATLAB numeric objects.

1-9
1 Getting Started

Generate Elements While Creating a Matrix


The sym function also lets you define a symbolic matrix or vector without having to
define its elements in advance. In this case, the sym function generates the elements of
a symbolic matrix at the same time that it creates a matrix. The function presents all
generated elements using the same form: the base (which must be a valid variable name),
a row index, and a column index. Use the first argument of sym to specify the base for the
names of generated elements. You can use any valid variable name as a base. To check
whether the name is a valid variable name, use the isvarname function. By default, sym
separates a row index and a column index by underscore. For example, create the 2-by-4
matrix A with the elements A1_1, ..., A2_4:
A = sym('A', [2 4])

A =
[ A1_1, A1_2, A1_3, A1_4]
[ A2_1, A2_2, A2_3, A2_4]

To control the format of the generated names of matrix elements, use %d in the first
argument:
A = sym('A%d%d', [2 4])

A =
[ A11, A12, A13, A14]
[ A21, A22, A23, A24]

Create Matrix of Symbolic Numbers


A particularly effective use of sym is to convert a matrix from numeric to symbolic form.
The command
A = hilb(3)

generates the 3-by-3 Hilbert matrix:


A =
1.0000 0.5000 0.3333
0.5000 0.3333 0.2500
0.3333 0.2500 0.2000

By applying sym to A
A = sym(A)

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]

For more information on numeric to symbolic conversions, see Numeric to Symbolic


Conversion on page 2-93.

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

Perform Symbolic Computations


In this section...
Differentiate Symbolic Expressions on page 1-12
Integrate Symbolic Expressions on page 1-13
Solve Equations on page 1-15
Simplify Symbolic Expressions on page 1-17
Substitutions in Symbolic Expressions on page 1-18
Plot Symbolic Functions on page 1-21

Differentiate Symbolic Expressions


With the Symbolic Math Toolbox software, you can find

Derivatives of single-variable expressions


Partial derivatives
Second and higher order derivatives
Mixed derivatives

For in-depth information on taking symbolic derivatives see Differentiation on page


2-5.

Expressions with One Variable

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.

To differentiate the symbolic expression f with respect to a variable y, enter:


syms x y
f = sin(x)^2 + cos(y)^2;
diff(f, y)

ans =
-2*cos(y)*sin(y)

Second Partial and Mixed Derivatives

To take a second derivative of the symbolic expression f with respect to a variable y,


enter:
syms x y
f = sin(x)^2 + cos(y)^2;
diff(f, y, 2)

ans =
2*sin(y)^2 - 2*cos(y)^2

You get the same result by taking derivative twice: diff(diff(f, y)). To take mixed
derivatives, use two differentiation commands. For example:
syms x y
f = sin(x)^2 + cos(y)^2;
diff(diff(f, y), x)

ans =
0

Integrate Symbolic Expressions


You can perform symbolic integration including:

Indefinite and definite integration

1-13
1 Getting Started

Integration of multivariable expressions

For in-depth information on the int command including integration with real and
complex parameters, see Integration on page 2-22.

Indefinite Integrals of One-Variable Expressions

Suppose you want to integrate a symbolic expression. The first step is to create the
symbolic expression:
syms x
f = sin(x)^2;

To find the indefinite integral, enter


int(f)

ans =
x/2 - sin(2*x)/4

Indefinite Integrals of Multivariable Expressions

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)

If the integration variable is n, enter

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)

If MATLAB Cannot Find a Closed Form of an Integral

If the int function cannot compute an integral, it returns an unresolved integral:


syms x
int(sin(sinh(x)))

ans =
int(sin(sinh(x)), x)

Solve Equations
You can solve different types of symbolic equations including:

Algebraic equations with one symbolic variable


Algebraic equations with several symbolic variables
Systems of algebraic equations

For in-depth information on solving symbolic equations including differential equations,


see Equation Solving.

Solve Algebraic Equations with One Symbolic Variable

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

Solve Algebraic Equations with Several Symbolic Variables

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.

Solve Systems of Algebraic Equations

You also can solve systems of equations. For example:


syms x y z
[x, y, z] = solve(z == 4*x, x == y, z == x^2 + y^2)

x =
0
2

1-16
Perform Symbolic Computations

y =
0
2

z =
0
8

Simplify Symbolic Expressions


Symbolic Math Toolbox provides a set of simplification functions allowing you to
manipulate the output of a symbolic expression. For example, the following polynomial of
the golden ratio phi
phi = (1 + sqrt(sym(5)))/2;
f = phi^2 - phi - 1

returns
f =
(5^(1/2)/2 + 1/2)^2 - 5^(1/2)/2 - 3/2

You can simplify this answer by entering


simplify(f)

and get a very short answer:


ans =
0

Symbolic simplification is not always so straightforward. There is no universal


simplification function, because the meaning of a simplest representation of a symbolic
expression cannot be defined clearly. Different problems require different forms of the
same mathematical expression. Knowing what form is more effective for solving your
particular problem, you can choose the appropriate simplification function.

For example, to show the order of a polynomial or symbolically differentiate or integrate


a polynomial, use the standard polynomial form with all the parentheses multiplied out
and all the similar terms summed up. To rewrite a polynomial in the standard form, use
the expand function:
syms x

1-17
1 Getting Started

f = (x ^2- 1)*(x^4 + x^3 + x^2 + x + 1)*(x^4 - x^3 + x^2 - x + 1);


expand(f)

ans =
x^10 - 1

The factor simplification function shows the polynomial roots. If a polynomial cannot
be factored over the rational numbers, the output of the factor function is the standard
polynomial form. For example, to factor the third-order polynomial, enter:
syms x
g = x^3 + 6*x^2 + 11*x + 6;
factor(g)

ans =
[ x + 3, x + 2, x + 1]

The nested (Horner) representation of a polynomial is the most efficient for numerical
evaluations:
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.

Substitutions in Symbolic Expressions


Substitute Symbolic Variables with Numbers

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

The subs function does not change the original expression f:

1-18
Perform Symbolic Computations

f =
2*x^2 - 3*x + 1

Substitute in Multivariate Expressions

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);

enter the command

subs(f, x, 3)

ans =
9*y + 15*y^(1/2)

Substitute One Symbolic Variable for Another

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)

Substitute a Matrix into a Polynomial

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

To substitute a matrix at each element, use the subs command:

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]

You can do element-by-element substitution for rectangular or square matrices.


Substitution in a Matrix Sense

If you want to substitute a matrix into a polynomial using standard matrix


multiplication rules, a matrix must be square. For example, you can substitute the magic
square A into a polynomial f:

1 Create the polynomial:

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:

A^3 - 15*A^2 - 24*A + 350*eye(3)

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

Substitute the Elements of a Symbolic Matrix

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)

The result is the matrix:

A =
[ a, alpha, c]
[ beta, a, alpha]
[ alpha, c, a]

For more information, see Substitute Elements in Symbolic Matrices on page 2-75.

Plot Symbolic Functions


Symbolic Math Toolbox provides the plotting functions:

fplot to create 2-D plots of symbolic expressions, equations, or functions in


Cartesian coordinates.
fplot3 to create 3-D parametric plots.

1-21
1 Getting Started

ezpolar to create plots in polar coordinates.


fsurf to create surface plots.
fcontour to create contour plots.
fmesh to create mesh plots.

Explicit Function Plot

Create a 2-D line plot by using fplot. Plot the expression .

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

Implicit Function Plot

Plot equations and implicit functions using fimplicit.

Plot the equation over .

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

Plot 3-D parametric lines by using fplot3.

Plot the parametric line

1-24
Perform Symbolic Computations

syms t
fplot3(t^2*sin(10*t), t^2*cos(10*t), t)

Create Surface Plot

Create a 3-D surface by using fsurf.

Plot the paraboloid .

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

Use Assumptions on Symbolic Variables


In this section...
Default Assumption on page 1-27
Set Assumptions on page 1-27
Check Existing Assumptions on page 1-28
Delete Symbolic Objects and Their Assumptions on page 1-28

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.

Check Existing Assumptions


To see all assumptions set on a symbolic variable, use the assumptions function with
the name of the variable as an input argument. For example, this command returns the
assumptions currently used for the variable x:

assumptions(x)

To see all assumptions used for all symbolic variables in the MATLAB workspace, use
assumptions without input arguments:

assumptions

For details, see Check Assumptions Set On Variables on page 3-67.

Delete Symbolic Objects and Their Assumptions


Symbolic objects and their assumptions are stored separately. When you set an
assumption that x is real using

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:

1 To clear the assumption, enter

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

Create Symbolic Functions on page 1-7


Create Symbolic Matrices on page 1-9
Perform Symbolic Computations on page 1-12

1-30
2

Using Symbolic Math Toolbox


Software

Find Symbolic Variables in Expressions, Functions, Matrices on page 2-3


Differentiation on page 2-5
Functional Derivatives Tutorial on page 2-11
Limits on page 2-19
Integration on page 2-22
Symbolic Summation on page 2-30
Taylor Series on page 2-33
Pad Approximant on page 2-36
Find Asymptotes, Critical and Inflection Points on page 2-45
Simplify Symbolic Expressions on page 2-52
Abbreviate Common Terms in Long Expressions on page 2-58
Choose Function to Rearrange Expression on page 2-60
Extract Numerators and Denominators of Rational Expressions on page 2-71
Substitute Variables in Symbolic Expressions on page 2-73
Substitute Elements in Symbolic Matrices on page 2-75
Substitute Scalars with Matrices on page 2-77
Use subs to Evaluate Expressions and Functions on page 2-79
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
Numeric to Symbolic Conversion on page 2-93
Basic Algebraic Operations on page 2-97
2 Using Symbolic Math Toolbox Software

Linear Algebraic Operations on page 2-99


Eigenvalues on page 2-105
Jordan Canonical Form on page 2-110
Singular Value Decomposition on page 2-112
Solve Algebraic Equation on page 2-114
Select Numeric or Symbolic Solver on page 2-119
Solve System of Algebraic Equations on page 2-121
Troubleshoot Equation Solutions from solve Function on page 2-132
Solve System of Linear Equations on page 2-137
Solve Equations Numerically on page 2-140
Solve a Single Differential Equation on page 2-151
Solve a System of Differential Equations on page 2-155
Differential Algebraic Equations on page 2-161
Set Up Your DAE Problem on page 2-162
Reduce Differential Order of DAE Systems on page 2-167
Check and Reduce Differential Index on page 2-169
Convert DAE Systems to MATLAB Function Handles on page 2-173
Find Consistent Initial Conditions on page 2-180
Solve DAE Systems Using MATLAB ODE Solvers on page 2-186
Fourier Transforms and Inverse on page 2-191
Laplace Transform and Inverse on page 2-197
Z-Transform and Inverse on page 2-204
Create Plots on page 2-208
Generate C or Fortran Code from Symbolic Expressions on page 2-220
Generate MATLAB Functions from Symbolic Expressions on page 2-222
Generate MATLAB Function Blocks from Symbolic Expressions on page 2-226
Generate Simscape Equations from Symbolic Expressions on page 2-228

2-2
Find Symbolic Variables in Expressions, Functions, Matrices

Find Symbolic Variables in Expressions, Functions, Matrices


To find symbolic variables in an expression, function, or matrix, use symvar. For
example, find all symbolic variables in symbolic expressions f and g:
syms a b n t x
f = x^n;
g = sin(a*t + b);
symvar(f)

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.

You also can find symbolic variables in a function:


syms x y w z
f(w, z) = x*w + y*z;
symvar(f)

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]

Find a Default Symbolic Variable


If you do not specify an independent variable when performing substitution,
differentiation, or integration, MATLAB uses a default variable. The default variable
is typically the one closest alphabetically to x or, for symbolic functions, the first input
argument of a function. To find which variable is chosen as a default variable, use the
symvar(f, 1) command. For example:

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)

differentiates f with respect to x:

ans =
5*cos(5*x)

As another example, let

g = exp(x)*cos(x);

where exp(x) denotes ex, and differentiate g:

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

To take the second derivative of g, enter

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)

In this example, MATLAB software automatically simplifies the answer. However,


in some cases, MATLAB might not simplify an answer, in which case you can use the
simplify command. For an example of such simplification, see More Examples on
page 2-7.

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

If you just enter

diff(5)

MATLAB returns

ans =
[]

because 5 is not a symbolic expression.

Derivatives of Expressions with Several Variables


To differentiate an expression that contains more than one symbolic variable, specify
the variable that you want to differentiate with respect to. The diff command then
calculates the partial derivative of the expression with respect to that variable. For
example, given the symbolic expression

syms s t
f = sin(s*t);

the command

2-6
Differentiation

diff(f,t)

calculates the partial derivative f / t . The result is

ans =
s*cos(s*t)

To differentiate f with respect to the variable s, enter

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

Calculate the second derivative of f with respect to t:

diff(f, t, 2)

This command returns

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

This table illustrates the results of entering diff(f).

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

return the Jacobian


J =
[ cos(f)*cos(l), -r*cos(f)*sin(l), -r*cos(l)*sin(f)]
[ cos(l)*sin(f), -r*sin(f)*sin(l), r*cos(f)*cos(l)]
[ sin(l), r*cos(l), 0]

and the command


detJ = simplify(det(J))

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).

A table summarizing diff and jacobian follows.

Mathematical Operator MATLAB Command


df diff(f) or diff(f, x)
dx

df diff(f, a)
da
diff(f, b, 2)
d2 f
db2

( r, t) J = jacobian([r; t],[u; v])


J=
(u, v)

2-10
Functional Derivatives Tutorial

Functional Derivatives Tutorial


This example shows how to use functional derivatives in the Symbolic Math Toolbox
using the example of the wave equation. The wave equation for a string fixed at its
ends is solved using functional derivatives. A functional derivative is the derivative of
a functional with respect to the function that the functional depends on. The Symbolic
Math Toolbox implements functional derivatives using the functionalDerivative
function.

Solving the wave equation is one application of functional derivatives. It describes the
motion of waves, from the motion of a string to the propagation of an electromagnetic
wave, and is an important equation in physics. You can apply the techniques
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

The potential energy is

where r is the tension.

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) =

L*r*diff(S(x, t), x, x) - L*d*diff(S(x, t), t, t) == 0

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) =

diff(S(x, t), t, t)/v^2 == diff(S(x, t), x, x)

Solve the equation using the method of separation of variables. Set S(x,t) =
U(x)*V(t) to separate the dependence on position x and time t. Separate both sides of
the resulting equation using children.

syms U(x) V(t)


eqn2 = subs(eqn,S(x,t),U(x)*V(t));
eqn2 = eqn2/(U(x)*V(t))
tmp = children(eqn2);

2-12
Functional Derivatives Tutorial

eqn2(x, t) =

diff(V(t), t, t)/(v^2*V(t)) == diff(U(x), x, x)/U(x)

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)

Obtain the constants in the equations.

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 =

C6 ~= 0 & 1 <= k & in(k, 'integer')

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 = subs(S,[p1 p2],[1 1]);


S = simplify(S,'Steps',50)

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

where denotes arbitrary constants.

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

You can calculate the values in the equation by


specifying a condition for initial velocity

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

limit((1 + x/n)^n, n, inf)

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

To calculate the limit as x approaches 0 from the left,

x
lim ,
x 0- x

enter
syms x
limit(x/abs(x), x, 0, 'left')

ans =
-1

To calculate the limit as x approaches 0 from the right,

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.

Mathematical Operation MATLAB Command


lim f ( x) limit(f)
x 0

lim f ( x) limit(f, x, a) or
x a
limit(f, a)
lim f ( x) limit(f, x, a, 'left')
x a-

lim f ( x) limit(f, x, a, 'right')


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.

Mathematical Operation MATLAB Command

log( x) if n = -1 int(x^n) or int(x^n,x)




n
x dx = xn +1
otherwise.
n +1

p /2 int(sin(2*x), 0, pi/2) or int(sin(2*x), x,


sin(2 x) dx = 1 0, pi/2)
0

g = cos(at + b) g = cos(a*t + b) int(g) or int(g, t)

g(t)dt = sin(at + b) / a
int(besselj(1, z)) or int(besselj(1, z),
J1 (z)dz = - J0 ( z) z)

In contrast to differentiation, symbolic integration is a more complicated task. A number


of difficulties can arise in computing the integral:

The antiderivative, F, may not exist in closed form.


The antiderivative may define an unfamiliar function.
The antiderivative may exist, but the software can't find it.

2-22
Integration

The software could find the antiderivative on a larger computer, but runs out of time
or memory on the available machine.

Nevertheless, in many cases, MATLAB can perform symbolic integration successfully.


For example, create the symbolic variables
syms a b theta x y n u z

The following table illustrates integration of expressions containing those variables.

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.

If MATLAB is unable to find an answer to the integral of a function f, it just returns


int(f).

2-23
2 Using Symbolic Math Toolbox Software

Definite integration is also possible.

Definite Integral Command


b int(f, a, b)
a f ( x)dx
b int(f, v, a, b)
a f (v)dv
Here are some additional examples.

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

For the Bessel function (besselj) example, it is possible to compute a numerical


approximation to the value of the integral, using the double function. The commands

syms z
a = int(besselj(1,z)^2,0,1)

2-24
Integration

return

a =
hypergeom([3/2, 3/2], [2, 5/2, 3], -1)/12

and the command

a = double(a)

returns

a =
0.0717

Integration with Real Parameters


One of the subtleties involved in symbolic integration is the value of various
parameters. For example, if a is any positive real number, the expression

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

However, if you try to calculate the integral


- ax 2
e dx
-

without assigning a value to a, MATLAB assumes that a represents a complex number,


and therefore returns a piecewise answer that depends on the argument of a. If you
are only interested in the case when a is a positive real number, use assume to set an
assumption on a:

syms a
assume(a > 0)

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)

Integration with Complex Parameters


To calculate the integral


1
a + x2
2
dx
-

for complex values of a, enter

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.

The preceding commands produce the complex output

F =
(pi*signIm(1i/a))/a

The function signIm is defined as:

1 if Im( z) > 0, or Im( z) = 0 and z < 0



signIm( z) = 0 if z = 0
-1 otherwise.

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

High-Precision Numerical Integration Using Variable-Precision Arithmetic


High-precision numerical integration is implemented in the vpaintegral function of
the Symbolic Math Toolbox. vpaintegral uses variable-precision arithmetic in contrast
to the MATLAB integral function, which uses double-precision arithmetic.

Integrate besseli(5,25*u).*exp(-u*25) by using both integral and


vpaintegral. The integral function returns NaN and issues a warning while
vpaintegral returns the correct result.

syms u
f = besseli(5,25*x).*exp(-x*25);
fun = @(u)besseli(5,25*u).*exp(-u*25);

usingIntegral = integral(fun, 0, 30)


usingVpaintegral = vpaintegral(f, 0, 30)

Warning: Infinite or Not-a-Number value encountered.

2-28
Integration

usingIntegral =
NaN

usingVpaintegral =
0.688424

For more information, see vpaintegral.

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

Comparing symsum and sum


You can find definite sums by using both sum and symsum. The sum function sums the
input over a dimension, while the symsum function sums the input over an index.

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

Computational Speed of symsum versus sum


For summing definite series, symsum can be faster than sum. For summing an indefinite
series, you can only use symsum.

You can demonstrate that symsum can be faster than sum by summing a large definite
100000
S= k2 .
series such as k=1

To compare runtimes on your computer, use the following commands.


syms k
tic
sum(sym(1:100000).^2);
toc
tic
symsum(k^2, k, 1, 100000);
toc

Output Format Differences Between symsum and sum


symsum can provide a more elegant representation of sums than sum provides.
Demonstrate this difference by comparing the function outputs for the definite series
10
S= xk .
k= 1 To simplify the solution, assume x > 1.
syms x
assume(x > 1)
S_sum = sum(x.^(1:10))
S_symsum = symsum(x^k, k, 1, 10)

S_sum =
x^10 + x^9 + x^8 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x
S_symsum =
x^11/(x - 1) - x/(x - 1)

Show that the outputs are equal by using isAlways. The isAlways function returns
logical 1 (true), meaning that the outputs are equal.

2-31
2 Using Symbolic Math Toolbox Software

isAlways(S_sum == S_symsum)

ans =
logical
1

For further computations, clear the assumptions.


assume(x, 'clear')

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

Technically, T is a Maclaurin series, since its expansion point is a = 0.

The command

pretty(T)

prints T in a format resembling typeset mathematics:

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.

t is a large expression; enter

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.

The behavior of a first-order system is described by this differential equation

dy ( t )
t + y( t) = ax ( t ) .
dt

Enter the differential equation in MATLAB.


syms tau a x(t) y(t) xS(s) yS(s) H(s) tmp

2-36
Pad Approximant

F = tau*diff(y)+y == a*x;

Find the Laplace transform of F using laplace.

F = laplace(F,t,s)

F =

laplace(y(t), t, s) - tau*(y(0) - s*laplace(y(t), t, s)) == a*laplace(x(t), t, s)

Assume the response of the system at t = 0 is 0. Use subs to substitute for y(0) = 0.

F = subs(F,y(0),0)

F =

laplace(y(t), t, s) + s*tau*laplace(y(t), t, s) == a*laplace(x(t), t, s)

To collect common terms, use simplify.

F = simplify(F)

F =

(s*tau + 1)*laplace(y(t), t, s) == a*laplace(x(t), t, s)

For readability, replace the Laplace transforms of x(t) and y(t) with xS(s) and
yS(s).

F = subs(F,[laplace(x(t),t,s) laplace(y(t),t,s)],[xS(s) 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 = heaviside(t - 3);


step = laplace(step)

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.

y = subs(y,[a tau],[1 3]);


y = ilaplace(y,s);

Find the Pad approximant of order [2 2] of the step input using the Order input
argument to pade.

stepPade22 = pade(step,'Order',[2 2])

stepPade22 =

(3*s^2 - 4*s + 2)/(2*s*(s + 1))

Find the response to the input by multiplying the transfer function and the Pad
approximant of the input.

yPade22 = H(s)*stepPade22

yPade22 =

(a*(3*s^2 - 4*s + 2))/(2*s*(s*tau + 1)*(s + 1))

Find the inverse Laplace transform of yPade22 using ilaplace.

yPade22 = ilaplace(yPade22,s)

yPade22 =

a + (9*a*exp(-s))/(2*tau - 2) - (a*exp(-s/tau)*(2*tau^2 + 4*tau + 3))/(tau*(2*tau - 2))

To plot the response, set parameters a and tau to their values of 1 and 3, respectively.

yPade22 = subs(yPade22,[a tau],[1 3])

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 = pade(step,'Order',[2 2],'OrderMode','Relative')


yPade22Rel = H(s)*stepPade22Rel
yPade22Rel = ilaplace(yPade22Rel)
yPade22Rel = subs(yPade22Rel,[a tau],[1 3])
fplot(yPade22Rel,[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]', 'Location', 'Best')

stepPade22Rel =

(3*s^2 - 6*s + 4)/(s*(3*s^2 + 6*s + 4))

yPade22Rel =

(a*(3*s^2 - 6*s + 4))/(s*(s*tau + 1)*(3*s^2 + 6*s + 4))

yPade22Rel =

a - (a*exp(-t/tau)*(4*tau^2 + 6*tau + 3))/(4*tau^2 - 6*tau + 3) + (12*a*tau*exp(-t)*(co

yPade22Rel =

(12*exp(-t)*(cos((3^(1/2)*t)/3) + (2*3^(1/2)*sin((3^(1/2)*t)/3))/3))/7 - (19*exp(-t/3))

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

'Pade approximant [4 5]', 'Location', 'Best')

stepPade45 =

(27*s^4 - 180*s^3 + 540*s^2 - 840*s + 560)/(s*(27*s^4 + 180*s^3 + 540*s^2 + 840*s + 560

yPade45 =

(a*(27*s^4 - 180*s^3 + 540*s^2 - 840*s + 560))/(s*(s*tau + 1)*(27*s^4 + 180*s^3 + 540*s

yPade45 =

(27*s^4 - 180*s^3 + 540*s^2 - 840*s + 560)/(s*(3*s + 1)*(27*s^4 + 180*s^3 + 540*s^2 + 8

yPade45 =

(294120*symsum((exp(root(s5^4 + (20*s5^3)/3 + 20*s5^2 + (280*s5)/9 + 560/27, s5, k)*t)*

yPade45 =

3.2418384981662546679005910164486*exp(-1.930807068546914778929595950184*t)*cos(0.578156

2-43
2 Using Symbolic Math Toolbox Software

The following points have been shown:

Pad approximants can model dead-time step inputs.


The accuracy of the Pad approximant increases with the increase in the order of the
approximant.
When a pole or zero exists at the expansion point, the Pad approximant is inaccurate
about the expansion point. To increase the accuracy of the approximant, set
the OrderMode option to Relative. You can also use increase the order of the
denominator relative to the numerator.

2-44
Find Asymptotes, Critical and Inflection Points

Find Asymptotes, Critical and Inflection Points


This section describes how to analyze a simple function to find its asymptotes, maximum,
minimum, and inflection point. The section covers the following topics:

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

To create the function, enter the following commands:

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)

This returns the solutions to x2 + x - 3 = 0 :

roots =
- 13^(1/2)/2 - 1/2
13^(1/2)/2 - 1/2

This tells you that vertical asymptotes are the lines

-1 + 13
x= ,
2

and

-1 - 13
x= .
2

Find Maximum and Minimum


You can see from the graph that f has a local maximum between the points x = 2
and x = 0, and might have a local minimum between x = 6 and x = 2. To find the x-
coordinates of the maximum and minimum, first take the derivative of f:

f1 = diff(f)

f1 =
(6*x + 6)/(x^2 + x - 3) - ((2*x + 1)*(3*x^2 + 6*x - 1))/(x^2 + x - 3)^2

To simplify this expression, enter

f1 = simplify(f1)

f1 =
-(3*x^2 + 16*x + 17)/(x^2 + x - 3)^2

2-47
2 Using Symbolic Math Toolbox Software

You can display f1 in a more readable form by entering

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

It is clear from the graph of f that it has a local minimum at

-8 - 13
x1 = ,
3

and a local maximum at

-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

title('Maximum and Minimum of f')


text(-4.8,5.5,'Local minimum')
text(-2,4,'Local maximum')
hold off

Find Inflection Point


To find the inflection point of f, set the second derivative equal to 0 and solve.

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);

To see the symbolic expression for the inflection point, enter

pretty(simplify(inflec_pt))

2/3 1/3 1/3 2/3 1/3 1/3


2 13 (13 - 3 sqrt(13)) 2 13 (3 sqrt(13) + 13) 8
- ------------------------------- - ------------------------------- - -
6 6 3

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.

fplot(f, [-9 6])


hold on
plot(double(inflec_pt), double(subs(f,inflec_pt)),'ro')
title('Inflection Point of f')
text(-7,1,'Inflection point')
hold off

2-50
Find Asymptotes, Critical and Inflection Points

2-51
2 Using Symbolic Math Toolbox Software

Simplify Symbolic Expressions


Simplification of a mathematical expression is not a clearly defined subject. There
is no universal idea as to which form of an expression is simplest. The form of a
mathematical expression that is simplest for one problem turns out to be complicated
or even unsuitable for another problem. For example, the following two mathematical
expressions present the same polynomial in different forms:

(x + 1)(x - 2)(x + 3)(x - 4),

x - 2x - 13x + 14x + 24.


4 3 2

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.

Besides specific simplifiers, Symbolic Math Toolbox offers a general simplifier,


simplify.

If you do not need a particular form of expressions (expanded, factored, or expressed in


particular terms), use simplify to shorten mathematical expressions. For example, use
this simplifier to find a shorter form for a final result of your computations.

simplify works on various types of symbolic expressions, such as polynomials,


expressions with trigonometric, logarithmic, and special functions. For example, simplify
these polynomials.
syms x y
simplify((1 - x^2)/(1 - x))
simplify((x - 1)*(x + 1)*(x^2 + x + 1)*(x^2 + 1)*(x^2 - x + 1)*(x^4 - x^2 + 1))

ans =
x + 1

ans =
x^12 - 1

Simplify expressions involving trigonometric functions.

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

Simplify expressions involving special functions.


simplify(gamma(x + 1) - x*gamma(x))
simplify(besselj(2, x) + besselj(0, x))

ans =
0

ans =
(2*besselj(1, x))/x

You also can simplify symbolic functions by using simplify.


syms f(x,y)
f(x,y) = exp(x)*exp(y)
f = simplify(f)

f(x, y) =
exp(x)*exp(y)

2-53
2 Using Symbolic Math Toolbox Software

f(x, y) =
exp(x + y)

Simplify Using Options


By default, simplify uses strict simplification rules and ensures that simplified
expressions are always mathematically equivalent to initial expressions. For example, it
does not combine logarithms.
syms x
simplify(log(x^2) + log(x))

ans =
log(x^2) + log(x)

You can apply additional simplification rules which are not correct for all values of
parameters and all cases, but using which simplify can return shorter results. For
this approach, use IgnoreAnalyticConstraints. For example, simplifying the same
expression withIgnoreAnalyticConstraints, you get the result with combined
logarithms.
simplify(log(x^2) + log(x),'IgnoreAnalyticConstraints',true)

ans =
3*log(x)

IgnoreAnalyticConstraints provides a shortcut allowing you to simplify expressions


under commonly used assumptions about values of the variables. Alternatively, you can
set appropriate assumptions on variables explicitly. For example, combining logarithms
is not valid for complex values in general. If you assume that x is a real value, simplify
combines logarithms without IgnoreAnalyticConstraints.
assume(x,'real')
simplify(log(x^2) + log(x))

ans =
log(x^3)

For further computations, clear the assumption on x.


syms x clear

Another approach that can improve simplification of an expression or function is the


syntax simplify(f,'Steps',n), where n is a positive integer that controls how many

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))

Use 50 steps to simplify the expression even further.

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

Simplify Using Assumptions


Some expressions cannot be simplified in general, but become much shorter under
particular assumptions. For example, simplifying this trigonometric expression without
additional assumptions returns the original expression.

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

For further computations, clear the assumption.

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

simplifyFraction((x^3 - x^2*y - x*y^2 + y^3)/(x^3 + y^3))

2-56
Simplify Symbolic Expressions

ans =
(x^2 - 2*x*y + y^2)/(x^2 - x*y + y^2)

By default, simplifyFraction does not expand expressions in the numerator and


denominator of the returned result. To expand the numerator and denominator in the
resulting expression, use the Expand option. For comparison, first simplify this fraction
without Expand.

simplifyFraction((1 - exp(x)^4)/(1 + exp(x))^4)

ans =
(exp(2*x) - exp(3*x) - exp(x) + 1)/(exp(x) + 1)^3

Now, simplify the same expressions with Expand.

simplifyFraction((1 - exp(x)^4)/(1 + exp(x))^4,'Expand',true)

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

Abbreviate Common Terms in Long Expressions


Often, long expressions contain several instances of the same subexpression. Such
expressions look shorter if you replace the subexpression with an abbreviation. For
example, solve this equation.

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

/ 25 sqrt(23) sqrt(108) \1/3

2-58
Abbreviate Common Terms in Long Expressions

#2 == | -- - ------------------ |
\ 54 108 /

pretty uses an internal algorithm to choose which subexpressions to abbreviate. It


also can use nested abbreviations. For example, the term #1 contains the subexpression
abbreviated as #2. This function does not provide any options to enable, disable, or
control abbreviations.

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

Choose Function to Rearrange Expression


Type of Transformation Function
Combine Terms of Same Algebraic combine
Structures on page 2-60
Expand Expressions on page 2-62 expand
Factor Expressions on page 2-63 factor
Extract Subexpressions from Expression children
on page 2-65
Collect Terms with Same Powers on page collect
2-66
Rewrite Expressions in Terms of Other rewrite
Functions on page 2-67
Compute Partial Fraction Decompositions partfrac
of Expressions on page 2-68
Compute Normal Forms of Rational simplifyFraction
Expressions on page 2-69
Represent Polynomials Using Horner horner
Nested Forms on page 2-69

Combine Terms of Same Algebraic Structures


Symbolic Math Toolbox provides the combine function for combining subexpressions
of an original expression. The combine function uses mathematical identities for the
functions you specify. For example, combine the trigonometric expression.

syms x y
combine(2*sin(x)*cos(x),'sincos')

ans =
sin(2*x)

If you do not specify a target function, combine uses the identities for powers wherever
these identities are valid:

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)

To combine these square roots, use the IgnoreAnalyticConstraints option.

combine(sqrt(x)*sqrt(y),'IgnoreanalyticConstraints',true)

ans =
(x*y)^(1/2)

IgnoreAnalyticConstraints provides a shortcut allowing you to combine expressions


under commonly used assumptions about values of the variables. Alternatively, you can
set appropriate assumptions on variables explicitly. For example, assume that x and y
are positive values.

assume([x,y],'positive')
combine(sqrt(x)*sqrt(y))

ans =
(x*y)^(1/2)

For further computations, clear the assumptions on x and y.

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)

For further computations, clear the assumptions.


syms a b c clear

Alternatively, use the IgnoreAnalyticConstraints option when expanding


logarithms.
expand(log(a*b*c),'IgnoreAnalyticConstraints',true)

ans =
log(a) + log(b) + log(c)

expand also works on trigonometric expressions. For example, expand this expression.

2-62
Choose Function to Rearrange Expression

expand(cos(x + y))

ans =
cos(x)*cos(y) - sin(x)*sin(y)

expand uses mathematical identities between the functions.

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

expand works recursively for all subexpressions.

expand((sin(3*x) + 1)*(cos(2*x) - 1))

ans =
2*sin(x) + 2*cos(x)^2 - 10*cos(x)^2*sin(x) + 8*cos(x)^4*sin(x) - 2

To prevent the expansion of all trigonometric, logarithmic, and exponential


subexpressions, use the option ArithmeticOnly.

expand(exp(x + y)*(x + exp(x - y)),'ArithmeticOnly',true)

ans =
exp(x - y)*exp(x + y) + x*exp(x + y)

expand((sin(3*x) + 1)*(cos(2*x) - 1),'ArithmeticOnly',true)

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]

If a polynomial expression is irreducible, factor returns the original expression.


factor(x^3 - 6*x^2 + 11*x - 5)

ans =
x^3 - 6*x^2 + 11*x - 5

Find irreducible polynomial factors of this expression. By default, factor uses


factorization over rational numbers keeping rational numbers in their exact symbolic
form. The resulting factors for this expression do not show polynomial roots.
factor(x^6 + 1)

ans =
[ x^2 + 1, x^4 - x^2 + 1]

Using other factorization modes lets you factor this expression further. For example,
factor the same expression over complex numbers.
factor(x^6 + 1,'FactorMode','complex')

ans =
[ x + 0.86602540378443864676372317075294 + 0.5i,...
x + 0.86602540378443864676372317075294 - 0.5i,...
x + 1.0i,...
x - 1.0i,...
x - 0.86602540378443864676372317075294 + 0.5i,...
x - 0.86602540378443864676372317075294 - 0.5i]

factor also works on expressions other than polynomials and rational expressions. For
example, you can factor the following expression that contains logarithm, sine, and cosine
functions. Internally, factor converts such expressions into polynomials and rational
expressions by substituting subexpressions with variables. After computing irreducible
factors, the function restores original subexpressions.
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))]

Use factor to factor symbolic integers and symbolic rational numbers.


factor(sym(902834092))

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]

Extract Subexpressions from Expression


The children function returns the subexpressions of an expression.

Define an expression f with several subexpressions.

syms x y
f = exp(3*x)*y^3 + exp(2*x)*y^2 + exp(x)*y;

Extract the subexpressions of f by using chlidren.

expr = children(f)

expr =
[ y^2*exp(2*x), y^3*exp(3*x), y*exp(x)]

You can extract lower-level subexpressions by calling children repeatedly on the


results.

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]

Access the contents of the cell array expr2 using braces.

expr2{1}
expr2{2}

ans =
[ y, 2]
ans =
2*x

Collect Terms with Same Powers


If a mathematical expression contains terms with the same powers of a specified
variable or expression, the collect function reorganizes the expression by rouping such
terms. When calling collect, specify the variables that the function must consider as
unknowns. The collect function regards the original expression as a polynomial in the
specified unknowns, and groups the coefficients with equal powers. Group the terms of
an expression with the equal powers of 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.

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, 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.

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, 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

Collect terms of an expression with respect to several unknowns by specifying those


unknowns as a vector.
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, [y,z])

ans =
(3*x^3)*y^4*z^2 + x*y^4 + y*z^2 + (x^2 + 5*x)*y*z + x*z + 2*x^3

Rewrite Expressions in Terms of Other Functions


To present an expression in terms of a particular function, use rewrite. This function
uses mathematical identities between functions. For example, rewrite an expression
containing trigonometric functions in terms of a particular trigonometric function.
syms x
rewrite(sin(x),'tan')

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)

Userewriteto express these trigonometric functions in terms of the exponential


function.
rewrite(sin(x),'exp')

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

Userewriteto express these hyperbolic functions in terms of the exponential function.


rewrite(sinh(x),'exp')

ans =
exp(x)/2 - exp(-x)/2

rewrite(cosh(x),'exp')

ans =
exp(-x)/2 + exp(x)/2

rewrite also expresses inverse hyperbolic functions in terms of logarithms.


rewrite(asinh(x),'log')

ans =
log(x + (x^2 + 1)^(1/2))

rewrite(acosh(x),'log')

ans =
log(x + (x - 1)^(1/2)*(x + 1)^(1/2))

Compute Partial Fraction Decompositions of Expressions


Thepartfrac function returns a rational expression in the form of a sum of a
polynomial and rational terms. In each rational term, the degree of the numerator is
smaller than the degree of the denominator. For some expressions,partfracreturns
visibly simpler forms.
syms x
n = x^6 + 15*x^5 + 94*x^4 + 316*x^3 + 599*x^2 + 602*x + 247;
d = x^6 + 14*x^5 + 80*x^4 + 238*x^3 + 387*x^2 + 324*x + 108;
partfrac(n/d, x)

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]

Compute Normal Forms of Rational Expressions


ThesimplifyFractionfunction represents the original rational expression as a single
rational term with expanded numerator and denominator. The greatest common divisor
of the numerator and denominator of the returned expression is 1. This function is more
efficient for simplifying fractions than the simplify function.

syms x y
simplifyFraction((x^3 + 3*y^2)/(x^2 - y^2) + 3)

ans =
(x^3 + 3*x^2)/(x^2 - y^2)

simplifyFraction cancels common factors that appear in numerator and denominator.

simplifyFraction(x^2/(x + y) - y^2/(x + y))

ans =
x - y

simplifyFraction also handles expressions other than polynomials and rational


functions. Internally, it converts such expressions into polynomials or rational functions
by substituting subexpressions with identifiers. After normalizing the expression with
temporary variables, simplifyFraction restores the original subexpressions.

simplifyFraction((exp(2*x) - exp(2*y))/(exp(x) - exp(y)))

ans =
exp(x) + exp(y)

Represent Polynomials Using Horner Nested Forms


The Horner, or nested, form of a polynomial expression is efficient for numerical
evaluation because it often involves fewer arithmetical operations than other
mathematically equivalent forms of the same polynomial. Typically, this form of an

2-69
2 Using Symbolic Math Toolbox Software

expression is numerically stable. To represent a polynomial expression in a nested form,


use the horner function.

syms x
horner(x^3 - 6*x^2 + 11*x - 6)

ans =
x*(x*(x - 6) + 11) - 6

If polynomial coefficients are floating-point numbers, the resulting Horner form


represents them as rational numbers.
horner(1.1 + 2.2*x + 3.3*x^2)

ans =
x*((33*x)/10 + 11/5) + 11/10

To convert the coefficients in the result to floating-point numbers, use vpa.

vpa(ans)

ans =
x*(3.3*x + 2.2) + 1.1

2-70
Extract Numerators and Denominators of Rational Expressions

Extract Numerators and Denominators of Rational Expressions


To extract the numerator and denominator of a rational symbolic expression, use the
numden function. The first output argument of numden is a numerator, the second
output argument is a denominator. Use numden to find numerators and denominators of
symbolic rational numbers.

[n,d] = numden(1/sym(3))

n =
1

d =
3

Use numden to find numerators and denominators of a symbolic expressions.

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.

syms f(x) g(x)


f(x) = sin(x)/x^2;
g(x) = cos(x)/x;
[n,d] = numden(f)

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

Substitute Variables in Symbolic Expressions


Solve the following trigonometric equation using the ReturnConditions option of the
solver to obtain the complete solution. The solver returns the solution, parameters used
in the solution, and conditions on those parameters.

syms x
eqn = sin(2*x) + cos(x) == 0;
[solx, params, conds] = solve(eqn, x, 'ReturnConditions', true)

solx =
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

Substitute parameter a with a floating-point number. The toolbox converts numbers to


floating-point values, but it keeps intact the symbolic expressions, such as sym(pi),
exp(sym(1)), and so on.

subs(solx, params, vpa(2))

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.

vpa(subs(solx, params, 2))

ans =
7.8539816339744830961566084581988
12.042771838760874080773466302571
16.231562043547265065390324146944

2-74
Substitute Elements in Symbolic Matrices

Substitute Elements in Symbolic Matrices


Create a 3-by-3 circulant matrix using the backward shift.
syms a b c
M = [a b c; b c a; c a b]

M =
[ a, b, c]
[ b, c, a]
[ c, a, b]

Replace variable b in 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).

Replace all elements whose value is M(1,3) = c with the expression a + 2.


M = subs(M, M(1,3), a + 2)

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.

Find eigenvalues and eigenvectors of the matrix.


[V,E] = eig(M)

V =

2-75
2 Using Symbolic Math Toolbox Software

[ 1, 3^(1/2)/2 - 1/2, - 3^(1/2)/2 - 1/2]


[ 1, - 3^(1/2)/2 - 1/2, 3^(1/2)/2 - 1/2]
[ 1, 1, 1]

E =
[ 3*a + 3, 0, 0]
[ 0, 3^(1/2), 0]
[ 0, 0, -3^(1/2)]

Replace the symbolic parameter a with the value 1.

subs(E, a, 1)

ans =
[ 6, 0, 0]
[ 0, 3^(1/2), 0]
[ 0, 0, -3^(1/2)]

2-76
Substitute Scalars with Matrices

Substitute Scalars with Matrices


Create the following expression representing the sine function.
syms w t
f = sin(w*t);

Suppose, your task involves creating a matrix whose elements are sine functions with
angular velocities represented by a Toeplitz matrix. First, create a 4-by-4 Toeplitz
matrix.
W = toeplitz(sym([3 2 1 0]))

W =
[ 3, 2, 1, 0]
[ 2, 3, 2, 1]
[ 1, 2, 3, 2]
[ 0, 1, 2, 3]

Next, replace the variable w in the expression f with the Toeplitz matrix W. When you
replace a scalar in a symbolic expression with a matrix, subs expands the expression
into a matrix. In this example, subs expands f = sin(w*t) into a 4-by-4 matrix
whose elements are sin(w*t). Then it replaces w in that matrix with the corresponding
elements of the Toeplitz matrix W.
F = subs(f, w, W)

F =
[ sin(3*t), sin(2*t), sin(t), 0]
[ sin(2*t), sin(3*t), sin(2*t), sin(t)]
[ sin(t), sin(2*t), sin(3*t), sin(2*t)]
[ 0, sin(t), sin(2*t), sin(3*t)]

Find the sum of these sine waves at t = , t = /2, t = /3, t = /4, t = /5,
and t = /6. First, find the sum of all elements of matrix F. Here, the first call to sum
returns a row vector containing sums of elements in each column. The second call to sum
returns the sum of elements of that row vector.
S = sum(sum(F))

S =
6*sin(2*t) + 4*sin(3*t) + 4*sin(t)

Now, use subs to evaluate S for particular values of the variable 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

Use subs to Evaluate Expressions and Functions


In this section...
Evaluate Expressions on page 2-79
Evaluate Functions on page 2-80

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;

Now, assign a numeric value to x.

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

After this assignment, y is independent of x.

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;

Now, assign a numeric value to x.

x = 2;

The function itself does not change: the body of the function is still the symbolic
expression x^2.

f(x) =
x^2

In case of symbolic expressions, the recommended approach is to use subs to evaluate


the expression with the most recent values of its parameters. This approach is not
recommended for symbolic functions. For example, if you evaluate f using the subs
function, the result is the expected value 4, but it is assigned to a symbolic function,
fnew. This new symbolic function formally depends on the variable x.

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 remains independent of the value assigned to x.

f
[f(1),f(2),f(3)]

f(x) =
x^2

ans =
[ 1, 4, 9]

2-81
2 Using Symbolic Math Toolbox Software

Choose Symbolic or Numeric Arithmetic


Symbolic Math Toolbox operates on numbers by using either symbolic or numeric
arithmetic. Numeric arithmetic is either variable precision or double precision. The
following information compares symbolic, variable-precision, and double-precision
arithmetic.

Symbolic Variable Precision Double Precision


Example: Find sin() a = sym(pi) b = vpa(pi) pi
sin(a) sin(b) sin(pi)

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

Increase Precision of Numeric Calculations


By default, MATLAB uses 16 digits of precision. For higher precision, use the vpa
function in Symbolic Math Toolbox. vpa provides variable precision which can be
increased without limit.

When you choose variable-precision arithmetic, by default, vpa uses 32 significant


decimal digits of precision. For details, see Choose Symbolic or Numeric Arithmetic on
page 2-82. You can set a higher precision by using the digits function.

Approximate a sum using the default precision of 32 digits. If at least one input is
wrapped with vpa, all other inputs are converted to variable precision automatically.
vpa(1/3) + 1/2

ans =
0.83333333333333333333333333333333

You must wrap all inner inputs with vpa, such as exp(vpa(200)). Otherwise, the
inputs are automatically converted to double by MATLAB.

Increase the precision to 50 digits by using digits and save the old value of digits in
digitsOld. Repeat the sum.
digitsOld = digits(50);
sum50 = vpa(1/3) + 1/2

sum50 =
0.83333333333333333333333333333333333333333333333333

Restore the old value of digits for further calculations.


digits(digitsOld)

Note: vpa output is symbolic. To use symbolic output with a MATLAB function that does
not accept symbolic values, convert symbolic values to double precision by using double.

Check the current digits setting by calling digits.


digits

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 % digits remains 32

Digits = 32

Variable precision can be increased arbitrarily. Find pi to 500 digits.

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

Recognize and Avoid Round-Off Errors


When approximating a value numerically, remember that floating-point results can be
sensitive to the precision used. Also, floating-point results are prone to round-off errors.
The following approaches can help you recognize and avoid incorrect results.

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

Use Symbolic Computations When Possible


Performing computations symbolically on page 2-82 is recommended because exact
symbolic computations are not prone to round-off errors. For example, standard
mathematical constants have their own symbolic representations in Symbolic Math
Toolbox:

pi
sym(pi)

ans =
3.1416

ans =
pi

Avoid unnecessary use of numeric approximations. A floating-point number


approximates a constant; it is not the constant itself. Using this approximation, you can
get incorrect results. For example, the heaviside special function returns different
results for the sine of sym(pi) and the sine of the numeric approximation of pi:

heaviside(sin(sym(pi)))
heaviside(sin(pi))

ans =
1/2

2-86
Recognize and Avoid Round-Off Errors

ans =
1

Perform Calculations with Increased Precision


The Riemann hypothesis states that all nontrivial zeros of the Riemann Zeta function (z)
have the same real part (z) = 1/2. To locate possible zeros of the Zeta function, plot its
absolute value |(1/2 + iy)|. The following plot shows the first three nontrivial roots of
the Zeta function |(1/2 + iy)|.

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:

vpasolve(zeta(1/2 + i*y), y, 15)


vpasolve(zeta(1/2 + i*y), y, 20)
vpasolve(zeta(1/2 + i*y), y, 25)

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

For further computations, restore the default number of digits:

digits(old)

2-88
Recognize and Avoid Round-Off Errors

Compare Symbolic and Numeric Results


Bessel functions with half-integer indices return exact symbolic expressions.
Approximating these expressions by floating-point numbers can produce very unstable
results. For example, the exact symbolic expression for the following Bessel function is:

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

Use vpa to approximate this expression with the 10-digit accuracy:

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

Plot the Function or Expression


Plotting the results can help you recognize incorrect approximations. For example, the
numeric approximation of the following Bessel function returns:

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

Increase Speed by Reducing Precision


Increase MATLABs speed by reducing the precision of your calculations. Reduce
precision by using variable-precision arithmetic provided by the vpa and digits
functions in Symbolic Math Toolbox. When you reduce precision, you are gaining
performance by reducing accuracy. For details, see Choose Symbolic or Numeric
Arithmetic on page 2-82.

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;

Then, find the time taken to calculate zeta(C).

tic
zeta(C);
toc

Elapsed time is 340.204407 seconds.

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

Elapsed time is 113.792543 seconds.

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;

Running zeta(vpa(C)) with 10-digit precision takes 15 minutes, while running


zeta(C) takes three times as long.

digits(10)
vpaC = vpa(C);
tic
zeta(vpaC);
toc

Elapsed time is 886.035806 seconds.

tic
zeta(C);
toc

Elapsed time is 2441.991572 seconds.

Note: If you want to increase precision, see Increase Precision of Numeric Calculations
on page 2-84.

2-92
Numeric to Symbolic Conversion

Numeric to Symbolic Conversion


This topic shows how Symbolic Math Toolbox converts numbers into symbolic form.
For an overview of symbolic and numeric arithmetic, see Choose Symbolic or Numeric
Arithmetic on page 2-82.

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

Conversion to Rational Symbolic Form


Convert input to exact rational form by calling sym with the 'r' flag. This is the default
behavior when you call sym without flags.
sym(t, 'r')

ans =
1/10

Conversion by Using Floating-Point Expansion


If you call sym with the flag 'f', sym converts double-precision, floating-point numbers
to their numeric value by using N*2^e, where N and e are the exponent and mantissa
respectively.

Convert t by using a floating-point expansion.


sym(t, 'f')

ans =
3602879701896397/36028797018963968

Conversion to Rational Symbolic Form with Error Term


If you call sym with the flag 'e', sym returns the rational form of t plus the error
between the estimated, exact value for t and its floating-point representation. This error
is expressed in terms of eps (the floating-point relative precision).

Convert t to symbolic form. Return the error between its estimated symbolic form and its
floating-point value.
sym(t, 'e')

ans =
eps/40 + 1/10

The error term eps/40 is the difference between sym('0.1') and sym(0.1).

Conversion to Decimal Form


If you call sym with the flag 'd', sym returns the decimal expansion of the input. The
digits function specifies the number of significant digits used. The default value of
digits is 32.

2-95
2 Using Symbolic Math Toolbox Software

sym(t,'d')

ans =
0.10000000000000000555111512312578

Change the number of significant digits by using digits.

digitsOld = digits(7);
sym(t,'d')

ans =
0.1

For further calculations, restore the old value of digits.

digits(digitsOld)

2-96
Basic Algebraic Operations

Basic Algebraic Operations


Basic algebraic operations on symbolic objects are the same as operations on MATLAB
objects of class double. This is illustrated in the following example.

The Givens transformation produces a plane rotation through the angle t. The
statements

syms t
G = [cos(t) sin(t); -sin(t) cos(t)]

create this transformation matrix.

G =
[ cos(t), sin(t)]
[ -sin(t), cos(t)]

Applying 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]

The simplify function

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

Linear Algebraic Operations


The following examples show how to do several basic linear algebraic operations using
Symbolic Math Toolbox software.

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]

This allows subsequent symbolic operations on H to produce results that correspond


to the infinitely precise Hilbert matrix, sym(hilb(3)), not its floating-point
approximation, hilb(3). Therefore,

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

produce the solution


x =
3
-24
30

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]

shows the loss of two digits. So does


1/det(V)

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

Since H is nonsingular, calculating the null space of H with the command

null(H)

returns an empty matrix:

ans =
Empty sym: 1-by-0

Calculating the column space of H with

colspace(H)

returns a permutation of the identity matrix:

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)

substitutes the computed value of sol for s in H to give


H =
[ 8/9, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]

Now, the command


det(H)

returns
ans =
0

and
inv(H)

produces the message


ans =
FAIL

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 variable-precision counterparts are E = eig(vpa(A)) and [V,E] =


eig(vpa(A)).

The eigenvalues of A are the zeros of the characteristic polynomial of A, det(A-x*I),


which is computed by charpoly(A).

The matrix H from the last section provides the first example:

H = sym([8/9 1/2 1/3; 1/2 1/3 1/4; 1/3 1/4 1/5])

H =
[ 8/9, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]

The matrix is singular, so one of its eigenvalues must be zero. The statement

[T,E] = eig(H)

produces the matrices T and E. The columns of T are the eigenvectors of H and the
diagonal elements of E are the eigenvalues of H:
T =
[ 3/10, 218/285 - (4*12589^(1/2))/285, (4*12589^(1/2))/285 + 218/285]
[ -6/5, 292/285 - 12589^(1/2)/285, 12589^(1/2)/285 + 292/285]
[ 1, 1, 1]

E =
[ 0, 0, 0]
[ 0, 32/45 - 12589^(1/2)/180, 0]
[ 0, 0, 12589^(1/2)/180 + 32/45]

It may be easier to understand the structure of the matrices of eigenvectors, T, and


eigenvalues, E, if you convert T and E to decimal notation. To do so, proceed as follows.
The commands

Td = double(T)
Ed = double(E)

return

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)

to find all these values


ans =
0
1000
1000
1020
510 - 100*26^(1/2)
100*26^(1/2) + 510
-10*10405^(1/2)
10*10405^(1/2)

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;

and then try


p = charpoly(S, x)

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.

For this modified Rosser matrix

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

Symbolic Math Toolbox commands

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]

You can simplify this expression using simplify:

G = simplify(G)

G =
[ cos(t), sin(t)]
[ -sin(t), cos(t)]

Next, the command


g = eig(G)

produces
g =
cos(t) - sin(t)*1i
cos(t) + sin(t)*1i

You can rewrite g in terms of exponents:

g = rewrite(g, 'exp')

g =
exp(-t*1i)
exp(t*1i)

2-109
2 Using Symbolic Math Toolbox Software

Jordan Canonical Form


The Jordan canonical form (Jordan normal form) results from attempts to convert
a matrix to its diagonal form by a similarity transformation. For a given matrix A,
find a nonsingular matrix V, so that inv(V)*A*V, or, more succinctly, J = V\A*V,
is as close to diagonal as possible. For almost all matrices, the Jordan canonical
form is the diagonal matrix of eigenvalues and the columns of the transformation
matrix are the eigenvectors. This always happens if the matrix is symmetric or if it has
distinct eigenvalues. Some nonsymmetric matrices with multiple eigenvalues cannot be
converted to diagonal forms. The Jordan form has the eigenvalues on its diagonal, but
some of the superdiagonal elements are one, instead of zero. The statement
J = jordan(A)

computes the Jordan canonical form of A. The statement

[V,J] = jordan(A)

also computes the similarity transformation where J = inv(V)*A*V. The columns of V


are the generalized eigenvectors of A.

The Jordan form is extremely sensitive to changes. Almost any change in A causes its
Jordan form to be diagonal. This implies that A must be known exactly (i.e., without
round-off error, etc.) and makes it very difficult to compute the Jordan form reliably with
floating-point arithmetic. Thus, computing the Jordan form with floating-point values is
unreliable and not recommended.

For example, let


A = sym([12,32,66,116;-25,-76,-164,-294;
21,66,143,256;-6,-19,-41,-73])

A =
[ 12, 32, 66, 116]
[ -25, -76, -164, -294]
[ 21, 66, 143, 256]
[ -6, -19, -41, -73]

Then
[V,J] = jordan(A)

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

A*V(:,2) = 1*V(:,2) + V(:,1)


A*V(:,4) = 2*V(:,4) + V(:,3)

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

Singular Value Decomposition


Singular value decomposition expresses an m-by-n matrix A as A = U*S*V'. Here, S
is an m-by-n diagonal matrix with singular values of A on its diagonal. The columns of
the m-by-m matrix U are the left singular vectors for corresponding singular values. The
columns of the n-by-n matrix V are the right singular vectors for corresponding singular
values. V' is the Hermitian transpose (the complex conjugate of the transpose) of V.

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)

or with one output argument


S = svd(A)

To compute singular values and singular vectors of a matrix, use three output
arguments:
[U,S,V] = svd(A)

svd returns two unitary matrices, U and V, the columns of which are singular vectors.
It also returns a diagonal matrix, S, containing singular values on its diagonal. The
elements of all three matrices are floating-point numbers. The accuracy of computations
is determined by the current setting of digits.

Create the n-by-n matrix A with elements defined by A(i,j) = 1/(i - j + 1/2). The
most obvious way of generating this matrix is
n = 3;
for i = 1:n
for j = 1:n
A(i,j) = sym(1/(i-j+1/2));
end
end

For n = 3, the matrix is


A

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

Now, compute the singular values and singular vectors of A:

[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

Solve Algebraic Equation


Symbolic Math Toolbox offers both symbolic and numeric equation solvers. This topic
shows you how to solve an equation symbolically using the symbolic solver solve. To
compare symbolic and numeric solvers, see Select Numeric or Symbolic Solver on page
2-119.

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.

Return the Full Solution to an Equation


solve does not automatically return all solutions of an equation. Solve the equation
cos(x) == -sin(x). The solve function returns one of many solutions.
syms x
solx = solve(cos(x) == -sin(x), 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.

Work with the Full Solution, Parameters, and Conditions Returned by


solve
You can use the solutions, parameters, and conditions returned by solve to find
solutions within an interval or under additional conditions.

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

To find values of x corresponding to these values of k, use subs to substitute for k in


solx.

xvalues = subs(solx, solk)

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

Visualize and Plot Solutions Returned by solve


The previous sections used solve to solve the equation cos(x) == -sin(x). The
solution to this equation can be visualized using plotting functions such as fplot and
scatter.

Plot both sides of equation cos(x) == -sin(x).

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

As expected, the solutions appear at the intersection of the two plots.

Simplify Complicated Results and Improve Performance


If results look complicated, solve is stuck, or if you want to improve performance, see,
Troubleshoot Equation Solutions from solve Function on page 2-132.

2-118
Select Numeric or Symbolic Solver

Select Numeric or Symbolic Solver


You can solve equations to obtain a symbolic or numeric answer. For example, a solution
to cos ( x ) = -1 is pi in symbolic form and 3.14159 in numeric form. The symbolic
solution is exact, while the numeric solution approximates the exact symbolic solution.
Symbolic Math Toolbox offers both symbolic and numeric equation solvers. This table can
help you choose either the symbolic solver (solve) or the numeric solver (vpasolve).
A possible strategy is to try the symbolic solver first, and use the numeric solver if the
symbolic solver is stuck.

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

Solve Equations Numerically on page 2-140


Solve System of Linear Equations on page 2-137

2-120
Solve System of Algebraic Equations

Solve System of Algebraic Equations


This topic shows you how to solve a system of equations symbolically using Symbolic
Math Toolbox. This toolbox offers both numeric and symbolic equation solvers. For a
comparison of numeric and symbolic solvers, see Select Numeric or Symbolic Solver on
page 2-119.

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

Handle the Output of solve


Suppose you have the system

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)

The call returns the following.


solx =
0
a
soly =

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)

Four distinct solutions are produced.


solx =
a/2 - (a^2 - 2)^(1/2)/2
a/2 - (a^2 + 2)^(1/2)/2
a/2 + (a^2 - 2)^(1/2)/2
a/2 + (a^2 + 2)^(1/2)/2
soly =
- a - (a^2 - 2)^(1/2)
- a - (a^2 + 2)^(1/2)
(a^2 - 2)^(1/2) - a
(a^2 + 2)^(1/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)

The solver returns its results enclosed in this structure.


S =
struct with fields:

a: [21 sym]
u: [21 sym]
v: [21 sym]

The solutions for a reside in the a-field of S.

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]

Clear solx and soly for further use.


clear solx soly

Solve a Linear System of Equations


Linear systems of equations can also be solved using matrix division. For example, solve
this system.
clear u v x y
syms u v x y
eqns = [x + 2*y == u, 4*x + 5*y == v];
S = solve(eqns);
sol = [S.x; S.y]

[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.

Return the Full Solution of a System of Equations


solve does not automatically return all solutions of an equation. To return all solutions
along with the parameters in the solution and the conditions on the solution, set the
ReturnConditions option to true.

Consider the following system of equations:

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 = solve(eqn1, eqn2, 'ReturnConditions', 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.

Index into S to return the solutions, parameters, and conditions.


S.x
S.y
S.parameters
S.conditions

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 a System of Equations Under Conditions


To solve the system of equations under conditions, specify the conditions in the input to
solve.

Solve the system of equations considered above for x and y in the interval -2*pi to
2*pi. Overlay the solutions on the plot using scatter.
Srange = solve(eqn1, eqn2, -2*pi<x, x<2*pi, -2*pi<y, y<2*pi, 'ReturnConditions', true);

2-126
Solve System of Algebraic Equations

scatter(Srange.x, Srange.y,'k')

Work with Solutions, Parameters, and Conditions Returned by solve


You can use the solutions, parameters, and conditions returned by solve to find
solutions within an interval or under additional conditions. This section has the same
goal as the previous section, to solve the system of equations within a search range, but
with a different approach. Instead of placing conditions directly, it shows how to work
with the parameters and conditions returned by solve.

For the full solution S of the system of equations, find values of x and y in the interval
-2*pi to 2*pi by solving the solutions S.x and S.y for the parameters S.parameters
within that interval under the condition S.conditions.

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))

Find the parameters in S.x and S.y.


paramx = intersect(symvar(S.x), S.parameters)
paramy = intersect(symvar(S.y), S.parameters)

paramx =
z1
paramy =
z

Solve the first solution of x for the parameter paramx.


solparamx(1,:) = solve(S.x(1) > -2*pi, S.x(1) < 2*pi, paramx)

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)]

Similarly, solve the first solution of y for paramy.


solparamy(1,:) = solve(S.y(1) > -2*pi, S.y(1) < 2*pi, paramy)

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)]

Clear the assumptions set by S.conditions(1) using assume. Call asumptions to


check that the assumptions are cleared.
assume(S.parameters,'clear')
assumptions

ans =
Empty sym: 1-by-0

Assume the conditions for the second solution.


assume(S.conditions(2))

Solve the second solution to x and y for the parameters paramx and paramy.

2-128
Solve System of Algebraic Equations

solparamx(2,:) = solve(S.x(2) > -2*pi, S.x(2) < 2*pi, paramx)


solparamy(2,:) = solve(S.y(2) > -2*pi, S.y(2) < 2*pi, paramy)

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(1,:) = subs(S.x(1), paramx, solparamx(1,:));


solx(2,:) = subs(S.x(2), paramx, solparamx(2,:))
soly(1,:) = subs(S.y(1), paramy, solparamy(1,:));
soly(2,:) = subs(S.y(2), paramy, solparamy(2,:))

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

Convert Symbolic Results to Numeric Values


Symbolic calculations provide exact accuracy, while numeric calculations are
approximations. Despite this loss of accuracy, you might need to convert symbolic
results to numeric approximations for use in numeric calculations. For a high-accuracy
conversion, use variable-precision arithmetic provided by the vpa function. For standard
accuracy and better performance, convert to double precision using double.

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]

Simplify Complicated Results and Improve Performance


If results look complicated, solve is stuck, or if you want to improve performance, see,
Troubleshoot Equation Solutions from solve Function on page 2-132.

2-131
2 Using Symbolic Math Toolbox Software

Troubleshoot Equation Solutions from solve Function


If solve returns solutions that look complicated, or if solve cannot handle an input,
there are many options. These options simplify the solution space for solve. These
options also help solve when the input is complicated, and might allow solve to return
a solution where it was previously stuck.

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

Return Only Real Solutions


Solve the equation x^5 - 1 == 0. This equation has five solutions.

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.

solve(x^5 - 1, x, 'Real', true)

ans =
1

Apply Simplification Rules


Solve the following equation. The solve function returns a complicated solution.

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)

To apply simplification rules when solving equations, specify the


IgnoreAnalyticConstraints option as true. The applied simplification rules are
not generally correct mathematically but might produce useful solutions, especially in
physics and engineering. With this option, the solver does not guarantee the correctness
and completeness of the result.

solve(x^(5/2) + 1/x^(5/2) == 1, x, 'IgnoreAnalyticConstraints', true)

ans =
1/(1/2 - (3^(1/2)*1i)/2)^(2/5)
1/((3^(1/2)*1i)/2 + 1/2)^(2/5)

This solution is simpler and more usable.

Use Assumptions to Narrow Results


For solutions to specific cases, set assumptions to return appropriate solutions. Solve the
following equation. The solve function returns seven solutions.

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

solve(x^7 + 2*x^6 - 59*x^5 - 106*x^4 + 478*x^3 + 284*x^2 - 1400*x + 800, x)

ans =
1
17^(1/2)/2 - 1/2
5*2^(1/2)
5^(1/2) - 1

Place the additional assumption that x is an integer using in(x,'integer'). Place


additional assumptions on variables using assumeAlso.
assumeAlso(in(x,'integer'))
solve(x^7 + 2*x^6 - 59*x^5 - 106*x^4 + 478*x^3 + 284*x^2 - 1400*x + 800, x)

ans =
1

solve returns the only positive, integer solution to x.

Clear the assumptions on x for further computations.


syms x clear

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.

Clear the assumptions on the variables for further computations.


syms a c f h clear

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

Call simplify to simplify solution S.


simplify(S)

ans =
-log(37^(1/2)*(- 1/37 - 6i/37))*1i
log(2)*1i - (log(- 140/37 + 48i/37)*1i)/2

Call simplify with more steps to simplify the result even further.
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

Solve System of Linear Equations


This section shows you how to solve a system of linear equations using the Symbolic
Math Toolbox.

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

Solve System of Linear Equations Using linsolve


A system of linear equations

a11 x1 + a12 x2 + + a1n xn = b1


a21 x1 + a22 x2 + + a2n xn = b2
L
am1 x1 + am2 x2 + + amn xn = bm

can be represented as the matrix equation A x = b , where A is the coefficient matrix,


r r

a11 a1n

A= M O M
a
m1 L amn

and b is the vector containing the right sides of equations,


r

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

Declare the system of equations.

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,B] = equationsToMatrix([eqn1, eqn2, eqn3], [x, y, z])

A =
[ 2, 1, 1]
[ -1, 1, -1]
[ 1, 2, 3]

B =
2
3
-10

Use linsolve to solve AX = B for the vector of unknowns X.

X = linsolve(A,B)

X =
3
1
-5

From X, x=3, y=1 and z=-5.

Solve System of Linear Equations Using solve


Use solve instead of linsolve if you have the equations in the form of expressions and
not a matrix of coefficients. Consider the same system of linear equations.

2-138
Solve System of Linear Equations

2x + y + z = 2
-x + y - z = 3
x + 2 y + 3 z = -10

Declare the system of equations.


syms x y z
eqn1 = 2*x + y + z == 2;
eqn2 = -x + y - z == 3;
eqn3 = x + 2*y + 3*z == -10;

Solve the system of equations using solve. The inputs to solve are a vector of
equations, and a vector of variables to solve the equations for.
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

Solve Equations Numerically


The Symbolic Math Toolbox offers both numeric and symbolic equation solvers. For a
comparison of numeric and symbolic solvers, please see Select Numeric or Symbolic
Solver on page 2-119. An equation or a system of equations can have multiple solutions.
To find these solutions numerically, use the function vpasolve. For polynomial
equations, vpasolve returns all solutions. For nonpolynomial equations, vpasolve
returns the first solution it finds. This shows you how to use vpasolve to find solutions
to both polynomial and nonpolynomial equations, and how to obtain these solutions to
arbitrary precision.

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

Find All Roots of a Polynomial Function

Use vpasolve to find all the solutions to function f ( x ) = 6 x7 - 2 x6 + 3 x3 - 8 .

syms f(x)
f(x) = 6*x^7-2*x^6+3*x^3-8;
sol = vpasolve(f)

sol =
1.0240240759053702941448316563337
- 0.88080620051762149639205672298326 + 0.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

Find Zeros of a Nonpolynomial Function Using Search Ranges and


Starting Points

Consider the function f ( x ) = e(


x / 7)
cos( 2 x) . A plot of the function reveals periodic zeros,
with increasing slopes at the zero points as x increases.

syms x
h = fplot(exp(x/7)*cos(2*x),[-2 25]);
grid on

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)

Warning: All variables have a starting value for the numeric...


search. The option 'random' has no effect in this case.
> In sym.vpasolve at 166
ans =
14.922565104551517882697556070578

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.

The function is explained section by section here.

Declare the function with the two inputs and one output.

function sol = findzeros(f,range,err)

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

Find a zero in the search range using vpasolve.

sol = vpasolve(f,range);

If vpasolve does not find a zero, exit.

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.

temp = findzeros(f,[range(1) lowLimit],1);


if ~isempty(temp)
sol = sort([sol temp]);
end

Call findzeros with the higher search range. If findzeros returns zeros, copy the
values into the solution array and sort them.

temp = findzeros(f,[highLimit range(2)],1);


if ~isempty(temp)
sol = sort([sol temp]);
end
return
end
end

The entire function findzeros is as follows.

2-144
Solve Equations Numerically

function sol = findzeros(f,range,err)


if nargin < 3
err = 1e-3;
end
sol = vpasolve(f,range);
if(isempty(sol))
return
else
lowLimit = sol-err;
highLimit = sol+err;
temp = findzeros(f,[range(1) lowLimit],1);
if ~isempty(temp)
sol = sort([sol temp]);
end
temp = findzeros(f,[highLimit range(2)],1);
if ~isempty(temp)
sol = sort([sol temp]);
end
return
end
end

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]

Obtain Solutions to Arbitrary Precision


Use digits to set the precision of the solutions. By default, vpasolve returns solutions
to a precision of 32 significant figures. Use digits to increase the precision to 64
significant figures. When modifying digits, ensure that you save its current value so
that you can restore it.

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

Solve Multivariate Equations Using Search Ranges


Consider the following system of equations.

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.3697477224547979209101337160174, 0.33025227754520207908986628398261, 2.293354376823

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 =

[ 0.91062661725633361176950031551069, 1.7893733827436663882304996844893, 3.964101572135

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 =

[ 0.91062661725633361176950031551069, 1.7893733827436663882304996844893, 3.96410157213


[ 2.3697477224547979209101337160174, 0.33025227754520207908986628398261, 2.29335437682
[ 0.91062661725633361176950031551069, 1.7893733827436663882304996844893, 3.96410157213
[ 0.91062661725633361176950031551069, 1.7893733827436663882304996844893, 3.96410157213
[ 0.91062661725633361176950031551069, 1.7893733827436663882304996844893, 3.96410157213

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

axis([0 2.5 0 2.5 -20 10])


hold on
scatter3(sol(:,1),sol(:,2),sol(:,3),600,'yellow','X','LineWidth',2)
title('Randomly found solutions in specified search range')
cz = ax.Children;
caxis([0 20])
view(69,28)
hold off

2-150
Solve a Single Differential Equation

Solve a Single Differential Equation


Use dsolve to compute symbolic solutions to ordinary differential equations. Specify
differential equations as symbolic expressions containing diff.

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)

For details, see Create Symbolic Functions on page 1-7.

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.

For output from dsolve, you can:

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.

First-Order Linear ODE


Suppose you want to solve the equation y'(t) = t*y. First, create the symbolic
function y(t):
syms y(t)

Now use dsolve to solve the equation:


y(t) = dsolve(diff(y,t) == t*y)

y(t) =
C2*exp(t^2/2)

y(t) = C2*exp(t^2/2) is a solution to the equation for any constant C2.

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)

Second-Order ODE with Initial Conditions


Solve this second-order differential equation with two initial conditions. One initial
condition is a derivative y'(x) at x = 0. To be able to specify this initial condition,
create an additional symbolic function Dy = diff(y). (You also can use any valid
function name instead of Dy.) Then Dy(0) = 0 specifies that Dy = 0 at x = 0.

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

u(0) = 1, u(0) = -1, u(0) = p ,

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) =

(pi*exp(x))/3 - exp(-x/2)*cos((3^(1/2)*x)/2)*(pi/3 - 1) -...


(3^(1/2)*exp(-x/2)*sin((3^(1/2)*x)/2)*(pi + 1))/3

More ODE Examples


This table shows examples of differential equations and their Symbolic Math Toolbox
syntax. The last example is the Airy differential equation, whose solution is called the
Airy function.

Differential Equation MATLAB Command


dy syms y(t)
+ 4 y(t) = e-t dsolve(diff(y) + 4*y == exp(-t), y(0) ==
dt
1)
y(0) = 1
2x2y + 3xy y = 0 syms y(x)
( = d/dx) dsolve(2*x^2*diff(y, 2) + 3*x*diff(y) -
y == 0)
syms y(x)
d2 y
= xy( x) dsolve(diff(y, 2) == x*y, y(0) == 0,
dx2 y(3) == besselk(1/3, 2*sqrt(3))/pi)

1
y(0) = 0, y(3) = K1/ 3 ( 2 3)
p

(The Airy equation)

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

Solve a System of Differential Equations


dsolve can handle several ordinary differential equations in several variables, with or
without initial conditions.

In this section...
Solve System of Differential Equations on page 2-155
Solve Differential Equations in Matrix Form on page 2-157

Solve System of Differential Equations


Solve the system of linear first-order differential equations

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.

syms f(t) g(t)


eqn1 = diff(f) == 3*f + 4*g;
eqn2 = diff(g) == -4*f + 3*g;

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]

To return f(t) and g(t), access the elements of S.

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), gSol(t)] = dsolve(eqn1, eqn2)

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)

Specifying initial conditions allows dsolve to find the values of constants.

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)

Visualize the solutions by using fplot.

fplot(fSol)
hold on
fplot(gSol)
grid on
legend('fSol','gSol','Location','best')

2-156
Solve a System of Differential Equations

Solve Differential Equations in Matrix Form


You can solve differential equations in matrix form by using dsolve.

Consider the system of differential equations

dx
= x + 2 y + 1,
dt
dy
= - x + y + t.
dt

The system can be represented in matrix form as

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

The relation is now Y=AY + B.

Define these matrices and the matrix equation.

syms x(t) y(t)


A = [1 2; -1 1];
B = [1; t];
Y = [x; y];
eqn = diff(Y) == A*Y + B

eqn(t) =
diff(x(t), t) == x(t) + 2*y(t) + 1
diff(y(t), t) == t - x(t) + y(t)

Solve the matrix equation by using dsolve.

[xSol(t), ySol(t)] = dsolve(eqn)

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)

Simplify the solution by using simplify.

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.

C = Y(0) == [2; -1];


[xSol(t), ySol(t)] = dsolve(eqn, C)

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

Visualize the solutions by using fplot.

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

Differential Algebraic Equations


A system of differential algebraic equations is a system of equations involving unknown
functions of one independent variable (typically, the time variable t) and their
derivatives. These functions are often called state variables. A general form of a DAE
system is

F ( x& ( t ) , x ( t ) , t ) = 0

The number of equations F = [ F1 , , Fn ] must match the number of state variables


x ( t ) = [ x1 ( t ) , , xn ( t) ] .

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

Set Up Your DAE Problem


Often, you can solve a system of differential algebraic equations (DAEs) by converting
it to a system of DAEs with differential index 1 or 0, and then using MATLAB solvers,
such as ode15i, ode15s, or ode23t. These solvers have their own requirements for the
system of equations and initial conditions. Most DAE systems do not directly come in the
form suitable for the MATLAB solvers, but you can convert them to a suitable form.

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

Step 1: Equations and Variables


Specify equations and state variables of the system. A system of differential algebraic
equations includes equations, dependent variables (state variables), and an independent
variable t. Specify equations as symbolic equations (using the == operator) or as symbolic
expressions. If you use symbolic expressions, the toolbox assumes that these expressions
are equations with right sides equal to 0.

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];

vars = [x(t); y(t); T(t)];

Alternatively, you can specify the same equations as symbolic expressions.


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];

Step 2: Differential Order


Determine if the differential order of the system is 1. For example, the differential order
of the two-dimensional pendulum system is 2.

If the system involves higher order differential equations, use


reduceDifferentialOrder to convert all higher order equations to first-order
equations by substituting derivatives with additional state variables. See Reduce
Differential Order of DAE Systems on page 2-167.

Step 3: Differential Index


Check the differential index of the system. To be able to use the MATLAB solvers
ode15i, ode15s, or ode23t, your DAE system must be of differential index 1 or 0.
(In the latter case, it is a system of ordinary differential equations.) If the differential
index of the system is 2 or higher, then reduce it by using reduceDAEIndex or
reduceDAEToODE. See Check and Reduce Differential Index on page 2-169.

Step 4: MATLAB Function Handles


Convert the system to MATLAB functions acceptable by the MATLAB solvers. If you
want to use the ode15i solver, then use daeFunction to convert the system to a

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.

Step 5: Consistent Initial Conditions


If you reduced the differential index of the system, then find consistent initial conditions
for the new system. See Find Consistent Initial Conditions on page 2-180.

Step 6: ODE Solvers


Use one of the MATLAB solvers, ode15i, ode15s, or ode23t, to solve the system. See
Solve DAE Systems Using MATLAB ODE Solvers on page 2-186.

Solving DAE Systems Flow Chart


This flow chart shows possible sequences of steps that you might need to take when
solving a DAE system. The flow chart includes the functions that you might need to use.
The process involves MATLAB functions, as well as functions available in Symbolic Math
Toolbox.

2-165
2 Using Symbolic Math Toolbox Software

2-166
Reduce Differential Order of DAE Systems

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.

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];

vars = [x(t); y(t); T(t)];

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

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

Reduce Differential Index to 1


Once you have a first-order DAE system, use the isLowIndexDAE function to check the
differential index of the system. If the index is 0 or 1, then isLowIndexDAE returns
1 (logical true). In this case, skip the index reduction and go to the next step. If the
differential index is 2 or higher, then isLowIndexDAE returns 0 (logical false). For this
system of differential algebraic equations, isLowIndexDAE returns 0 (logical false).

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)

Often, reduceDAEIndex introduces equations and variables that can be easily


eliminated. You can simplify the system by eliminating redundant equations.
[DAEs,DAEvars] = reduceRedundancies(DAEs,DAEvars)

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.

Reduce Differential Index to 0


Once you have a first-order DAE system, use the isLowIndexDAE function to check the
differential index of the system. If the index is 0 or 1, then isLowIndexDAE returns
1 (logical true). In this case, skip the index reduction and go to the next step. If the
differential index is 2 or higher, then isLowIndexDAE returns 0 (logical false). For this
system of differential algebraic equations, isLowIndexDAE returns 0 (logical false).

isLowIndexDAE(eqs,vars)

ans =
logical
0

The Pantelides algorithm used by reduceDAEIndex can underestimate the differential


index of a system. After index reduction, the reduceDAEIndex function internally calls
isLowIndexDAE to check the differential index of the new DAE system. If the reduced
index is still 2 or higher, it issues the following warning:

Warning: The index of the reduced DAEs is larger...


than 1. [daetools::reduceDAEIndex]

Another index reduction function, reduceDAEToODE, reduces a DAE system to a system


of implicit ordinary differential equations by using a structural algorithm based on
Gaussian elimination of the mass matrix. This function only works on semilinear DAE
systems, and it is typically slower than reduceDAEIndex. The main advantage of using
reduceDAEToODE is that it reliably reduces semilinear DAE systems to ODE systems
(DAEs of index 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

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

DAEs to Function Handles for ode15i


To use ode15i, you need a function handle that describes a DAE system as F(t, y(t),
y'(t)) = 0. Thus, you must convert a DAE system to a function handle F = F(y, y,
yp), where t is a scalar, and y and yp are column vectors.

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);

Although daeFunction lets you create a function handle containing symbolic


parameters without numeric values assigned to them, you cannot use these function
handles as input arguments for the ode15i solver. Before calling 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 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

ODEs to Function Handles for ode15i


To use ode15i, you need a function handle that describes an ODE system as F(t,
y(t), y'(t)) = 0. Thus, you must convert an ODE system to a function handle F =
F(y, y, yp), where t is a scalar, and y and yp are column vectors.

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)

Use daeFunction to create a function handle suitable for ode15i.


F = daeFunction(ODEs, vars);

For the next step in solving your DAE problem, see Find Consistent Initial Conditions
on page 2-180.

DAEs to Function Handles for ode15s and ode23t


To use ode15s or ode23t, you need two function handles: one must represent the mass
matrix of a DAE system, and the other must represent the vector containing the right
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 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

r^2 - y(t)^2 - x(t)^2


- 2*Dxt(t)*x(t) - 2*Dyt(t)*y(t)
- 2*Dxtt(t)*x(t) - 2*Dytt(t)*y(t) - 2*Dxt(t)^2 - 2*Dyt(t)^2
-Dytt(t)
-Dyt(t)

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);

If M or F contain symbolic parameters (symbolic variables other than those specified


in the vector of state variables DAEvars), then specify these symbolic parameters as
additional input arguments of odeFunction. Because F contains the variables m, r, and
g, provide these variables as additional arguments when you call odeFunction for F.
F = odeFunction(F, DAEvars, m, r, g);

Although odeFunction lets you create a function handle 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 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.

ODEs to Function Handles for ode15s and ode23t


To use ode15s or ode23t, you need two function handles: one must represent the mass
matrix of a ODE system, and the other must represent the vector containing the right

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.

If M or F contain symbolic parameters (symbolic variables other than specified in the


vector of state variables DAEvars), then specify these symbolic parameters as additional
input arguments of odeFunction. In this example, both M and F contain the variables m,
r, and g. Call odeFunction and provide these variables as additional arguments.

M = odeFunction(M, vars, m, r, g);


F = odeFunction(F, vars, m, r, g);

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.

M = @(t, Y) M(t, Y, m, r, g);


F = @(t, Y) F(t, Y, m, r, g);

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

Find Consistent Initial Conditions

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

DAEs: Initial Conditions for ode15i


The vector of variables for the first-order DAE system of differential index 1 describing a
two-dimensional pendulum is a 7-by-1 vector. Therefore, estimates for initial values of
variables and their derivatives must also be 7-by-1 vectors.

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

ODEs: Initial Conditions for ode15i


The vector of variables for the first-order ODE system describing a two-dimensional
pendulum is a 5-by-1 vector, therefore, estimates for initial values of variables and
their derivatives must also be 5-by-1 vectors.
vars

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.

DAEs: Initial Conditions for ode15s and ode23t


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 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.

opt = odeset('Mass', M, 'InitialSlope', yp0est,...


'RelTol', 10.0^(-7), 'AbsTol' , 10.0^(-7));

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.

ODEs: Initial Conditions for ode15s and ode23t


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);

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

Solve DAE Systems Using MATLAB ODE Solvers

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

Solve a DAE System with ode15i


Solve the system integrating over the time span 0 t 0.5. Add the grid lines and the
legend to the plot.
ode15i(F, [0, 0.5], y0, yp0, opt)

for k = 1:numel(DAEvars)
S{k} = char(DAEvars(k));

2-186
Solve DAE Systems Using MATLAB ODE Solvers

end

legend(S, 'Location', 'Best')


grid on

Solve an ODE System with ode15i


Solve the system integrating over the time span 0 t 0.5. Add the grid lines and the
legend to the plot.

ode15i(F, [0, 0.5], y0, yp0, opt)

for k = 1:numel(vars)

2-187
2 Using Symbolic Math Toolbox Software

S{k} = char(vars(k));
end

legend(S, 'Location', 'Best')


grid on

Solve a DAE System with ode15s


Solve the system integrating over the time span 0 t 0.5. Add the grid lines and the
legend to the plot.

ode15s(F, [0, 0.5], y0, opt)

2-188
Solve DAE Systems Using MATLAB ODE Solvers

for k = 1:numel(DAEvars)
S{k} = char(DAEvars(k));
end

legend(S, 'Location', 'Best')


grid on

Solve an ODE System with ode15s


Solve the system integrating over the time span 0 t 0.5. Add the grid lines and the
legend to the plot.

ode15s(F, [0, 0.5], y0, opt)

2-189
2 Using Symbolic Math Toolbox Software

for k = 1:numel(vars)
S{k} = char(vars(k));
end

legend(S, 'Location', 'Best')


grid on

2-190
Fourier Transforms and Inverse

Fourier Transforms and Inverse


The Fourier transform of a function f(x) is defined as


F [ f ] (w) = f ( x) e-iwx dx,
-

and the inverse Fourier transform (IFT) as


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

The shock could be induced by a pneumatic hammer blow.

The differential equation idealizing this physical setting is

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).
-

A definition of the Dirac Delta function is

d ( x) = lim n c( -1 / 2n,1 / 2n ) ( x),


n

where

2-193
2 Using Symbolic Math Toolbox Software

1 1
1 for - <x<
c( -1 / 2n, 1/ 2n ) ( x) = 2n 2n
0 otherwise.

Let Y(w) = F[y(x)](w) and (w)=F[(x)](w). Indeed, try the command


fourier(dirac(x), x, w). The Fourier transform turns differentiation into
exponentiation, and, in particular,

d4 y 4
F (w) = w Y ( w).
dx4

See a demonstration of this property:

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

This is done to ease the computation of F 1[G(w)](x). Now type

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)

Since Y is the product of Fourier transforms, y is the convolution of the transformed


functions. That is, F[y] = Y(w) = (w) G(w) = F[] F[g] implies


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

Laplace Transform and Inverse


The Laplace transform of a function f(t) is defined as


L [ f ] (s ) = f (t)e
- ts
dt,
0

while the inverse Laplace transform (ILT) of f(s) is

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

Let Rj and Ij, j = 1, 2, 3 be resistances (measured in ohms) and currents (amperes),


respectively; L be inductance (henrys), and C be capacitance (farads); E(t) be the
electromotive force, and Q(t) be the charge.

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

dI1(t) = diff(I1(t), t);


dQ(t) = diff(Q(t),t);
E(t) = sin(t); % Voltage
eq1(t) = dI1(t) + R2*dQ(t)/L - (R2 - R1)*I1(t)/L;
eq2(t) = dQ(t) - (E(t) - Q/C)/(R2 + R3) - R2*I1(t)/(R2 + R3);

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))

Now you need to solve the system of equations L1 = 0, L2 = 0 for


laplace(I1(t),t,s) and laplace(Q(t),t,s), the Laplace transforms of I1 and
Q, respectively. To do this, make a series of substitutions. For the purposes of this
example, use the quantities R1 = 4(ohms), R2 = 2, R3=3, C = 1/4farads, L =
1.6H(henrys), I1(0) = 15A(amperes), and Q(0) = 2A*sec. Substituting these values in
L1
syms LI1 LQ
NI1 = subs(L1(t),{R1,R2,R3,L,C,I1(0),Q(0)}, ...
{4,2,3,1.6,1/4,15,2})

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 solve for laplace(I1(t),t,s) and laplace(Q(t),t,s), make a final pair of


substitutions. First, replace laplace(I1(t),t,s) and laplace(Q(t),t,s) by the
sym objects LI1 and LQ, using
NI1 = subs(NI1,{laplace(I1(t),t,s),laplace(Q(t),t,s)},{LI1,LQ})

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

which, after collecting terms,


NQ = collect(NQ,LQ)

gives
NQ(t) =
(s + 4/5)*LQ - (2*LI1)/5 - 1/(5*(s^2 + 1)) - 2

Now, solving for LI1 and LQ


[LI1, LQ] = solve(NI1, NQ, LI1, LQ)

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-Transform and Inverse


The (one-sided) z-transform of a function f(n) is defined as


Z [ f ]( z ) = f (n)z -n .
n =0

The notation Z[f] refers to the z-transform of f at z. Let R be a positive number so


that the function g(z) is analytic on and outside the circle |z| = R. Then the inverse z-
transform (IZT) of g at n is defined as

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

p(n+2) = p(n+1) + p(n), p(0) = 1, p(1) = 2.

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

Now solve for Pz


P = solve(eq, Pz)

to obtain
P =
-(z^2 + z)/(- z^2 + z + 1)

To recover p(n), take the inverse z-transform of P.


p = iztrans(P, z, n);
p = simplify(p)

The result is a bit complicated, but explicit:


p =
4*(-1)^(n/2)*cos(n*(pi/2 + asinh(1/2)*1i)) +...
1/2^n*((3*5^(1/2))/10 - 3/2)*(5^(1/2) + 1)^n -...
1/2^n*((3*5^(1/2))/10 + 3/2)*(1 - 5^(1/2))^n

Finally, plot p to show the growth in rabbit population over time.


m = 1:10;
y = double(subs(p,n,m));
plot(m, real(y),'rO')

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] Crandall, R.E., Projects in Scientific Computation, Springer-Verlag Publishers, New


York, 1994

2-206
Z-Transform and Inverse

[3] Strang, G., Introduction to Applied Mathematics, Wellesley-Cambridge Press,


Wellesley, MA, 1986

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 with Symbolic Plotting Functions


MATLAB provides many techniques for plotting numerical data. Graphical capabilities
of MATLAB include plotting tools, standard plotting functions, graphic manipulation and
data exploration tools, and tools for printing and exporting graphics to standard formats.
Symbolic Math Toolbox expands these graphical capabilities and lets you plot symbolic
functions using:

fplot to create 2-D plots of symbolic expressions, equations, or functions in


Cartesian coordinates.
fplot3 to create 3-D parametric plots.
ezpolar to create plots in polar coordinates.
fsurf to create surface plots.
fcontour to create contour plots.
fmesh to create mesh plots.

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 .

Plot the symbolic expression in polar coordinates.

syms t
ezpolar(sin(6*t))

2-209
2 Using Symbolic Math Toolbox Software

Plot Functions Numerically


As an alternative to plotting expressions symbolically, you can substitute symbolic
variables with numeric values by using subs. Then, you can use these numeric values
with plotting functions in MATLAB.

In the following expressions u and v, substitute the symbolic variables x and y with the
numeric values defined by meshgrid.
syms x y
u = sin(x^2 + y^2);
v = cos(x*y);
[X, Y] = meshgrid(-1:.1:1,-1:.1:1);

2-210
Create Plots

U = subs(u, [x y], {X,Y});


V = subs(v, [x y], {X,Y});

Now, you can plot U and V by using standard MATLAB plotting functions.

Create a plot of the vector field defined by the functions U(X,Y) and V(X,Y) by using
the MATLAB quiver function.
quiver(X, Y, U, V)

Plot Multiple Symbolic Functions in One Graph


Plot several functions on one graph by adding the functions sequentially. After plotting
the first function, add successive functions by using the hold on command. The hold

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.

Plot using fplot. Show the bounds of by superimposing plots of and


as dashed red lines. Set the title by using the DisplayName property of the object
returned by fplot.

syms x y
f = exp(x)*sin(20*x)
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

Plot Multiple Symbolic Functions in One Figure


Display several functions side-by-side in one figure by dividing the figure window into
several subplots using subplot. The command subplot(m,n,p) divides the figure into
a m by n matrix of subplots and selects the subplot p. Display multiple plots in separate
subplots by selecting the subplot and using plotting commands. Plotting into multiple
subplots is useful for side-by-side comparisons of plots.

Compare plots of for by using subplot to create


side-by-side subplots.

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

Combine Symbolic Function Plots and Numeric Data Plots


Plot numeric and symbolic data on the same graph by using MATLAB and Symbolic
Math Toolbox functions together.

For numeric values of between , return a noisy sine curve by finding


and adding random values to . View the noisy sine curve by using scatter to plot the
points .

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

Combine Numeric and Symbolic Plots in 3-D


Combine symbolic and numeric plots in 3-D by using MATLAB and Symbolic Math
Toolbox plotting functions. Symbolic Math Toolbox provides these 3-D plotting functions:

fplot3 creates 3-D parameterized line plots.


fsurf creates 3-D surface plots.
fmesh creates 3-D mesh plots.

Create a spiral plot by using fplot3 to plot the parametric line

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

Generate C or Fortran Code from Symbolic Expressions


You can generate C or Fortran code fragments from a symbolic expression, or generate
files containing code fragments, using the ccode and fortran functions. These code
fragments calculate numerical values as if substituting numbers for variables in the
symbolic expression.

To generate code from a symbolic expression g, enter either ccode(g) or fortran(g).

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);

To generate a file containing code, either enter ccode(g,'file','filename') or


fortran(g,'file','filename'). For the example above,
fortran(z, 'file', 'fortrantest')

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

Similarly, the command


ccode(z,'file','ccodetest')

generates a file named ccodetest that consists of the lines


t16 = x*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

Generate MATLAB Functions from Symbolic Expressions


You can use matlabFunction to generate a MATLAB function handle that calculates
numerical values as if you were substituting numbers for variables in a symbolic
expression. Also, matlabFunction can create a file that accepts numeric arguments
and evaluates the symbolic expression applied to the arguments. The generated file is
available for use in any MATLAB calculation, whether or not the computer running the
file has a license for Symbolic Math Toolbox functions.

If you work in the MuPAD Notebook app, see Create MATLAB Functions from MuPAD
Expressions on page 3-70.

Generating a Function Handle


matlabFunction can generate a function handle from any symbolic expression. For
example:

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))

You can use this function handle to calculate numerically:

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

Tip Some symbolic expressions cannot be represented using MATLAB functions.


matlabFunction cannot convert these symbolic expressions, but issues a warning.
Since these expressions might result in undefined function calls, always check conversion
results and verify the results by executing the resulting function.

Control the Order of Variables


matlabFunction generates input variables in alphabetical order from a symbolic
expression. That is why the function handle in Generating a Function Handle on page
2-222 has x before y:

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 = matlabFunction(tanh(r), 'vars', {'x', 'y', 'z'})

ht2 =
function_handle with value:
@(x,y,z)tanh(sqrt(x.^2+y.^2.*3.0+z.^2.*5.0))

ht3 = matlabFunction(tanh(r), 'vars', {'x', [y z]})

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')

The file testMatrix.m contains the following code:

function F = testMatrix(t,x,y)
%TESTMATRIX
% F = TESTMATRIX(T,X,Y)

t2 = x.^2;
t3 = tan(y);
t4 = t2.*x;
t5 = t.^2;
t6 = t5 + 1;
t7 = 1./y;
t8 = t6.*t7.*x;
t9 = t3 + t4;
t10 = 1./t9;
F = [-(t10.*(t3 - t4))./t6,t8; t8,- t10.*(3.*t3 - 3.*t2.*x) - 1];

matlabFunction generates many intermediate variables. This is called optimized


code. MATLAB generates intermediate variables as a lowercase letter t followed by an
automatically generated number, for example t32. Intermediate variables can make the
resulting code more efficient by reusing intermediate expressions (such as t4, t6, t8, t9,
and t10 in the calculation of F). Using intermediate variables can make the code easier
to read by keeping expressions short.

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

...

Name Output Variables


By default, the names of the output variables coincide with the names you use calling
matlabFunction. For example, if you call matlabFunction with the variable F

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])

the generated name of an output variable is also F:

function F = testMatrix(x,y,t)
...

If you call matlabFunction using an expression instead of individual variables

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'})

The generated function returns name1 and name2 as results:

function [name1,name2] = new_function(x,y,z)


...

2-225
2 Using Symbolic Math Toolbox Software

Generate MATLAB Function Blocks from Symbolic Expressions


Using matlabFunctionBlock, you can generate a MATLAB Function block. The
generated block is available for use in Simulink models, whether or not the computer
running the simulations has a license for Symbolic Math Toolbox.

If you work in the MuPAD Notebook app, see Create MATLAB Function Blocks from
MuPAD Expressions on page 3-74.

Generate and Edit a Block


Suppose, you want to create a model involving the symbolic expression r = sqrt(x^2 +
y^2). Before you can convert a symbolic expression to a MATLAB Function block, create
an empty model or open an existing one:

new_system('my_system')
open_system('my_system')

Create a symbolic expression and pass it to the matlabFunctionBlock command. Also


specify the block name:

syms x y
r = sqrt(x^2 + y^2);
matlabFunctionBlock('my_system/my_block', r)

If you use the name of an existing block, the matlabFunctionBlock command replaces
the definition of an existing block with the converted symbolic expression.

You can open and edit the generated block. To open a block, double-click it.

function r = my_block(x,y)
%#codegen

r = sqrt(x.^2+y.^2);

Tip Some symbolic expressions cannot be represented using MATLAB functions.


matlabFunctionBlock cannot convert these symbolic expressions, but issues a
warning. Since these expressions might result in undefined function calls, always check
conversion results and verify results by running the simulation containing the resulting
block.

2-226
Generate MATLAB Function Blocks from Symbolic Expressions

Control the Order of Input Ports


matlabFunctionBlock generates input variables and the corresponding input ports in
alphabetical order from a symbolic expression. To change the order of input variables,
use the vars option:

syms x y
mu = sym('mu');
dydt = -x - mu*y*(x^2 - 1);
matlabFunctionBlock('my_system/vdp', dydt,'vars', [y mu x])

Name the Output Ports


By default, matlabFunctionBlock generates the names of the output ports as the word
out followed by the output port number, for example, out3. The output option allows
you to use the custom names of the output ports:
syms x y
mu = sym('mu');
dydt = -x - mu*y*(x^2 - 1);
matlabFunctionBlock('my_system/vdp', dydt,'outputs',{'name1'})

2-227
2 Using Symbolic Math Toolbox Software

Generate Simscape Equations from Symbolic Expressions


Simscape software extends the Simulink product line with tools for modeling and
simulating multidomain physical systems, such as those with mechanical, hydraulic,
pneumatic, thermal, and electrical components. Unlike other Simulink blocks, which
represent mathematical operations or operate on signals, Simscape blocks represent
physical components or relationships directly. With Simscape blocks, you build a model
of a system just as you would assemble a physical system. For more information about
Simscape software see Simscape.

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.

Convert Algebraic and Differential Equations


Suppose, you want to generate a Simscape equation from the solution of the following
ordinary differential equation. As a first step, use the dsolve function to solve the
equation:

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)

The solution is:

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

simscapeEquation generates the following code:

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.

simscapeEquation converts any derivative with respect to the variable t to the


Simscape notation, X.der, where X is the time-dependent variable. For example,
convert the following differential equation to a Simscape equation. Also, here you
explicitly specify the left and the right sides of the equation by using the syntax
simscapeEquation(LHS, RHS):

syms a x(t)
simscapeEquation(diff(x), -a^2*x)

ans =
116 char array
x.der == -a^2*x;

simscapeEquation also translates piecewise expressions to the Simscape language. For


example, the result of the following Fourier transform is a piecewise function:

syms v u x
assume(x, 'real')
f = exp(-x^2*abs(v))*sin(v)/v;
s = fourier(f, v, u)

s =
piecewise(x ~= 0, atan((u + 1)/x^2) - atan((u - 1)/x^2))

From this symbolic piecewise equation, simscapeEquation generates valid code for the
equation section of a Simscape component file:

simscapeEquation(s)

ans =
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

Clear the assumption that x is real:


syms x clear

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:

Expressions with infinities


Expressions returned by evalin and feval

2-230
3

MuPAD in Symbolic Math Toolbox

MuPAD Engines and MATLAB Workspace on page 3-2


Create MuPAD Notebooks on page 3-3
Open MuPAD Notebooks on page 3-6
Save MuPAD Notebooks on page 3-12
Evaluate MuPAD Notebooks from MATLAB on page 3-13
Close MuPAD Notebooks from MATLAB on page 3-17
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
Edit MuPAD Code in MATLAB Editor on page 3-42
Notebook Files and Program Files on page 3-45
Source Code of the MuPAD Library Functions on page 3-47
Differences Between MATLAB and MuPAD Syntax on page 3-48
Copy Variables and Expressions Between MATLAB and MuPAD on page 3-51
Reserved Variable and Function Names on page 3-55
Call Built-In MuPAD Functions from MATLAB on page 3-57
Use Your Own MuPAD Procedures on page 3-61
Clear Assumptions and Reset the Symbolic Engine on page 3-66
Create MATLAB Functions from MuPAD Expressions on page 3-70
Create MATLAB Function Blocks from MuPAD Expressions on page 3-74
Create Simscape Equations from MuPAD Expressions on page 3-76
3 MuPAD in Symbolic Math Toolbox

MuPAD Engines and MATLAB Workspace

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 MuPAD engine is a separate process that runs on your computer in addition to a


MATLAB process. A MuPAD engine starts when you first call a function that needs a
symbolic engine, such as syms. Symbolic Math Toolbox functions that use the symbolic
engine use standard MATLAB syntax, such as y = int(x^2).

Conceptually, each MuPAD notebook has its own symbolic engine, with an associated
workspace. You can have any number of MuPAD notebooks open simultaneously.

One engine exists for use by Each MuPAD notebook also


Symbolic Math Toolbox. has its own engine.

MATLAB workspace MuPAD notebook 1 MuPAD notebook 2

MuPAD engine MuPAD engine MuPAD engine


Engine 1 Engine 2 Engine 3

Engine Engine Engine


Workspace Workspace Workspace

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

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.

If You Need Communication Between Interfaces


If you perform computations in both interfaces, use handles to notebooks. The toolbox
uses this handle for communication between the MATLAB workspace and the MuPAD
notebook.

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.

If You Use MATLAB to Access MuPAD


Use the Apps Tab

To create a new blank notebook:

1 On the MATLAB Toolstrip, click the Apps tab.


2 On the Apps tab, click the down arrow at the end of the Apps section.
3 Under Math, Statistics and Optimization, click the MuPAD Notebook button.

To create several MuPAD notebooks, click the MuPAD Notebook button repeatedly.

Use the mupad Command

To create a new blank notebook, type mupad in the MATLAB Command Window.

Use the Welcome to MuPAD Dialog Box

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

Create New Notebooks from MuPAD

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

Open 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 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.

If You Need Communication Between Interfaces


The following commands are also useful if you lose the handle to a notebook, in which
case, you can save the notebook file and then reopen it with a new handle.

Use the mupad or openmn Command


Open an existing MuPAD notebook file and create a handle to it by using mupad or
openmn in the MATLAB Command Window:
nb = mupad('file_name')

nb1 = openmn('file_name')

Here, file_name must be a full path, such as H:\Documents\Notes\myNotebook.mn,


unless the notebook is in the current folder.

To open a notebook and automatically jump to a particular location, create a link


target at that location inside a notebook, and refer to it when opening a notebook. For
information about creating link targets, see Work with Links. To refer to a link target
when opening a notebook, enter:
nb = mupad('file_name#linktarget_name')

nb = openmn('file_name#linktarget_name')

Use the open Command


Open an existing MuPAD notebook file and create a handle to it by using the open
function in the MATLAB Command Window:
nb1 = open('file_name')

Here, file_name must be a full path, such as H:\Documents\Notes\myNotebook.mn,


unless the notebook is in the current folder.

If You Use MATLAB to Access MuPAD


Double-Click the File Name
You can open an existing MuPAD notebook, program file, or graphic file (.xvc or .xvz)
by double-clicking the file name. The system opens the file in the appropriate interface.

3-7
3 MuPAD in Symbolic Math Toolbox

Use the mupad or openmn Command

Open an existing MuPAD notebook file by using the mupad or openmn function in the
MATLAB Command Window:

mupad('file_name')

openmn('file_name')

Here, file_name must be a full path, such as H:\Documents\Notes\myNotebook.mn,


unless the notebook is in the current folder.

To open a notebook and automatically jump to a particular location, create a link


target at that location inside a notebook, and refer to it when opening a notebook. For
information about creating link targets, see Work with Links. To refer to a link target
when opening a notebook, enter:

mupad('file_name#linktarget_name')

openmn('file_name#linktarget_name')

Use the open Command

Open an existing MuPAD notebook file by using open in the MATLAB Command
Window:

open('file_name')

Here, file_name must be a full path, such as H:\Documents\Notes\myNotebook.mn,


unless the notebook is in the current folder.

Use the Welcome to MuPAD Dialog Box

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

Open Notebooks in MuPAD

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.

Open MuPAD Program Files and Graphics


Besides notebooks, MuPAD lets you create and use program files (.mu) and graphic files
(.xvc or .xvz). Also, you can use the MuPAD Debugger to diagnose problems in your
MuPAD code.

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.

Double-Click the File Name

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

Use the openmn Command

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.

Use the open Command

Open an existing MuPAD file by using open in the MATLAB Command Window:

open('file_name')

Here, file_name must be a full path, such as H:\Documents\Notes


\myProcedure.mu, unless the notebook is in the current folder.

Use the Welcome to MuPAD Dialog Box

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

Open Program Files and Graphics from MuPAD

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

Save 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.

To save changes in a notebook:

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

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');

Suppose that myFile1.mn performs these computations.

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

If any calculation in a notebook throws an error, then evaluateMuPADNotebook stops.


The error messages appear in the MATLAB Command Window and in the MuPAD
notebook. When you evaluate several notebooks and one of them throws an error,
evaluateMuPADNotebook does not proceed to the next notebook. It stops and displays
an error message immediately. If you want to skip calculations that cause errors and
evaluate all input regions that run without errors, use 'IgnoreErrors',true:

evaluateMuPADNotebook(allMuPADNotebooks,'IgnoreErrors',true)

3-16
Close MuPAD Notebooks from MATLAB

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;

Now, close the notebook:

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

Use allMuPADNotebooks to get a vector of handles to these notebooks:

nbhandles = allMuPADNotebooks

nbhandles =
Notebook1
Notebook2
Notebook3

Close the first notebook (Notebook1):

close(nbhandles(1))

Close all notebooks:

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')

Evaluate all notebooks:


evaluateMuPADNotebook(allMuPADNotebooks)

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

Convert MuPAD Notebooks to MATLAB Live Scripts


Migrate MuPAD notebooks to MATLAB live scripts that use MATLAB code. Live scripts
are an interactive way to run MATLAB code. For details, see What Is a Live Script?
MuPAD notebooks are converted to live scripts by using Symbolic Math Toolbox. For
more information, see Getting Started with Symbolic Math Toolbox.

Convert a MuPAD Notebook .mn to a MATLAB Live Script .mlx


1 Prepare the notebook: This step is optional, but helps avoid conversion errors
and warnings. Check if your notebook contains untranslatable objects from MuPAD
Objects That Are Not Converted on page 3-20. These objects cause translation
errors or warnings.
2 Convert the notebook: Use convertMuPADNotebook. For example, convert
myNotebook.mn in the current folder to myScript.mlx in the same folder.

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.

Created ''myScript.mlx': 4 translation errors, 1 warnings. For verifying...


the document, see help.

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.

MuPAD Objects That Are Not Converted on page 3-20


No Automatic Substitution in MATLAB on page 3-21
last(1) in MuPAD Is Not ans in MATLAB on page 3-21
Some solve Results Are Wrongly Accessed on page 3-22
break Inside case Is Wrongly Translated on page 3-22
Some MuPAD Graphics Options Are Not Translated on page 3-23
Some Operations on Matrices Are Wrongly Translated on page 3-23
indets Behavior in MATLAB Differs on page 3-24
Return Type of factor Differs in MATLAB on page 3-24
Layout Issues on page 3-24
Syntax Differences Between MATLAB and MuPAD on page 3-24

MuPAD Objects That Are Not Converted

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.

Objects Not Converted

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

Reading code from files. Replace commands such as read("filename.mu") by the


content of filename.mu.
Function calls with expression sequences as input arguments.
Function calls where the function is generated by the preceding code instead of being
specified explicitly.
Substitutions, such as subs(f,[x1 = a1,x2 = a2,...]), where a vector of
equations [x1 = a1,x2 = a2,...] is not specified explicitly, but generated by the
preceding code.
Domains, and commands that create domains and their elements.
Assignments to slots of domains and function environments.
Commands using the history mechanism, such as last(2) or HISTORY := 30.
MuPAD environment variables, such as ORDER, HISTORY, and LEVEL.

No Automatic Substitution in MATLAB

In MATLAB, when symbolic variables are assigned values, then expressions containing
those values are not automatically updated.

Fixing This Issue

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

last(1) in MuPAD Is Not ans in MATLAB

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

Fixing This Issue

Instead of using ans, assign the result to a variable and use that variable.

Some solve Results Are Wrongly Accessed

When results of MuPAD solve are accessed, convertMuPADNotebook assumes that


the result is a finite set. However, if the result is a non-finite set then the code is wrongly
translated.

Fixing This Issue

There is no general solution. Further, non-finite solution sets are not translatable.

If you are accessing parameters or conditions, use the parameters or conditions


output arguments of MATLAB solve.

syms x
S = solve(sin(x) == 1, x, 'ReturnConditions', true);
S.x % solution
S.parameters % parameters in solution
S.conditions % conditions on solution

ans =
pi/2 + 2*pi*k
ans =
k
ans =
in(k, 'integer')

break Inside case Is Wrongly Translated

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.

Fixing This Issue

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

Some MuPAD Graphics Options Are Not Translated

While the most commonly used MuPAD graphics options are translated, there are some
options that are not translated.

Fixing This Issue

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];

Some Operations on Matrices Are Wrongly Translated

Operations on matrices are not always translated correctly. For example, if M is a


matrix, then exp(M) in MuPAD is wrongly translated to exp(M) instead of the matrix
exponential expm(M).

Fixing This Issue

When performing operations on matrices, search for the matrix operation and use it
instead. For example, in MATLAB:

Use expm instead of exp.


Use funm(M,'sin') instead of sin(M).

3-23
3 MuPAD in Symbolic Math Toolbox

A == [1 2; 3 4] displays differently from A = matrix([[1, 2], [3, 4]]) in


MuPAD but is programmatically equivalent.

indets Behavior in MATLAB Differs

indets is translated to MATLAB symvar. However, symvar does not find bound
variables or constant identifiers like PI.

Return Type of factor Differs in MATLAB

The return type of MuPAD factor has no equivalent in MATLAB. Subsequent


operations on the results of factor in MATLAB might return incorrect results.

Fixing This Issue

Check and modify the output of factor in MATLAB as required such that subsequent
commands run correctly.

Layout Issues

MuPAD notebook frames are not converted.


MuPAD notebook tables are not converted.
MuPAD plots are not interactive in live scripts.
Titles or headings in MuPAD notebooks are not always detected.
MuPAD text attribute underline is not converted
Text formatting: Font, font size, and color are not converted. All text in live scripts
looks the same.

Syntax Differences Between MATLAB and MuPAD

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

Troubleshoot MuPAD to MATLAB Translation Errors


This page helps troubleshoot all errors generated by the convertMuPADNotebook
function when converting MuPAD notebooks to MATLAB live scripts. For the conversion
steps, see Convert MuPAD Notebooks to MATLAB Live Scripts on page 3-19. To
troubleshoot warnings, see Troubleshoot MuPAD to MATLAB Translation Warnings on
page 3-34.

Error Message Details Recommendations


No equivalent code in convertMuPADNotebook Check the code for MuPAD-
MATLAB. cannot find the specific functionality. Adjust
corresponding functionality it so that it uses only the
in MATLAB. functionality that can be
expressed in the MATLAB
language.
Unable to translate The MATLAB airy Rewrite second and higher
the second and higher function represents Airy derivatives of Airy functions
derivatives of Airy functions of the first in terms of Airy functions
functions. Express these and second kind and and their first derivatives.
derivatives in terms of Airy their first derivatives. In Then convert the result to
functions and their first MuPAD, airyAi(z,n) MATLAB code.
derivatives. and airyBi(z,n) can
represent second and The MuPAD airyAi
higher derivatives of Airy and airyBi functions
functions, that is, n can be return results in terms of
greater than 1. Airy functions and their
first derivatives. You can
replace second and higher
derivatives by their outputs
in MuPAD, before converting
the code to MATLAB.
Unable to translate Environment variables are In some cases, you can use
assignment to MuPAD global variables, such as name-value pair arguments
environment variable. HISTORY, LEVEL, ORDER, in each function call, such as
and so on, that affect setting the value Order in
the behavior of MuPAD the taylor function call.
algorithms.
In other cases, there is no
appropriate replacement.

3-25
3 MuPAD in Symbolic Math Toolbox

Error Message Details Recommendations


Adjust the code so that it
does not require a global
setting.
Unable to translate MuPAD uses remember Adjust the code so that it
assignments to the tables to speed up does not use remember
remember table of a computations, especially tables.
procedure. when you use recursive
procedure calls. The system
stores the arguments of a
procedure call as indices of
theremembertableentries,
and the corresponding
results as values of these
entries.When you call a
procedure using the same
arguments as in previous
calls, MuPAD accesses
theremembertableof
that procedure. If
theremembertablecontains
the entry with the required
arguments, MuPAD returns
the value of that entry. For
details, see Remember
Mechanism.

The remember tables are


not available in MATLAB.

3-26
Troubleshoot MuPAD to MATLAB Translation Errors

Error Message Details Recommendations


Unable to translate In MuPAD, the slot Adjust the code so that it
assignments to slots of function defines methods does not use assignments to
domains and function and entries of data types slots of domains and function
environments. (domains) or for defining environments.
attributes of function
environments. These
methods and entries (slots)
let you overload system
functions by your own
domains and function
environments.

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

Error Message Details Recommendations


Unable to translate the Environment variables are Adjust the code so that it
MuPAD environment global variables, such as does not require accessing
variable ''{0}''. HISTORY, LEVEL, ORDER, MuPAD environment
and so on, that affect variables.
the behavior of MuPAD
algorithms.

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

Error Message Details Recommendations


Unable to translate infinite MuPAD recognizes Adjust the code so that it
sets. infinite sets. For example, does not use infinite sets as
solve can return a inputs.
solution as an infinite set:
solve(sin(x*PI/2) =
0, x) returns { 2k k } .
You can create such sets by
using Dom::ImageSet.

MATLAB does not support


infinite sets.
Unable to translate a The MuPAD last function Adjust the code so that it
call accessing previously and its shortcut % typically uses assignments instead of
computed results. The let you access the last 20 relying on last or %.
MATLAB ans function lets commands stored in an
you access only the most internal history table.
recent result.
In MATLAB, ans lets you
access only one most recent
command.
Unable to translate the Libraries contain most of Adjust the code so that it
variable "{0}" representing a the MuPAD functionality. does not use MuPAD library
MuPAD library. Each library includes a names as identifiers.
collection of functions for
solving particular types of
mathematical problems.
While MuPAD library
functions are translated to
MATLAB code, the libraries
themselves are not.

3-29
3 MuPAD in Symbolic Math Toolbox

Error Message Details Recommendations


Unable to translate this MuPAD provides a few Adjust the code so that it
form of matrix definition. different approaches for defines matrices by using an
creating a matrix. You can array, list of elements, or a
create a matrix from an nested list of rows.
array, list of elements, a
nested list of rows, or a
table. Also, you can create
a matrix by specifying only
the nonzero entries, such
as A[i1,j1] = value1,
A[i2,j2] = value2, and
so on.

Some of these approaches


cannot be translated to
MATLAB code.
Unable to translate For code that you want Adjust the code so that it
nontrivial procedures. to execute repeatedly, does not use complicated
MuPAD lets you create procedures.
procedures by using the
proc command.

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

Error Message Details Recommendations


Unable to translate the convertMuPADNotebook Set properties and
global table of properties. cannot translate the assumptions as described
MuPAD global table of in Properties and
properties, PROPERTIES, Assumptions.
because this functionality is
not available in MATLAB.
Unable to create random MuPAD lets you set a Adjust the code so that it
generators with individual separate seed value for each does not rely on individual
seed values. random number generator. seed values for different
MATLAB has one seed random number generators.
value for all random
number generators. See rng
for details.

3-31
3 MuPAD in Symbolic Math Toolbox

Error Message Details Recommendations


Unable to translate target The MuPAD rewrite Adjust the code so that
''{0}'' for MATLAB function function can rewrite an it uses the target options
''rewrite''. expression in terms of available in MATLAB. If
the following targets: needed, use a sequence of
andor, arccos, arccosh, function calls to rewrite
arccot, arccoth, with different target options.
arcsin, arcsinh,
arctan, arctanh, arg,
bernoulli, cos, cosh,
cot, coth, diff, D,
erf, erfc, erfi, exp,
fact, gamma, harmonic,
heaviside, inverf,
inverfc, lambertW, ln,
max, min, piecewise, psi,
sign, sin, sincos, sinh,
sinhcosh, tan, tanh.

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

Error Message Details Recommendations


Unknown domain or library Most likely, a custom Check and correct the
"{0}". domain or library is used MuPAD code that you are
and cannot be translated. translating.
Unknown MuPAD function The function is not available Check and correct the
"{0}". in MuPAD. MuPAD code that you are
translating.
Unable to translate calls to The function is a valid Check and correct the
the function ''{0}''. MuPAD function, but the MuPAD code that you are
function call is invalid. For translating.
example, the number of
input arguments or types of
arguments can be incorrect.
Unable to translate calls to The functions of this Adjust the code so that it
functions of the library ''{0}''. library are available in does not use the functions of
MuPAD, but there are no this library.
corresponding functions in
MATLAB.
MuPAD function ''{0}'' The MuPAD function does Adjust the code to use
cannot be converted to not have an equivalent a function that has an
function handle. function handle in equivalent in MATLAB.
MATLAB.
Unable to translate option Most likely, this option is Adjust the code so that it
''{0}''. available in MuPAD, but does not use this option.
there are no corresponding
options in MATLAB.
Unable to translate MuPAD Most likely, the function call Check and correct the
code because it uses invalid in the MuPAD code has an MuPAD code that you are
calling syntax. error. translating.

3-33
3 MuPAD in Symbolic Math Toolbox

Troubleshoot MuPAD to MATLAB Translation Warnings


This page helps troubleshoot all warnings generated by the convertMuPADNotebook
function when converting MuPAD notebooks to MATLAB live scripts. For the conversion
steps, see Convert MuPAD Notebooks to MATLAB Live Scripts on page 3-19. To
troubleshoot errors, see Troubleshoot MuPAD to MATLAB Translation Errors on page
3-25.

Warning Message Meaning Recommendations


Translating the alias The MuPAD alias and Verify the resulting code. If
function as an assignment, unalias function let you do not want a MuPAD
and the unalias function as you create and delete an alias to be converted to an
deletion of an assignment. alias (abbreviation) for assignment in MATLAB,
any MuPAD object. For adjust the code so that it
example, you can create does not use aliases.
an alias d for the diff
function: alias(d =
diff).

Creating aliases is not


available in MATLAB.
When translating
a notebook file,
convertMuPADNotebook
replaces aliases with
assignments.
Replacing animation by its MuPAD animations cannot Verify the resulting code.
last frame. be correctly reproduced The last frame might not be
in MATLAB. When ideal for some animations.
translating a notebook file, If you want the static image
convertMuPADNotebook to show any other frame
replaces an animation with of the animation, rewrite
a static image showing the the MuPAD code so that it
last frame of the animation. creates a static plot showing
that image.
Omitting arrowhead. Arrowheads are not Verify the resulting code.
available in MATLAB. Check if the ignored
arrowheads are essential
for visualizing results. If

3-34
Troubleshoot MuPAD to MATLAB Translation Warnings

Warning Message Meaning Recommendations


they are, you might want to
use annotations or quiver
plots instead. If they are not
essential, simply delete this
warning.
Potentially incorrect When translating Verify the corrected code.
MuPAD code ''{0}''. a notebook file, Then delete this warning.
Replacing it by ''{1}''. convertMuPADNotebook
detected that the part of
the code in the MuPAD
notebook might be incorrect.
For example, the code
appears to have a typo, or a
commonly used argument is
missing.

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

Warning Message Meaning Recommendations


Replacing MuPAD domain Domains represent data Verify the resulting code.
by an anonymous function types in MuPAD. They are Check if an anonymous
that creates objects similar not available in MATLAB. MATLAB function is the
to the elements of this correct translation of the
domain. convertMuPADNotebook domain in this case, and that
translated a MuPAD the code still has the desired
domain to a MATLAB functionality.
anonymous function that
creates objects similar to
the elements of the domain.
For example, the code line
f:=Dom::IntegerMod(7)
gets translated
to a MATLAB
anonymous function f =
@(X)mod(X,sym(7)).
Ignoring assertions. Assertions are not available Verify the resulting code. If
in MATLAB. When assertions are not essential
translating a notebook file, part of your code, you
convertMuPADNotebook can ignore this warning.
ignores assertions. However, if your code relies
on assertions, you can
implement them using
conditional statements, such
as if-then.

3-36
Troubleshoot MuPAD to MATLAB Translation Warnings

Warning Message Meaning Recommendations


Ignoring assignment to Environment variables are Verify the resulting code.
a MuPAD environment global variables, such as If an assignment to an
variable. HISTORY, LEVEL, ORDER, environment variable is
and so on, that affect not essential for your code,
the behavior of MuPAD simply delete the warning.
algorithms.
In some cases, you can use
name-value pair arguments
in each function call, such as
setting the value Order in
the taylor function call.

In other cases, there is no


appropriate replacement.
Adjust the code so that it
does not require a global
setting.
Ignoring assignment to a The names of the built-in Verify the resulting code.
protected MuPAD constant MuPADfunctions, options, Check if the ignored
or function. and constants areprotected. assignment is essential for
If you try to assign a value the correctness of the code
to a MuPAD function, and results. If it is, adjust
option, or constant, the the code so that it does not
system throws an error. use this assignment, but still
This approach ensures has the desired functionality.
that you will not overwrite If it is not essential, simply
a built-in functionality delete this warning.
accidentally. See Protect
Function and Option
Names.
Ignoring info command. MATLAB functions do For information on a
Information not available in not have associated function, refer to MATLAB
MATLAB. information. documentation.

3-37
3 MuPAD in Symbolic Math Toolbox

Warning Message Meaning Recommendations


Ignoring options ''{0}''. These options are available Verify the resulting code.
in MuPAD, but are not Check if the ignored
available in MATLAB. options are essential for the
Because they do not appear correctness of the code and
to be essential for this code, results. If they are, adjust
convertMuPADNotebook the code so that it does not
ignores them. use these options, but still
has the desired functionality.
If they are not essential,
simply delete this warning.
Ignoring MuPAD path The MuPAD environment Verify the resulting code.
variables. variables FILEPATH, Check if the ignored path
NOTEBOOKPATH, variables are essential
WRITEPATH, and READPATH for the correctness of the
let you specify the working code and results. If they
folders for writing new files, are, adjust the code so
searching for files, loading that it does not use these
files, and so on if you do not preferences, but still has
specify the full path to the the desired functionality. If
file. they are not essential, simply
delete this warning.
These environment
variables are not available
in MATLAB.

3-38
Troubleshoot MuPAD to MATLAB Translation Warnings

Warning Message Meaning Recommendations


Ignoring MuPAD preference The MuPAD Pref library Verify the resulting code.
because there is no provides a collection of Check if the ignored
equivalent setting in functions which can be preferences are essential for
MATLAB. used to set and restore the correctness of the code
preferences, such as use of and results. If they are not
abbreviations in outputs, essential, simply delete this
representation of floating- warning.
point numbers, memory
limit on a MuPAD session,
and so on.

MATLAB uses sympref


for a few preferences, such
as specifying parameters
of Fourier transforms,
specifying the value of the
Heaviside function at 0,
or enabling and disabling
abbreviations in outputs.
Most preferences cannot
be translated to MATLAB
code.

3-39
3 MuPAD in Symbolic Math Toolbox

Warning Message Meaning Recommendations


Ignoring call to variable The names of the built-in Verify the resulting code.
protection mechanism. MuPADfunctions, options, Check if the ignored call
and constants areprotected. to variable protection
If you try to assign a value mechanism is essential for
to a MuPAD function, the correctness of the code
option, or constant, the and results. If it is, adjust
system throws an error. the code so that it does not
This approach ensures use this call, but still has the
that you will not overwrite desired functionality. If it is
a built-in functionality not essential, simply delete
accidentally. See Protect this warning.
Function and Option
Names.

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

Warning Message Meaning Recommendations


Ignoring default value when MuPAD tables let you set Verify the resulting code.
translating a table. the default value. This Check if the ignored value is
value is returned when you essential for the correctness
index into a table using the of the code and results.
index for which the entry If default values for the
does not exist. For example, tables are not essential,
if you create the table using simply delete this warning.
T := table(a = 13,c = Otherwise, you can create
42,10), and then index into a MATLAB function that
it using T[b], the result is checks if the containers.Map
10. object corresponding to the
MuPAD table has a certain
Default values for tables key, and if it does not,
cannot be translated returns the default value.
to MATLAB. When
translating a notebook file,
convertMuPADNotebook
ignores the corresponding
value.
Possibly missing a Do not skip multiplication Verify the resulting code.
multiplication sign. signs in MuPAD and Check if you missed a
MATLAB code. Both multiplication sign. Correct
languages require you to the code if needed.
type multiplication signs
explicitly. For example, the
expression x(x + 1) must
be typed as x*(x + 1).
MuPAD package The MuPAD package Adjust the code to avoid
mechanism not available in mechanism is not available using the MuPAD package
MATLAB. in MATLAB. mechanism.

3-41
3 MuPAD in Symbolic Math Toolbox

Edit MuPAD Code in MATLAB Editor

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.

Note: The MATLAB Editor cannot evaluate or debug MuPAD code.

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.

Comments in MuPAD Procedures


Enter a comment in a .mu file by entering the // characters. All text following the //
on the same line is ignored. The // characters do not affect text on succeeding lines. To
create a multi-line comment, start with the /* characters and end the comment with the
*/ characters. All text between these characters is ignored. You can nest comments using
/* and */.

3-43
3 MuPAD in Symbolic Math Toolbox

3-44
Notebook Files and Program Files

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.

The two main types of files in MuPAD are:

Notebook files, or notebooks


Program files

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

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

Differences Between MATLAB and MuPAD Syntax

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.

Common Tasks in MATLAB and MuPAD Syntax

Task MuPAD Syntax MATLAB Syntax


Assignment := =
List variables anames(All, User) whos
Numerical value of float(expression) double(expression)
expression
Suppress output : ;
Enter matrix matrix([[x11,x12,x13], [x11,x12,x13;
[x21,x22,x23]]) x21,x22,x23]
Translate MuPAD {a,b,c} unique([1 2 3])
set
Auto-completion Ctrl+space bar Tab

3-48
Differences Between MATLAB and MuPAD Syntax

Task MuPAD Syntax MATLAB Syntax


Equality, inequality =, <> ==, ~=
comparison

The next table lists differences between MATLAB expressions and MuPAD expressions.

MATLAB vs. MuPAD Expressions

MuPAD Expression MATLAB Expression


infinity Inf
PI pi
I i
undefined NaN
trunc fix
arcsin asin
arccos acos
arctan atan
arcsinh asinh
arccosh acosh
arctanh atanh
arccsc acsc
arcsec asec
arccot acot
arccsch acsch
arcsech asech
arccoth acoth
besselJ besselj
besselY bessely
besselI besseli
besselK besselk
lambertW lambertw

3-49
3 MuPAD in Symbolic Math Toolbox

MuPAD Expression MATLAB Expression


Si sinint
Ci cosint
EULER eulergamma
conjugate conj
CATALAN catalan

The MuPAD definition of exponential integral differs from the Symbolic Math Toolbox
counterpart.

Symbolic Math Toolbox Definition MuPAD Definition


Exponential expint(x) = Ei(x) = x
integral et

Ei( x) = t
dt for x < 0 .
exp( -t) -
t
dt for x > 0 =
x
exp(- xt)
Ei(1, x).
Ei( n, x) = tn
dt.
1

The definitions of Ei extend to the


complex plane, with a branch cut
along the negative real axis.

3-50
Copy Variables and Expressions Between MATLAB and MuPAD

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.

To copy a symbolic variable in the MATLAB workspace to a variable in the MuPAD


notebook engine with the same name, enter this command in the MATLAB Command
Window:

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

To assign a symbolic expression to a variable in a MuPAD notebook, enter:

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))

For this type of assignment, x must be a symbolic variable in the MATLAB


workspace.

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)

Copy and Paste Using the System Clipboard


You can also copy and paste between notebooks and the MATLAB workspace using
standard editing commands. If you copy a result in a MuPAD notebook to the system
clipboard, you might get the text associated with the expression, or a picture, depending
on your operating system and application support.

For example, consider this MuPAD expression:

Select the output with the mouse and copy it to the clipboard:

Paste this into the MATLAB workspace. The result is text:

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

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:

Error using solve (line 263)


Specify a variable for which you solve.

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()')

If you work in a MuPAD notebook, enter:


anames()

3-56
Call Built-In MuPAD Functions from MATLAB

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.

To access built-in MuPAD functions at the MATLAB command line, use


evalin(symengine,...) or feval(symengine,...). These functions are designed to
work like the existing MATLAB evalin and feval functions.

evalin and feval do not open a MuPAD notebook, and therefore, you cannot use these
functions to access MuPAD graphics capabilities.

evalin
For evalin, the syntax is
y = evalin(symengine,'MuPAD_Expression');

Use evalin when you want to perform computations in the MuPAD language, while
working in the MATLAB workspace. For example, to make a three-element symbolic
vector of the sin(kx) function, k = 1 to 3, enter:
y = evalin(symengine,'[sin(k*x) $ k = 1..3]')

y =
[ sin(x), sin(2*x), sin(3*x)]

feval
For evaluating a MuPAD function, you can also use the feval function. feval has a
different syntax than evalin, so it can be simpler to use. The syntax is:
y = feval(symengine,'MuPAD_Function',x1,...,xn);

MuPAD_Function represents the name of a MuPAD function. The arguments


x1,...,xn must be symbolic variables, numbers, or character vectors. For example, to
find the tenth element in the Fibonacci sequence, enter:

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

The numeric solver fsolve returns this result:

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.

evalin vs. feval


The evalin(symengine,...) function causes the MuPAD engine to evaluate a
character vector. Since the MuPAD engine workspace is generally empty, expressions
returned by evalin(symengine,...) are not simplified or evaluated according to their
definitions in the MATLAB workspace. For example:

syms x
y = x^2;
evalin(symengine, 'cos(y)')

ans =
cos(y)

Variable y is not expressed in terms of x because y is unknown to the MuPAD engine.

3-58
Call Built-In MuPAD Functions from MATLAB

In contrast, feval(symengine,...) can pass symbolic variables that exist in the


MATLAB workspace, and these variables are evaluated before being processed in the
MuPAD engine. For example:
syms x
y = x^2;
feval(symengine,'cos',y)

ans =
cos(x^2)

Floating-Point Arguments of evalin and feval


By default, MuPAD performs all computations in an exact form. When you call the
evalin or feval function with floating-point numbers as arguments, the toolbox
converts these arguments to rational numbers before passing them to MuPAD. For
example, when you calculate the incomplete gamma function, the result is the following
symbolic expression:
y = feval(symengine,'igamma', 0.1, 2.5)

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

Alternatively, use quotes to prevent the conversion of floating-point arguments to


rational numbers. (The toolbox treats arguments enclosed in quotes as character vectors.)
When MuPAD performs arithmetic operations on numbers involving at least one
floating-point number, it automatically switches to numeric computations and returns a
floating-point result:
feval(symengine,'igamma', '0.1', 2.5)

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

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.

Write MuPAD Procedures


A MuPAD procedure is a text file that you can write in any text editor. The recommended
practice is to use the MATLAB Editor on page 3-42.

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.

Steps to Take Before Calling a Procedure


To be able to call a procedure, you must first execute the code defining that procedure,
in a notebook. If you write a procedure in the same notebook, simply evaluate the input
region that contains the procedure. If you write a procedure in a separate file, you
must read the file into a notebook. Reading a file means finding it and executing the
commands inside it.

Read MuPAD Procedures

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

1 Folders specified by the environment variable READPATH


2 filename regarded as an absolute path
3 Current folder (depends on the operating system)

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.

Use Startup Commands and Scripts

Alternatively, you can add a MuPAD procedure to startup commands of a particular


notebook. This method lets you execute the procedure every time you start a notebook
engine. Startup commands are executed silently, without any visible outputs in the
notebook. You can copy the procedure to the dialog box that specifies startup commands
or attach the procedure as a startup script. For information, see Hide Code Lines.

Call Your Own MuPAD Procedures


You can extend the functionality available in the toolbox by writing your own procedures
in the MuPAD language. This section explains how to call such procedures at the
MATLAB Command Window.

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:

feval(symengine, 'myProc', 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

Clear Assumptions and Reset the Symbolic Engine

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.

Note: These commands

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.

If you reset the symbolic engine by entering the command


reset(symengine)

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.

Step Command MATLAB Workspace MuPAD Engine Workspace


1 syms x positive x x > 0
or
syms x;
assume(x > 0)
2 clear x empty x > 0
3 syms x x x > 0
4 assume(x,'clear') x empty

Check Assumptions Set On Variables


To check whether a variable, say x, has any assumptions in the symbolic engine
workspace associated with the MATLAB workspace, use the assumptions function in
the MATLAB Live Editor:
assumptions(x)

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')

Another way to set an assumption is to use the assume function:


syms z
assume(z ~= 0);
assumptions(z)

ans =
z ~= 0

To see assumptions set on all variables in the MATLAB workspace, use assumptions
without input arguments:
assumptions

ans =
[ in(x, 'real'), z ~= 0]

Clear assumptions set on x and z:


assume([x z],'clear')

assumptions

ans =
Empty sym: 1-by-0

Effects of Assumptions on Computations


Assumptions can affect many computations, including results returned by the solve
function. They also can affect the results of simplifications. For example, solve this
equation without any additional assumptions on its variable:
syms x
solve(x^4 == 1, x)

ans =
-1
1
-1i
1i

Now solve the same equation assuming that x is real:

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

Clearing x with assume(x,'clear') clears the assumption:

assume(x,'clear')
assumptions(x)

ans =
Empty sym: 1-by-0

3-69
3 MuPAD in Symbolic Math Toolbox

Create MATLAB Functions from MuPAD Expressions

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.

Copy MuPAD Variables to the MATLAB Workspace


If your notebook has a handle, like notebook_handle in this example, you can copy
variables from that notebook to the MATLAB workspace with the getVar function, and
then create a MATLAB function. For example, to convert the symbolic matrix S to a
MATLAB function:

1 Copy variable S to the MATLAB workspace:

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');

You can open and edit cartesian.m in the MATLAB Editor.

3-71
3 MuPAD in Symbolic Math Toolbox

Generate MATLAB Code in a MuPAD Notebook


To generate the MATLAB code from a MuPAD expression within the MuPAD notebook,
use the generate::MATLAB function. Then, you can create a new file that contains an
empty MATLAB function, copy the code, and paste it there. Alternatively, you can create
a file with a MATLAB formatted character vector representing a MuPAD expression, and
then add appropriate syntax to create a valid MATLAB function.

1 In the MuPAD Notebook app, use the generate::MATLAB function to generate


MATLAB code from the MuPAD expression. Instead of printing the result on screen,
use the fprint function to create a file and write the generated code to that file:

fprint(Unquoted, Text, "cartesian.m", generate::MATLAB(S)):

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

Create MATLAB Function Blocks from MuPAD Expressions

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:

1 In a MuPAD notebook, assign that expression to a variable.


2 Use the getVar function to copy that variable from a notebook to the MATLAB
workspace.

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.

For example, open a MuPAD notebook with the handle notebook_handle:


notebook_handle = mupad;

In this notebook, create the following symbolic expression:


r := sqrt(x^2 + y^2)

Use getVar to copy variable r to the MATLAB workspace:


r = getVar(notebook_handle,'r')

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

Create Simscape Equations from MuPAD Expressions

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.

If you work in the MuPAD Notebook app, you can:

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:

1 Open a MuPAD notebook with the handle notebook_handle:

notebook_handle = mupad;
2 In this notebook, define the following equation:

s:= ode(y'(t) = y(t)^2, y(t)):


3 Decide whether you want to generate the Simscape equation in the MuPAD
Notebook app or in the MATLAB Command Window.

3-76
Create Simscape Equations from MuPAD Expressions

GenerateSimscape Equations in the MuPAD Notebook App


To generate the Simscape equation in the same notebook, use generate::Simscape.
To display generated Simscape code on screen, use the print function. To remove
quotes and expand special characters like line breaks and tabs, use the printing option
Unquoted:

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;

Generate Simscape Equations in the MATLAB Command Window


To generate the Simscape equation in the MATLAB Command Window, follow these
steps:

1 Use getVar to copy variable s to the MATLAB workspace:

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

Functions Alphabetical List


4 Functions Alphabetical List

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

Symbolic number, variable, or expression.

Vector or matrix of symbolic numbers, variables, or expressions.

Examples
Compute absolute values of these symbolic real numbers:

[abs(sym(1/2)), abs(sym(0)), abs(sym(pi) - 4)]

ans =
[ 1/2, 0, 4 - pi]

4-2
abs

Compute the absolute values of each element of matrix A:

A = sym([(1/2 + i), -25; i*(i + 1), pi/6 - i*pi/2]);


abs(A)

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

For further computations, clear the assumption:


syms x clear

More About
Complex Modulus

The absolute value of a complex number z=x+y*i is the value z = x2 + y2 . Here, x


and y are real numbers. The absolute value of a complex number is also called a complex
modulus.

Tips

Calling abs for a number that is not a symbolic object invokes the MATLAB abs
function.

See Also
angle | imag | real | sign | signIm

Introduced before R2006a

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

Inverse Cosine Function for Numeric and Symbolic Arguments


Depending on its arguments, acos returns floating-point or exact symbolic results.

Compute the inverse cosine function for these numbers. Because these numbers are not
symbolic objects, acos returns floating-point results.

A = acos([-1, -1/3, -1/2, 1/4, 1/2, sqrt(3)/2, 1])

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 = acos(sym([-1, -1/3, -1/2, 1/4, 1/2, sqrt(3)/2, 1]))

symA =
[ pi, pi - acos(1/3), (2*pi)/3, acos(1/4), pi/3, pi/6, 0]

Use vpa to approximate symbolic results with floating-point numbers:

4-4
acos

vpa(symA)

ans =
[ 3.1415926535897932384626433832795,...
1.9106332362490185563277142050315,...
2.0943951023931954923084289221863,...
1.318116071652817965745664254646,...
1.0471975511965977461542144610932,...
0.52359877559829887307710723054658,...
0]

Plot Inverse Cosine Function


Plot the inverse cosine function on the interval from -1 to 1.

syms x
fplot(acos(x), [-1, 1])
grid on

4-5
4 Functions Alphabetical List

Handle Expressions Containing Inverse Cosine Function


Many functions, such as diff, int, taylor, and rewrite, can handle expressions
containing acos.

Find the first and second derivatives of the inverse cosine function:

syms x
diff(acos(x), x)
diff(acos(x), x, x)

ans =
-1/(1 - x^2)^(1/2)

4-6
acos

ans =
-x/(1 - x^2)^(3/2)

Find the indefinite integral of the inverse cosine function:


int(acos(x), x)

ans =
x*acos(x) - (1 - x^2)^(1/2)

Find the Taylor series expansion of acos(x):

taylor(acos(x), x)

ans =
- (3*x^5)/40 - x^3/6 - x + pi/2

Rewrite the inverse cosine function in terms of the natural logarithm:


rewrite(acos(x), 'log')

ans =
-log(x + (1 - x^2)^(1/2)*1i)*1i

Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix

Input, specified as a symbolic number, variable, expression, or function, or as a vector or


matrix of symbolic numbers, variables, expressions, or functions.

See Also
acot | acsc | asec | asin | atan | cos | cot | csc | sec | sin | tan

Introduced before R2006a

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

Inverse Hyperbolic Cosine Function for Numeric and Symbolic Arguments


Depending on its arguments, acosh returns floating-point or exact symbolic results.

Compute the inverse hyperbolic cosine function for these numbers. Because these
numbers are not symbolic objects, acosh returns floating-point results.

A = acosh([-1, 0, 1/6, 1/2, 1, 2])

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 = acosh(sym([-1, 0, 1/6, 1/2, 1, 2]))

symA =
[ pi*1i, (pi*1i)/2, acosh(1/6), (pi*1i)/3, 0, acosh(2)]

Use vpa to approximate symbolic results with floating-point numbers:

4-8
acosh

vpa(symA)

ans =

[ 3.1415926535897932384626433832795i,...
1.5707963267948966192313216916398i,...
1.4033482475752072886780470855961i,...
1.0471975511965977461542144610932i,...
0,...
1.316957896924816708625046347308]

Plot Inverse Hyperbolic Cosine Function


Plot the inverse hyperbolic cosine function on the interval from 1 to 10.

syms x
fplot(acosh(x), [1, 10])
grid on

4-9
4 Functions Alphabetical List

Handle Expressions Containing Inverse Hyperbolic Cosine Function


Many functions, such as diff, int, taylor, and rewrite, can handle expressions
containing acosh.

Find the first and second derivatives of the inverse hyperbolic cosine function. Simplify
the second derivative by using simplify.

syms x
diff(acosh(x), x)
simplify(diff(acosh(x), x, x))

ans =

4-10
acosh

1/((x - 1)^(1/2)*(x + 1)^(1/2))

ans =
-x/((x - 1)^(3/2)*(x + 1)^(3/2))

Find the indefinite integral of the inverse hyperbolic cosine function. Simplify the result
by using simplify.
int(acosh(x), x)

ans =
x*acosh(x) - (x - 1)^(1/2)*(x + 1)^(1/2)

Find the Taylor series expansion of acosh(x) for x > 1:


assume(x > 1)
taylor(acosh(x), x)

ans =
(x^5*3i)/40 + (x^3*1i)/6 + x*1i - (pi*1i)/2

For further computations, clear the assumption:


syms x clear

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

Input, specified as a symbolic number, variable, expression, or function, or as a vector or


matrix of symbolic numbers, variables, expressions, or functions.

See Also
acoth | acsch | asech | asinh | atanh | cosh | coth | csch | sech | sinh | tanh

4-11
4 Functions Alphabetical List

Introduced before R2006a

4-12
acot

acot
Symbolic inverse cotangent function

Syntax
acot(X)

Description
acot(X) returns the inverse cotangent function (arccotangent function) of X.

Examples

Inverse Cotangent Function for Numeric and Symbolic Arguments


Depending on its arguments, acot returns floating-point or exact symbolic results.

Compute the inverse cotangent function for these numbers. Because these numbers are
not symbolic objects, acot returns floating-point results.

A = acot([-1, -1/3, -1/sqrt(3), 1/2, 1, sqrt(3)])

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 = acot(sym([-1, -1/3, -1/sqrt(3), 1/2, 1, sqrt(3)]))

symA =
[ -pi/4, -acot(1/3), -pi/3, acot(1/2), pi/4, pi/6]

Use vpa to approximate symbolic results with floating-point numbers:

4-13
4 Functions Alphabetical List

vpa(symA)

ans =
[ -0.78539816339744830961566084581988,...
-1.2490457723982544258299170772811,...
-1.0471975511965977461542144610932,...
1.1071487177940905030170654601785,...
0.78539816339744830961566084581988,...
0.52359877559829887307710723054658]

Plot Inverse Cotangent Function


Plot the inverse cotangent function on the interval from -10 to 10.

syms x
fplot(acot(x), [-10, 10])
grid on

4-14
acot

Handle Expressions Containing Inverse Cotangent Function


Many functions, such as diff, int, taylor, and rewrite, can handle expressions
containing acot.

Find the first and second derivatives of the inverse cotangent function:

syms x
diff(acot(x), x)
diff(acot(x), x, x)

ans =
-1/(x^2 + 1)

4-15
4 Functions Alphabetical List

ans =
(2*x)/(x^2 + 1)^2

Find the indefinite integral of the inverse cotangent function:


int(acot(x), x)

ans =
log(x^2 + 1)/2 + x*acot(x)

Find the Taylor series expansion of acot(x) for x > 0:


assume(x > 0)
taylor(acot(x), x)

ans =
- x^5/5 + x^3/3 - x + pi/2

For further computations, clear the assumption:


syms x clear

Rewrite the inverse cotangent function in terms of the natural logarithm:


rewrite(acot(x), 'log')

ans =
(log(1 - 1i/x)*1i)/2 - (log(1i/x + 1)*1i)/2

Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix

Input, specified as a symbolic number, variable, expression, or function, or as a vector or


matrix of symbolic numbers, variables, expressions, or functions.

See Also
acos | acsc | asec | asin | atan | cos | cot | csc | sec | sin | tan

Introduced before R2006a

4-16
acoth

acoth
Symbolic inverse hyperbolic cotangent function

Syntax
acoth(X)

Description
acoth(X) returns the inverse hyperbolic cotangent function of X.

Examples

Inverse Hyperbolic Cotangent Function for Numeric and Symbolic


Arguments
Depending on its arguments, acoth returns floating-point or exact symbolic results.

Compute the inverse hyperbolic cotangent function for these numbers. Because these
numbers are not symbolic objects, acoth returns floating-point results.

A = acoth([-pi/2, -1, 0, 1/2, 1, pi/2])

A =
-0.7525 + 0.0000i -Inf + 0.0000i 0.0000 + 1.5708i...
0.5493 + 1.5708i Inf + 0.0000i 0.7525 + 0.0000i

Compute the inverse hyperbolic cotangent function for the numbers converted to
symbolic objects. For many symbolic (exact) numbers, acoth returns unresolved symbolic
calls.

symA = acoth(sym([-pi/2, -1, 0, 1/2, 1, pi/2]))

symA =

4-17
4 Functions Alphabetical List

[ -acoth(pi/2), Inf, -(pi*1i)/2, acoth(1/2), Inf, acoth(pi/2)]

Use vpa to approximate symbolic results with floating-point numbers:

vpa(symA)

ans =
[ -0.75246926714192715916204347800251,...
Inf,...
-1.5707963267948966192313216916398i,...
0.54930614433405484569762261846126...
- 1.5707963267948966192313216916398i,...
Inf,...
0.75246926714192715916204347800251]

Plot Inverse Hyperbolic Cotangent Function


Plot the inverse hyperbolic cotangent function on the interval from -10 to 10.

syms x
fplot(acoth(x), [-10, 10])
grid on

4-18
acoth

Handle Expressions Containing Inverse Hyperbolic Cotangent Function


Many functions, such as diff, int, taylor, and rewrite, can handle expressions
containing acoth.

Find the first and second derivatives of the inverse hyperbolic cotangent function:

syms x
diff(acoth(x), x)
diff(acoth(x), x, x)

ans =
-1/(x^2 - 1)

4-19
4 Functions Alphabetical List

ans =
(2*x)/(x^2 - 1)^2

Find the indefinite integral of the inverse hyperbolic cotangent function:


int(acoth(x), x)

ans =
log(x^2 - 1)/2 + x*acoth(x)

Find the Taylor series expansion of acoth(x) for x > 0:


assume(x > 0)
taylor(acoth(x), x)

ans =
x^5/5 + x^3/3 + x - (pi*1i)/2

For further computations, clear the assumption:


syms x clear

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

Input, specified as a symbolic number, variable, expression, or function, or as a vector or


matrix of symbolic numbers, variables, expressions, or functions.

See Also
acosh | acsch | asech | asinh | atanh | cosh | coth | csch | sech | sinh | tanh

Introduced before R2006a

4-20
acsc

acsc
Symbolic inverse cosecant function

Syntax
acsc(X)

Description
acsc(X) returns the inverse cosecant function (arccosecant function) of X.

Examples

Inverse Cosecant Function for Numeric and Symbolic Arguments


Depending on its arguments, acsc returns floating-point or exact symbolic results.

Compute the inverse cosecant function for these numbers. Because these numbers are
not symbolic objects, acsc returns floating-point results.

A = acsc([-2, 0, 2/sqrt(3), 1/2, 1, 5])

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 = acsc(sym([-2, 0, 2/sqrt(3), 1/2, 1, 5]))

symA =
[ -pi/6, Inf, pi/3, asin(2), pi/2, asin(1/5)]

Use vpa to approximate symbolic results with floating-point numbers:

4-21
4 Functions Alphabetical List

vpa(symA)

ans =
[ -0.52359877559829887307710723054658,...
Inf,...
1.0471975511965977461542144610932,...
1.5707963267948966192313216916398...
- 1.3169578969248165734029498707969i,...
1.5707963267948966192313216916398,...
0.20135792079033079660099758712022]

Plot Inverse Cosecant Function


Plot the inverse cosecant function on the interval from -10 to 10.

syms x
fplot(acsc(x), [-10, 10])
grid on

4-22
acsc

Handle Expressions Containing Inverse Cosecant Function


Many functions, such as diff, int, taylor, and rewrite, can handle expressions
containing acsc.

Find the first and second derivatives of the inverse cosecant function:

syms x
diff(acsc(x), x)
diff(acsc(x), x, x)

ans =
-1/(x^2*(1 - 1/x^2)^(1/2))

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))

Find the indefinite integral of the inverse cosecant function:


int(acsc(x), x)

ans =
x*asin(1/x) + log(x + (x^2 - 1)^(1/2))*sign(x)

Find the Taylor series expansion of acsc(x) around x = Inf:

taylor(acsc(x), x, Inf)

ans =
1/x + 1/(6*x^3) + 3/(40*x^5)

Rewrite the inverse cosecant function in terms of the natural logarithm:


rewrite(acsc(x), 'log')

ans =
-log(1i/x + (1 - 1/x^2)^(1/2))*1i

Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix

Input, specified as a symbolic number, variable, expression, or function, or as a vector or


matrix of symbolic numbers, variables, expressions, or functions.

See Also
acos | acot | asec | asin | atan | cos | cot | csc | sec | sin | tan

Introduced before R2006a

4-24
acsch

acsch
Symbolic inverse hyperbolic cosecant function

Syntax
acsch(X)

Description
acsch(X) returns the inverse hyperbolic cosecant function of X.

Examples

Inverse Hyperbolic Cosecant Function for Numeric and Symbolic


Arguments
Depending on its arguments, acsch returns floating-point or exact symbolic results.

Compute the inverse hyperbolic cosecant function for these numbers. Because these
numbers are not symbolic objects, acsch returns floating-point results.

A = acsch([-2*i, 0, 2*i/sqrt(3), 1/2, i, 3])

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 = acsch(sym([-2*i, 0, 2*i/sqrt(3), 1/2, i, 3]))

symA =
[ (pi*1i)/6, Inf, -(pi*1i)/3, asinh(2), -(pi*1i)/2, asinh(1/3)]

4-25
4 Functions Alphabetical List

Use vpa to approximate symbolic results with floating-point numbers:

vpa(symA)

ans =
[ 0.52359877559829887307710723054658i,...
Inf,...
-1.0471975511965977461542144610932i,...
1.4436354751788103424932767402731,...
-1.5707963267948966192313216916398i,...
0.32745015023725844332253525998826]

Plot Inverse Hyperbolic Cosecant Function


Plot the inverse hyperbolic cosecant function on the interval from -10 to 10.

syms x
fplot(acsch(x), [-10, 10])
grid on

4-26
acsch

Handle Expressions Containing Inverse Hyperbolic Cosecant Function


Many functions, such as diff, int, taylor, and rewrite, can handle expressions
containing acsch.

Find the first and second derivatives of the inverse hyperbolic cosecant function:

syms x
diff(acsch(x), x)
diff(acsch(x), x, x)

ans =
-1/(x^2*(1/x^2 + 1)^(1/2))

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))

Find the indefinite integral of the inverse hyperbolic cosecant function:


int(acsch(x), x)

ans =
x*asinh(1/x) + asinh(x)*sign(x)

Find the Taylor series expansion of acsch(x) around x = Inf:

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

Input, specified as a symbolic number, variable, expression, or function, or as a vector or


matrix of symbolic numbers, variables, expressions, or functions.

See Also
acosh | acoth | asech | asinh | atanh | cosh | coth | csch | sech | sinh | tanh

Introduced before R2006a

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

Symbolic square matrix.

Output Arguments
X

Symbolic square matrix of the same size as A.

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

Also verify that det(A)*eye(3) = X*A:

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)]

Verify that invA is the inverse of A:

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

The (j,i)-th cofactor of A is defined as

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)

airy( ___ ,1)

Description
airy(x) returns the Airy function of the first kind, Ai(x), for each element of x.

airy(0,x) is the same as airy(x).

airy(1,x) returns the derivative of Ai(x).

airy(2,x) returns the Airy function of the second kind, Bi(x).

airy(3,x) returns the derivative of Bi(x).

airy(n,x) uses the values in vector n to return the corresponding Airy functions of
elements of vector x. Both n and x must have the same size.

airy( ___ ,1) returns the Scaled Airy Functions on page 4-40 following the syntax
for the MATLAB airy function.

4-32
airy

Examples

Find the Airy Function of the First Kind


Find the Airy function of the first kind, Ai(x), for numeric or symbolic inputs using airy.
Approximate exact symbolic outputs using vpa.

Find the Airy function of the first kind, Ai(x), at 1.5. Because the input is double and not
symbolic, you get a double result.

airy(1.5)

ans =
0.0717

Find the Airy function of the values of vector v symbolically, by converting v to symbolic
form using sym. Because the input is symbolic, airy returns exact symbolic results. The
exact symbolic results for most symbolic inputs are unresolved function calls.

v = sym([-1 0 25.1 1+1i]);


vAiry = airy(v)

vAiry =
[ airy(0, -1), 3^(1/3)/(3*gamma(2/3)), airy(0, 251/10), airy(0, 1 + 1i)]

Numerically approximate the exact symbolic result using vpa.

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

Find the Airy Function of the Second Kind


Find the Airy function of the second kind, Bi(x), of the symbolic input [-3 4 1+1i x^2]
by specifying the first argument as 2. Because the input is symbolic, airy returns exact
symbolic results. The exact symbolic results for most symbolic inputs are unresolved
function calls.

v = sym([-3 4 1+1i x^2]);


vAiry = airy(2, v)

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 Airy Functions

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

Plot the absolute value of over the complex plane.

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

Find Derivatives of Airy Functions


Find the derivative of the Airy function of the first kind, Ai(x), at 0 by specifying the first
argument of airy as 1. Then, numerically approximate the derivative using vpa.

dAi = airy(1, sym(0))


dAi_vpa = vpa(dAi)

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

Solve Airy Differential Equation for Airy Functions


Show that the Airy functions Ai(x) and Bi(x) are the solutions of the differential equation

2 y
- xy = 0 .
x2

syms y(x)
dsolve(diff(y, 2) - x*y == 0)

ans =
C1*airy(0, x) + C2*airy(2, x)

Differentiate Airy Functions


Differentiate expressions containing airy.

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

Expand Airy Function using Taylor Series


Find the Taylor series expansion of the Airy functions, Ai(x) and Bi(x), using taylor.

aiTaylor = taylor(airy(x))
biTaylor = taylor(airy(2, x))

aiTaylor =
- (3^(1/6)*gamma(2/3)*x^4)/(24*pi) + (3^(1/3)*x^3)/(18*gamma(2/3))...
- (3^(1/6)*gamma(2/3)*x)/(2*pi) + 3^(1/3)/(3*gamma(2/3))
biTaylor =
(3^(2/3)*gamma(2/3)*x^4)/(24*pi) + (3^(5/6)*x^3)/(18*gamma(2/3))...
+ (3^(2/3)*gamma(2/3)*x)/(2*pi) + 3^(5/6)/(3*gamma(2/3))

Fourier Transform of Airy Function


Find the Fourier transform of the Airy function Ai(x) using fourier.

syms x
aiFourier = fourier(airy(x))

aiFourier =
exp((w^3*1i)/3)

Numeric Roots of Airy Function


Find a root of the Airy function Ai(x) numerically using vpasolve.

syms x
vpasolve(airy(x) == 0, x)

ans =
-226.99630507523600716771890962744

Find a root in the interval [-5 -3].

vpasolve(airy(x) == 0, x, [-5 -3])

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

Input, specified as a number, vector, matrix, or multidimensional array, or a symbolic


number, variable, vector, matrix, multidimensional array, function, or expression.

n Type of Airy function


0 (default) | number | vector | matrix | multidimensional array | symbolic number |
symbolic variable | symbolic vector | symbolic matrix | symbolic multidimensional array

Type of Airy function, specified as a number, vector, matrix, or multidimensional array,


or a symbolic number, variable, vector, matrix, or multidimensional array. The values of
the input must be 0, 1, 2, or 3, which specify the Airy function as follows.

n Returns
0 (default) Airy function, Ai(x), which is the same as airy(x).
1 Derivative of Airy function, Ai(x).
2 Airy function of the second kind, Bi(x).
3 Derivative of Airy function of the second kind, Bi(x).

More About
Airy Functions

The Airy functions Ai(x) and Bi(x) are the two linearly independent solutions of the
differential equation

2 y
- xy = 0 .
x2

Ai(x) is called the Airy function of the first kind. Bi(x) is called the Airy function of the
second kind.

4-39
4 Functions Alphabetical List

Scaled Airy Functions

The Airy function of the first kind, Ai(x), is scaled as

2 (3 / 2)
x
e 3 Ai ( x ) .

The derivative, Ai(x), is scaled by the same factor.

The Airy function of the second kind, Bi(x), is scaled as

2
- Re( x (3 / 2) )
e 3 Bi ( x) .

The derivative, Bi(x), is scaled by the same factor.

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.

all(A,dim) tests along the dimension of A specified by dim.

Input Arguments
A

Symbolic vector, matrix, or multidimensional symbolic array. For example, it can


be an array of symbolic equations, inequalities, or logical expressions with symbolic
subexpressions.

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

Create this matrix of symbolic equations and inequalities:

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

Create this matrix of symbolic equations and inequalities:

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:

all([1, 2, -3, 4 + i, x == x])

ans =
logical
1

More About
Tips

If A is an empty symbolic array, all(A) returns logical 1.

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.

If there are no open notebooks, allMuPADNotebooks returns an empty object [ empty


mupad ].

Examples
Identify All Open Notebooks

Get a vector of handles to 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

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

Create Handle to Existing Notebook

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.

Create a new notebook:


mupad

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

Create MuPAD Notebooks on page 3-3


Open MuPAD Notebooks on page 3-6
Save MuPAD Notebooks on page 3-12
Evaluate MuPAD Notebooks from MATLAB on page 3-13
Copy Variables and Expressions Between MATLAB and MuPAD on page 3-51

4-46
allMuPADNotebooks

Close MuPAD Notebooks from MATLAB on page 3-17

Output Arguments
L All open MuPAD notebooks
vector of handles to notebooks

All open MuPAD notebooks, returned as a vector of handles to these 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.

and(A,B) is equivalent to A & B.

Input Arguments
A

Symbolic equation, inequality, or logical expression that contains symbolic


subexpressions.

Symbolic equation, inequality, or logical expression that contains symbolic


subexpressions.

Examples
Combine these symbolic inequalities into the logical expression using &:

syms x y
xy = x >= 0 & y >= 0;

Set the corresponding assumptions on variables x and y using assume:

4-48
and

assume(xy)

Verify that the assumptions are set:


assumptions

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

To evaluate these inequalities to logical 1 or 0, use isAlways:


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

4-49
4 Functions Alphabetical List

s2 =
FALSE

Convert symbolic TRUE or FALSE to logical values using isAlways:

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

Evaluate these inequalities to logical 1 or 0 using isAlways.

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.

[angle(1 + i), angle(4 + pi*i), angle(Inf + Inf*i)]

ans =
0.7854 0.6658 0.7854

Compute the polar angles of these complex numbers which are converted to symbolic
objects:

[angle(sym(1) + i), angle(sym(4) + sym(pi)*i), angle(Inf + sym(Inf)*i)]

ans =
[ pi/4, atan(pi/4), pi/4]

4-52
angle

Compute the limits of these symbolic expressions:


syms x
limit(angle(x + x^2*i/(1 + x)), x, -Inf)
limit(angle(x + x^2*i/(1 + x)), x, Inf)

ans =
-(3*pi)/4

ans =
pi/4

Compute the polar angles of the elements of matrix Z:

Z = sym([sqrt(3) + 3*i, 3 + sqrt(3)*i; 1 + i, i]);


angle(Z)

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.

any(A,dim) tests along the dimension of A specified by dim.

Input Arguments
A

Symbolic vector, matrix, or multidimensional symbolic array. For example, it can


be an array of symbolic equations, inequalities, or logical expressions with symbolic
subexpressions.

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

Create this matrix of symbolic equations and inequalities:

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

Create this matrix of symbolic equations and inequalities:

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

If A is an empty symbolic array, any(A) returns logical 0.

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;

Use argnames to find input variables of f:

argnames(f)

ans =
[ x, y]

Create this symbolic function:

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

Inverse Secant Function for Numeric and Symbolic Arguments


Depending on its arguments, asec returns floating-point or exact symbolic results.

Compute the inverse secant function for these numbers. Because these numbers are not
symbolic objects, asec returns floating-point results.

A = asec([-2, 0, 2/sqrt(3), 1/2, 1, 5])

A =
2.0944 + 0.0000i 0.0000 + Infi 0.5236 + 0.0000i...
0.0000 + 1.3170i 0.0000 + 0.0000i 1.3694 + 0.0000i

Compute the inverse secant function for the numbers converted to symbolic objects. For
many symbolic (exact) numbers, asec returns unresolved symbolic calls.

symA = asec(sym([-2, 0, 2/sqrt(3), 1/2, 1, 5]))

symA =
[ (2*pi)/3, Inf, pi/6, acos(2), 0, acos(1/5)]

Use vpa to approximate symbolic results with floating-point numbers:

4-60
asec

vpa(symA)

ans =
[ 2.0943951023931954923084289221863,...
Inf,...
0.52359877559829887307710723054658,...
1.3169578969248165734029498707969i,...
0,...
1.3694384060045659001758622252964]

Plot Inverse Secant Function


Plot the inverse secant function on the interval from -10 to 10.

syms x
fplot(asec(x), [-10, 10])
grid on

4-61
4 Functions Alphabetical List

Handle Expressions Containing Inverse Secant Function


Many functions, such as diff, int, taylor, and rewrite, can handle expressions
containing asec.

Find the first and second derivatives of the inverse secant function:

syms x
diff(asec(x), x)
diff(asec(x), x, x)

ans =
1/(x^2*(1 - 1/x^2)^(1/2))

4-62
asec

ans =
- 2/(x^3*(1 - 1/x^2)^(1/2)) - 1/(x^5*(1 - 1/x^2)^(3/2))

Find the indefinite integral of the inverse secant function:


int(asec(x), x)

ans =
x*acos(1/x) - log(x + (x^2 - 1)^(1/2))*sign(x)

Find the Taylor series expansion of asec(x) around x = Inf:

taylor(asec(x), x, Inf)

ans =
pi/2 - 1/x - 1/(6*x^3) - 3/(40*x^5)

Rewrite the inverse secant function in terms of the natural logarithm:


rewrite(asec(x), 'log')

ans =
-log(1/x + (1 - 1/x^2)^(1/2)*1i)*1i

Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix

Input, specified as a symbolic number, variable, expression, or function, or as a vector or


matrix of symbolic numbers, variables, expressions, or functions.

See Also
acos | acot | acsc | asin | atan | cos | cot | csc | sec | sin | tan

Introduced before R2006a

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

Inverse Hyperbolic Secant Function for Numeric and Symbolic Arguments


Depending on its arguments, asech returns floating-point or exact symbolic results.

Compute the inverse hyperbolic secant function for these numbers. Because these
numbers are not symbolic objects, asech returns floating-point results.

A = asech([-2, 0, 2/sqrt(3), 1/2, 1, 3])

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 = asech(sym([-2, 0, 2/sqrt(3), 1/2, 1, 3]))

symA =
[ (pi*2i)/3, Inf, (pi*1i)/6, acosh(2), 0, acosh(1/3)]

Use vpa to approximate symbolic results with floating-point numbers:

4-64
asech

vpa(symA)

ans =
[ 2.0943951023931954923084289221863i,...
Inf,...
0.52359877559829887307710723054658i,...
1.316957896924816708625046347308,...
0,...
1.230959417340774682134929178248i]

Plot Inverse Hyperbolic Secant Function


Plot the inverse hyperbolic secant function on the interval from 0 to 1.

syms x
fplot(asech(x), [0, 1])
grid on

4-65
4 Functions Alphabetical List

Handle Expressions Containing Inverse Hyperbolic Secant Function


Many functions, such as diff, int, taylor, and rewrite, can handle expressions
containing asech.

Find the first and second derivatives of the inverse hyperbolic secant function. Simplify
the second derivative by using simplify.

syms x
diff(asech(x), x)
simplify(diff(asech(x), x, x))

ans =

4-66
asech

-1/(x^2*(1/x - 1)^(1/2)*(1/x + 1)^(1/2))

ans =
-(2*x^2 - 1)/(x^5*(1/x - 1)^(3/2)*(1/x + 1)^(3/2))

Find the indefinite integral of the inverse hyperbolic secant function:


int(asech(x), x)

ans =
atan(1/((1/x - 1)^(1/2)*(1/x + 1)^(1/2))) + x*acosh(1/x)

Find the Taylor series expansion of asech(x) around x = Inf:

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

Input, specified as a symbolic number, variable, expression, or function, or as a vector or


matrix of symbolic numbers, variables, expressions, or functions.

See Also
acosh | acoth | acsch | asinh | atanh | cosh | coth | csch | sech | sinh | tanh

Introduced before R2006a

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

Inverse Sine Function for Numeric and Symbolic Arguments


Depending on its arguments, asin returns floating-point or exact symbolic results.

Compute the inverse sine function for these numbers. Because these numbers are not
symbolic objects, asin returns floating-point results.

A = asin([-1, -1/3, -1/2, 1/4, 1/2, sqrt(3)/2, 1])

A =
-1.5708 -0.3398 -0.5236 0.2527 0.5236 1.0472 1.5708

Compute the inverse sine function for the numbers converted to symbolic objects. For
many symbolic (exact) numbers, asin returns unresolved symbolic calls.

symA = asin(sym([-1, -1/3, -1/2, 1/4, 1/2, sqrt(3)/2, 1]))

symA =
[ -pi/2, -asin(1/3), -pi/6, asin(1/4), pi/6, pi/3, pi/2]

Use vpa to approximate symbolic results with floating-point numbers:

4-68
asin

vpa(symA)

ans =
[ -1.5707963267948966192313216916398,...
-0.33983690945412193709639251339176,...
-0.52359877559829887307710723054658,...
0.25268025514207865348565743699371,...
0.52359877559829887307710723054658,...
1.0471975511965977461542144610932,...
1.5707963267948966192313216916398]

Plot Inverse Sine Function


Plot the inverse sine function on the interval from -1 to 1.

syms x
fplot(asin(x), [-1, 1])
grid on

4-69
4 Functions Alphabetical List

Handle Expressions Containing Inverse Sine Function


Many functions, such as diff, int, taylor, and rewrite, can handle expressions
containing asin.

Find the first and second derivatives of the inverse sine function:

syms x
diff(asin(x), x)
diff(asin(x), x, x)

ans =
1/(1 - x^2)^(1/2)

4-70
asin

ans =
x/(1 - x^2)^(3/2)

Find the indefinite integral of the inverse sine function:


int(asin(x), x)

ans =
x*asin(x) + (1 - x^2)^(1/2)

Find the Taylor series expansion of asin(x):

taylor(asin(x), x)

ans =
(3*x^5)/40 + x^3/6 + x

Rewrite the inverse sine function in terms of the natural logarithm:


rewrite(asin(x), 'log')

ans =
-log((1 - x^2)^(1/2) + x*1i)*1i

Input Arguments
X Input
symbolic number | symbolic variable | symbolic expression | symbolic function |
symbolic vector | symbolic matrix

Input, specified as a symbolic number, variable, expression, or function, or as a vector or


matrix of symbolic numbers, variables, expressions, or functions.

See Also
acos | acot | acsc | asec | atan | cos | cot | csc | sec | sin | tan

Introduced before R2006a

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

Inverse Hyperbolic Sine Function for Numeric and Symbolic Arguments


Depending on its arguments, asinh returns floating-point or exact symbolic results.

Compute the inverse hyperbolic sine function for these numbers. Because these numbers
are not symbolic objects, asinh returns floating-point results.

A = asinh([-i, 0, 1/6, i/2, i, 2])

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 = asinh(sym([-i, 0, 1/6, i/2, i, 2]))

symA =
[ -(pi*1i)/2, 0, asinh(1/6), (pi*1i)/6, (pi*1i)/2, asinh(2)]

Use vpa to approximate symbolic results with floating-point numbers:

4-72
asinh

vpa(symA)

ans =
[ -1.5707963267948966192313216916398i,...
0,...
0.16590455026930117643502171631553,...
0.52359877559829887307710723054658i,...
1.5707963267948966192313216916398i,...
1.4436354751788103012444253181457]

Plot Inverse Hyperbolic Sine Function


Plot the inverse hyperbolic sine function on the interval from -10 to 10.

syms x
fplot(asinh(x), [-10, 10])
grid on

4-73
4 Functions Alphabetical List

Handle Expressions Containing Inverse Hyperbolic Sine Function


Many functions, such as diff, int, taylor, and rewrite, can handle expressions
containing asinh.

Find the first and second derivatives of the inverse hyperbolic sine function:

syms x
diff(asinh(x), x)
diff(asinh(x), x, x)

ans =
1/(x^2 + 1)^(1/2)

4-74
asinh

ans =
-x/(x^2 + 1)^(3/2)

Find the indefinite integral of the inverse hyperbolic sine function:


int(asinh(x), x)

ans =
x*asinh(x) - (x^2 + 1)^(1/2)

Find the Taylor series expansion of asinh(x):

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

Input, specified as a symbolic number, variable, expression, or function, or as a vector or


matrix of symbolic numbers, variables, expressions, or functions.

See Also
acosh | acoth | acsch | asech | atanh | cosh | coth | csch | sech | sinh | tanh

Introduced before R2006a

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.

assume(expr,'clear') clears all 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 Variable Is Even or Odd


Assume the symbolic variable x is even, by setting the assumption that x/2 is an integer.

Assume x is even.
syms x
assume(x/2,'integer')

Find all even numbers between 0 and 10 using solve.


solve(x>0,x<10,x)

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

Clear assumptions on x for further computations.

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.

Use assume to set an assumption that a does not equal -1.

syms x a
assume(a ~= -1)

Compute this integral.

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))

Assumptions on Parameters and Variables of Equation


Use assumptions on the symbolic parameter and variable in the kinematic equation for
free fall motion.

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 time t is positive and solve the same equation again.

assume(t > 0)
solve(h == g*t^2/2,t)

Warning: The solutions are valid under the following


conditions: 0 < h. To include parameters and conditions in
the solution, specify the 'ReturnConditions' option.
> In solve>warnIfParams at 514
In solve at 356
ans =
(2^(1/2)*h^(1/2))/g^(1/2)

The solver returns a warning that h must be positive. This warning follows as the object
is above ground.

For further computations, clear the assumptions.

assume([g t],'clear')

Use Assumptions for Simplification


Setting appropriate assumptions can result in simpler expressions.

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 is an integer. simplify now simplifies the expression.

assume(n,'integer')

4-79
4 Functions Alphabetical List

simplify(sin(2*n*pi))

ans =
0

For further computations, clear the assumption.


assume(n,'clear')

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)

Set the assumption x21>0 to produce a simpler result.


assume(x^2 - 1 > 0)
int(1/abs(x^2 - 1),x)

ans =
-atanh(x)

For further computations, clear the assumption.


assume(x,'clear')

Assumptions Reducing Number of Solutions


Use assumptions to restrict the returned solutions of an equation to a particular interval.

Solve this equation.


syms x
solve(x^5 - (565*x^4)/6 - (1159*x^3)/2 - (2311*x^2)/6 + (365*x)/2 + 250/3, x)

ans =

4-80
assume

-5
-1
-1/3
1/2
100

Use assume to restrict the solutions to the interval 1<=x<=1.

assume(-1 <= x <= 1)


solve(x^5 - (565*x^4)/6 - (1159*x^3)/2 - (2311*x^2)/6 + (365*x)/2 + 250/3, x)

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.

assume(x < -1 | x > 1)


solve(x^5 - (565*x^4)/6 - (1159*x^3)/2 - (2311*x^2)/6 + (365*x)/2 + 250/3, x)

ans =
-5
100

For further computations, clear the assumptions.

assume(x,'clear')

Assumptions on Matrix Elements


Set assumptions on all elements of a matrix using sym.

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

Return the assumptions on the elements of A using assumptions.

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')

For further computations, clear the assumptions.

assume(A,'clear')

Input Arguments
condition Assumption statement
symbolic expression | symbolic equation | symbolic relation | vector or matrix of
symbolic expressions, equations, or relations

Assumption statement, specified as a symbolic expression, equation, relation, or vector


or matrix of symbolic expressions, equations, or relations. You also can combine several
assumptions by using the logical operators and, or, xor, not, or their shortcuts.

expr Expression to set assumption on


symbolic variable | symbolic expression | vector or matrix of symbolic variables or
expressions

Expression to set assumption on, specified as a symbolic variable, expression, vector, or


matrix. If expr is a vector or matrix, then assume(expr,set) sets an assumption that
each element of expr belongs to set.

set Set of integer, rational, real, or positive numbers


'integer' | 'rational' | 'real' | 'positive'

Set of integer, rational, real, or positive numbers, specified as 'integer', 'rational',


'real', or 'positive'.

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

Default Assumption on page 1-27

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.

assumeAlso(expr,set) states that expr belongs to set, in addition to all previously


made assumptions.

Examples

Assumptions Specified as Relations


Set assumptions using assume. Then add more assumptions using assumeAlso.

Solve this equation assuming that both x and y are nonnegative.

syms x y
assume(x >= 0 & y >= 0)
s = solve(x^2 + y^2 == 1, y)

Warning: The solutions are valid under the following


conditions: x <= 1; x == 1. To include parameters and
conditions in the solution, specify the 'ReturnConditions'
option.
> In solve>warnIfParams at 514
In solve at 356
s =

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)

Solve the same equation under the expanded set of assumptions.

s = solve(x^2 + y^2 == 1, y)

s =
(1 - x)^(1/2)*(x + 1)^(1/2)

For further computations, clear the assumptions.

assume([x y],'clear')

Assumptions Specified as Sets


Set assumptions using syms. Then add more assumptions using assumeAlso.

When declaring the symbolic variable n, set an assumption that n is positive.

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')

Return all assumptions affecting variable n using assumptions. In this case, n is a


positive integer.

assumptions(n)

ans =
[ in(n, 'integer'), 0 < n]

For further computations, clear the assumptions.

4-86
assumeAlso

assume(n,'clear')

Assumptions on Matrix Elements


Use the assumption on a matrix as a shortcut for setting the same assumption on each
matrix element.

Create the 3-by-3 symbolic matrix A with auto-generated elements. To assume every
element of A is rational, specify set as 'rational'.

A = sym('A',[3 3],'rational')

A =
[ A1_1, A1_2, A1_3]
[ A2_1, A2_2, A2_3]
[ A3_1, A3_2, A3_3]

Now, add the assumption that each element of A is greater than 1.

assumeAlso(A > 1)

Return assumptions affecting elements of A using assumptions:

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]

For further computations, clear the assumptions.


assume(A,'clear')

Contradicting Assumptions
When you add assumptions, ensure that the new assumptions do not contradict
the previous assumptions. Contradicting assumptions can lead to inconsistent and
unpredictable results. In some cases, assumeAlso detects conflicting assumptions and
issues an error.

4-87
4 Functions Alphabetical List

Try to set contradicting assumptions. assumeAlso returns an error.


syms y
assume(y,'real')
assumeAlso(y == i)

Error using mupadengine/feval (line 163)


Assumptions are inconsistent.
Error in sym/assumeAlso (line 551)
feval(symengine, 'assumeAlso', cond);

assumeAlso does not guarantee to detect contradicting assumptions. For example,


assume that y is nonzero, and both y and y*i are real values.
syms y
assume(y ~= 0)
assumeAlso(y,'real')
assumeAlso(y*i,'real')

Return all assumptions affecting variable y using assumptions:


assumptions(y)

ans =
[ in(y, 'real'), y ~= 0, in(y*1i, 'real')]

For further computations, clear the assumptions.


assume(y,'clear')

Input Arguments
condition Assumption statement
symbolic expression | symbolic equation | relation | vector or matrix of symbolic
expressions, equations, or relations

Assumption statement, specified as a symbolic expression, equation, relation, or vector


or matrix of symbolic expressions, equations, or relations. You also can combine several
assumptions by using the logical operators and, or, xor, not, or their shortcuts.

expr Expression to set assumption on


symbolic variable | symbolic expression | vector or matrix of symbolic variables or
expressions

4-88
assumeAlso

Expression to set assumption on, specified as a symbolic variable, expression, or a


vector or matrix of symbolic variables or expressions. If expr is a vector or matrix, then
assumeAlso(expr,set) sets an assumption that each element of expr belongs to set.

set Set of integer, rational, real, or positive numbers


'integer' | 'rational' | 'real' | 'positive'

Set of integer, rational, real, or positive numbers, specified as 'integer', 'rational',


'real', or 'positive'.

More About
Tips

assumeAlso keeps all assumptions previously set on the symbolic variables. To


replace previous assumptions with the new one, use assume.
When adding assumptions, always check that a new assumption does not contradict
the existing assumptions. To see existing assumptions, use assumptions. Symbolic
Math Toolbox does not guarantee to detect conflicting assumptions. Conflicting
assumptions can lead to unpredictable and inconsistent results.
When you delete a symbolic variable from the MATLAB workspace using clear, all
assumptions that you set on that variable remain in the symbolic engine. If later you
declare a new symbolic variable with the same name, it inherits these assumptions.
To clear all assumptions set on a symbolic variable var use this command.

assume(var,'clear')
To clear all objects in the MATLAB workspace and close the 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.

Default Assumption on page 1-27

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')

The syntax in(n, 'integer') indicates n is an 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]

assumptions returns the assumption x < 42 because it affects n through the


assumption n < x. Thus, assumptions returns the transitive closure of assumptions,
which is all assumptions that mathematically affect the input.

Set the assumption on variable m that 1 < m < 3. Return all assumptions on m and x
using assumptions.
syms m
assume(1<m<3)
assumptions([m x])

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]

For further computations, clear the assumptions.


assume([m n x],'clear')

Multiple Assumptions on One Variable


You cannot set an additional assumption on a variable using assume because assume
clears all previous assumptions on that variable. To set an additional assumption on a
variable, using assumeAlso.

Set an assumption on x using assume. Set an additional assumption on x use


assumeAlso. Use assumptions to return the multiple assumptions on x.
syms x
assume(x,'real')
assumeAlso(x<0)
assumptions(x)

ans =

4-92
assumptions

[ x < 0, in(x, 'real')]

The syntax in(x, 'real') indicates x is real.

For further computations, clear the assumptions.


assume(x,'clear')

Assumptions Affecting Expressions and Functions


assumptions accepts symbolic expressions and functions as input and returns all
assumptions that affect all variables in the symbolic expressions or functions.

Set assumptions on variables in a symbolic expression. 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')]

Clear the assumptions for further computations.


assume([a b c],'clear')

Restore Old Assumptions


To restore old assumptions, first store the assumptions returned by assumptions. Then
you can restore these assumptions at any point by calling assume or assumeAlso.

Solve the equation for a spring 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

dsolve(m*diff(x,t,t) == -k*x, x(0)==0)

ans =
C8*sin((k^(1/2)*t)/m^(1/2))

Suppose you want to explore solutions unconstrained by assumptions, but want to


restore the assumptions afterwards. First store the assumptions using assumptions,
then clear the assumptions and solve the equation. dsolve returns unconstrained
solutions.
tmp = assumptions;
assume([m k],'clear')
dsolve(m*diff(x,t,t) == -k*x, x(0)==0)

ans =
C10*exp((t*(-k*m)^(1/2))/m) + C10*exp(-(t*(-k*m)^(1/2))/m)

Restore the original assumptions using assume.


assume(tmp)

After computations are complete, clear assumptions using assume.


assume([m k],'clear')

Input Arguments
var Symbolic input to check for assumptions
symbolic variable | symbolic expression | symbolic function | symbolic vector | symbolic
matrix | symbolic multidimensional array

Symbolic input for which to show assumptions, specified as a symbolic variable,


expression, or function, or a vector, matrix, or multidimensional array of symbolic
variables, expressions, or functions.

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)

Immediately before or after executing reset(symengine) you should clear all


symbolic objects in the MATLAB workspace.
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

Default Assumption on page 1-27

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

Inverse Tangent Function for Numeric and Symbolic Arguments


Depending on its arguments, atan returns floating-point or exact symbolic results.

Compute the inverse tangent function for these numbers. Because these numbers are not
symbolic objects, atan returns floating-point results.

A = atan([-1, -1/3, -1/sqrt(3), 1/2, 1, sqrt(3)])

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 = atan(sym([-1, -1/3, -1/sqrt(3), 1/2, 1, sqrt(3)]))

symA =
[ -pi/4, -atan(1/3), -pi/6, atan(1/2), pi/4, pi/3]

Use vpa to approximate symbolic results with floating-point numbers:

4-96
atan

vpa(symA)

ans =
[ -0.78539816339744830961566084581988,...
-0.32175055439664219340140461435866,...
-0.52359877559829887307710723054658,...
0.46364760900080611621425623146121,...
0.78539816339744830961566084581988,...
1.0471975511965977461542144610932]

Plot Inverse Tangent Function


Plot the inverse tangent function on the interval from -10 to 10.

syms x
fplot(atan(x), [-10, 10])
grid on

4-97
4 Functions Alphabetical List

Handle Expressions Containing Inverse Tangent Function


Many functions, such as diff, int, taylor, and rewrite, can handle expressions
containing atan.

Find the first and second derivatives of the inverse tangent function:

syms 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

Find the indefinite integral of the inverse tangent function:


int(atan(x), x)

ans =
x*atan(x) - log(x^2 + 1)/2

Find the Taylor series expansion of atan(x):

taylor(atan(x), x)

ans =
x^5/5 - x^3/3 + x

Rewrite the inverse tangent function in terms of the natural logarithm:


rewrite(atan(x), 'log')

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

Input, specified as a symbolic number, variable, expression, or function, or as a vector or


matrix of symbolic numbers, variables, expressions, or functions.

See Also
acos | acot | acsc | asec | asin | atan2 | cos | cot | csc | sec | sin | tan

Introduced before R2006a

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.

[atan2(1, 1), atan2(pi, 4), atan2(Inf, Inf)]

4-100
atan2

ans =
0.7854 0.6658 0.7854

Compute the arctangents of these parameters which are converted to symbolic objects:

[atan2(sym(1), 1), atan2(sym(pi), sym(4)), atan2(Inf, sym(Inf))]

ans =
[ pi/4, atan(pi/4), pi/4]

Compute the limits of this symbolic expression:

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

Compute the arctangents of the elements of matrices Y and X:

Y = sym([3 sqrt(3); 1 1]);


X = sym([sqrt(3) 3; 1 0]);
atan2(Y, X)

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.

If X = 0 and Y < 0, then atan2(Y,X) returns -pi/2.

If X = Y = 0, then atan2(Y,X) returns 0.

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

Inverse Hyperbolic Tangent Function for Numeric and Symbolic


Arguments
Depending on its arguments, atanh returns floating-point or exact symbolic results.

Compute the inverse hyperbolic tangent function for these numbers. Because these
numbers are not symbolic objects, atanh returns floating-point results.

A = atanh([-i, 0, 1/6, i/2, i, 2])

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 = atanh(sym([-i, 0, 1/6, i/2, i, 2]))

symA =
[ -(pi*1i)/4, 0, atanh(1/6), atanh(1i/2), (pi*1i)/4, atanh(2)]

4-103
4 Functions Alphabetical List

Use vpa to approximate symbolic results with floating-point numbers:

vpa(symA)

ans =
[ -0.78539816339744830961566084581988i,...
0,...
0.1682361183106064652522967051085,...
0.46364760900080611621425623146121i,...
0.78539816339744830961566084581988i,...
0.54930614433405484569762261846126 - 1.5707963267948966192313216916398i]

Plot Inverse Hyperbolic Tangent Function


Plot the inverse hyperbolic tangent function on the interval from -1 to 1.

syms x
fplot(atanh(x), [-1, 1])
grid on

4-104
atanh

Handle Expressions Containing Inverse Hyperbolic Tangent Function


Many functions, such as diff, int, taylor, and rewrite, can handle expressions
containing atanh.

Find the first and second derivatives of the inverse hyperbolic tangent function:

syms x
diff(atanh(x), x)
diff(atanh(x), x, x)

ans =
-1/(x^2 - 1)

4-105
4 Functions Alphabetical List

ans =
(2*x)/(x^2 - 1)^2

Find the indefinite integral of the inverse hyperbolic tangent function:


int(atanh(x), x)

ans =
log(x^2 - 1)/2 + x*atanh(x)

Find the Taylor series expansion of 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

Input, specified as a symbolic number, variable, expression, or function, or as a vector or


matrix of symbolic numbers, variables, expressions, or functions.

See Also
acosh | acoth | acsch | asech | asinh | cosh | coth | csch | sech | sinh | tanh

Introduced before R2006a

4-106
bernoulli

bernoulli
Bernoulli numbers and polynomials

Syntax
bernoulli(n)
bernoulli(n,x)

Description
bernoulli(n) returns the nth Bernoulli number.

bernoulli(n,x) returns the nth Bernoulli polynomial.

Examples

Bernoulli Numbers with Odd and Even Indices


The 0th Bernoulli number is 1. The next Bernoulli number can be -1/2 or 1/2,
depending on the definition. The bernoulli function uses -1/2. The Bernoulli numbers
with even indices n > 1 alternate the signs. Any Bernoulli number with an odd index n
> 2 is 0.

Compute the even-indexed Bernoulli numbers with the indices from 0 to 10. Because
these indices are not symbolic objects, bernoulli returns floating-point results.

bernoulli(0:2:10)

ans =
1.0000 0.1667 -0.0333 0.0238 -0.0333 0.0758

Compute the same Bernoulli numbers for the indices converted to symbolic objects:
bernoulli(sym(0:2:10))

ans =

4-107
4 Functions Alphabetical List

[ 1, 1/6, -1/30, 1/42, -1/30, 5/66]

Compute the odd-indexed Bernoulli numbers with the indices from 1 to 11:
bernoulli(sym(1:2:11))

ans =
[ -1/2, 0, 0, 0, 0, 0]

Bernoulli Polynomials
For the Bernoulli polynomials, use bernoulli with two input arguments.

Compute the first, second, and third Bernoulli polynomials in variables x, y, and z,
respectively:
syms x y z
bernoulli(1, x)
bernoulli(2, y)
bernoulli(3, z)

ans =
x - 1/2

ans =
y^2 - y + 1/6

ans =
z^3 - (3*z^2)/2 + z/2

If the second argument is a number, bernoulli evaluates the polynomial at that


number. Here, the result is a floating-point number because the input arguments are not
symbolic numbers:
bernoulli(2, 1/3)

ans =
-0.0556

To get the exact symbolic result, convert at least one of the numbers to a symbolic object:
bernoulli(2, sym(1/3))

ans =
-1/18

4-108
bernoulli

Plot Bernoulli Polynomials


Plot the first six Bernoulli polynomials.

syms x
fplot(bernoulli(0:5, x), [-0.8 1.8])
title('Bernoulli Polynomials')
grid on

Handle Expressions Containing Bernoulli Polynomials


Many functions, such as diff and expand, handles expressions containing bernoulli.

4-109
4 Functions Alphabetical List

Find the first and second derivatives of the Bernoulli polynomial:


syms n x
diff(bernoulli(n,x^2), x)

ans =
2*n*x*bernoulli(n - 1, x^2)

diff(bernoulli(n,x^2), x, x)

ans =
2*n*bernoulli(n - 1, x^2) +...
4*n*x^2*bernoulli(n - 2, x^2)*(n - 1)

Expand these expressions containing the Bernoulli polynomials:


expand(bernoulli(n, x + 3))

ans =
bernoulli(n, x) + (n*(x + 1)^n)/(x + 1) +...
(n*(x + 2)^n)/(x + 2) + (n*x^n)/x

expand(bernoulli(n, 3*x))

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

Index of the Bernoulli number or polynomial, specified as a nonnegative integer,


symbolic nonnegative integer, variable, expression, function, vector, or matrix. If n
is a vector or matrix, bernoulli returns Bernoulli numbers or polynomials for each
element of n. If one input argument is a scalar and the other one is a vector or a matrix,
bernoulli(n,x) expands the scalar into a vector or matrix of the same size as the other
argument with all elements equal to that scalar.

x Polynomial variable
symbolic variable | symbolic expression | symbolic function | symbolic vector | symbolic
matrix

4-110
bernoulli

Polynomial variable, specified as a symbolic variable, expression, function, vector, or


matrix. If x is a vector or matrix, bernoulli returns Bernoulli numbers or polynomials
for each element of x. When you use the bernoulli function to find Bernoulli
polynomials, at least one 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, bernoulli(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.

More About
Bernoulli Polynomials

The Bernoulli polynomials are defined as follows:


te xt tn
et - 1
= bernoulli (n, x) n !
n =0

Bernoulli Numbers

The Bernoulli numbers are defined as follows:

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].

bernstein(g,n,t) with a symbolic expression or function g returns the nth-order


Bernstein polynomial, evaluated at the point t. This syntax regards g as a univariate
function of the variable determined by symvar(g,1).

If any argument is symbolic, bernstein converts all arguments except a function handle
to symbolic, and converts a function handles results to symbolic.

bernstein(g,var,n,t) with a symbolic expression or function g returns the


approximating nth-order Bernstein polynomial, regarding g as a univariate function of
the variable var.

Examples

Approximation of Sine Function Specified as Function Handle


Approximate the sine function by the 10th- and 100th-degree Bernstein polynomials:

syms t

4-112
bernstein

b10 = bernstein(@(t) sin(2*pi*t), 10, t);


b100 = bernstein(@(t) sin(2*pi*t), 100, t);

Plot sin(2*pi*t) and its approximations:

fplot(sin(2*pi*t),[0,1])
hold on
fplot(b10,[0,1])
fplot(b100,[0,1])

legend('sine function','10th-degree polynomial',...


'100th-degree polynomial')
title('Bernstein polynomials')
hold off

4-113
4 Functions Alphabetical List

Approximation of Exponential Function Specified as Symbolic Expression


Approximate the exponential function by the second-order Bernstein polynomial in the
variable t:

syms x t
bernstein(exp(x), 2, t)

ans =
(t - 1)^2 + t^2*exp(1) - 2*t*exp(1/2)*(t - 1)

Approximate the multivariate exponential function. When you approximate a


multivariate function, bernstein regards it as a univariate function of the default
variable determined by symvar. The default variable for the expression y*exp(x*y) is
x:

syms x y t
symvar(y*exp(x*y), 1)

ans =
x

bernstein treats this expression as a univariate function of 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)

To treat y*exp(x*y) as a function of the variable y, specify the variable explicitly:

bernstein(y*exp(x*y), y, 2, t)

ans =
t^2*exp(x) - t*exp(x/2)*(t - 1)

Approximation of Linear Ramp Specified as Symbolic Function


Approximate function f representing a linear ramp by the fifth-order Bernstein
polynomials in the variable t:

syms f(t)

4-114
bernstein

f(t) = triangularPulse(1/4, 3/4, Inf, t);


p = bernstein(f, 5, t)

p =
7*t^3*(t - 1)^2 - 3*t^2*(t - 1)^3 - 5*t^4*(t - 1) + t^5

Simplify the result:

simplify(p)

ans =
-t^2*(2*t - 3)

Numerical Stability of Simplified Bernstein Polynomials


When you simplify a high-order symbolic Bernstein polynomial, the result often cannot
be evaluated in a numerically stable way.

Approximate this rectangular pulse function by the 100th-degree Bernstein polynomial,


and then simplify the result:

f = @(x)rectangularPulse(1/4,3/4,x);
b1 = bernstein(f, 100, sym('t'));
b2 = simplify(b1);

Convert the polynomial b1 and the simplified polynomial b2 to MATLAB functions:

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

Function to be approximated by a polynomial, specified as a function handle. f must


accept one scalar input argument and return a scalar value.

g Function to be approximated by a polynomial


symbolic expression | symbolic function

4-116
bernstein

Function to be approximated by a polynomial, specified as a symbolic expression or


function.

n Bernstein polynomial order


nonnegative integer

Bernstein polynomial order, specified as a nonnegative number.

t Evaluation point
number | symbolic number | symbolic variable | symbolic expression | symbolic
function

Evaluation point, specified as a number, symbolic number, variable, expression, or


function. If t is a symbolic function, the evaluation point is the mathematical expression
that defines t. To extract the mathematical expression defining t, bernstein uses
formula(t).

var Free variable


symbolic variable

Free variable, specified as a symbolic variable.

More About
Bernstein Polynomials

A Bernstein polynomial is a linear combination of Bernstein basis polynomials.

A Bernstein polynomial of degree n is defined as follows:

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

The coefficients b k are called Bernstein coefficients or Bezier coefficients.

If f is a continuous function on the interval [0, 1] and

n
k
Bn ( f ) ( t ) = f n bk,n ( t)
k =0

is the approximating Bernstein polynomial, then

lim Bn ( f )( t ) = f ( t )
n

uniformly in t on the interval [0, 1].

Tips

Symbolic polynomials returned for symbolic t are numerically stable when


substituting numerical values between 0 and 1 for t.
If you simplify a symbolic Bernstein polynomial, the result can be unstable when
substituting numerical values for the curve parameter t.

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.

The Bernstein matrix is also called the Bezier matrix.

Use Bernstein matrices to construct Bezier curves:

bezierCurve = bernsteinMatrix(n, t)*P


Here, the n+1 rows of the matrix P specify the control points of the Bezier curve. For
example, to construct the second-order 3-D Bezier curve, specify the control points as:

P = [p0x, p0y, p0z; p1x, p1y, p1z; p2x, p2y, p2z]

Examples

2-D Bezier Curve


Plot the fourth-order Bezier curve specified by the control points p0 = [0 1], p1
= [4 3], p2 = [6 2], p3 = [3 0], p4 = [2 4]. Create a matrix with each row
representing a control point:

P = [0 1; 4 3; 6 2; 3 0; 2 4];

Compute the fourth-order Bernstein matrix B:

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]

Construct the Bezier curve:

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]

Plot the curve adding the control points to the plot:

fplot(bezierCurve(1), bezierCurve(2), [0, 1])


hold on
scatter(P(:,1), P(:,2),'filled')
title('Fourth-order Bezier curve')
hold off

4-120
bernsteinMatrix

3-D Bezier Curve


Construct the third-order Bezier curve specified by the 4-by-3 matrix P of control points.
Each control point corresponds to a row of the matrix P.

P = [0 0 0; 2 2 2; 2 -1 1; 6 1 3];

Compute the third-order Bernstein matrix:

syms t
B = bernsteinMatrix(3,t)

B =

4-121
4 Functions Alphabetical List

[ -(t - 1)^3, 3*t*(t - 1)^2, -3*t^2*(t - 1), t^3]

Construct the Bezier curve:


bezierCurve = simplify(B*P)

bezierCurve =
[ 6*t*(t^2 - t + 1), t*(10*t^2 - 15*t + 6), 3*t*(2*t^2 - 3*t + 2)]

Plot the curve adding the control points to the plot:


fplot3(bezierCurve(1), bezierCurve(2), bezierCurve(3), [0, 1])
hold on
scatter3(P(:,1), P(:,2), P(:,3),'filled')
hold off

4-122
bernsteinMatrix

3-D Bezier Curve with Evaluation Point Specified as Vector


Construct the third-order Bezier curve with the evaluation point specified by the
following 1-by-101 vector t:

t = 0:1/100:1;

Compute the third-order 101-by-4 Bernstein matrix and specify the control points:

B = bernsteinMatrix(3,t);
P = [0 0 0; 2 2 2; 2 -1 1; 6 1 3];

Construct and plot the Bezier curve. Add grid lines and control points to the plot.

bezierCurve = B*P;
plot3(bezierCurve(:,1), bezierCurve(:,2), bezierCurve(:,3))
hold on
grid
scatter3(P(:,1), P(:,2), P(:,3),'filled')
hold off

4-123
4 Functions Alphabetical List

Input Arguments
n Approximation order
nonnegative integer

Approximation order, specified as a nonnegative integer.

t Evaluation point
number | vector | symbolic number | symbolic variable | symbolic expression | symbolic
vector

4-124
bernsteinMatrix

Evaluation point, specified as a number, symbolic number, variable, expression, or


vector.

Output Arguments
B Bernstein matrix
matrix

Bernstein matrix, returned as a length(t)-by-n+1 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

Symbolic number, variable, expression, function, or a vector or matrix of symbolic


numbers, variables, expressions, or functions. If nu is a vector or matrix, besseli
returns the modified Bessel function of the first kind for each element of nu.

Symbolic number, variable, expression, or function, or a vector or matrix of symbolic


numbers, variables, expressions, or functions. If z is a vector or matrix, besseli returns
the modified Bessel function of the first kind for each element of z.

Examples
Find Modified Bessel Function of First Kind
Compute the modified Bessel functions of the first kind for these numbers. Because these
numbers are not symbolic objects, you get floating-point results.
[besseli(0, 5), besseli(-1, 2), besseli(1/3, 7/4), besseli(1, 3/2 + 2*i)]
ans =
27.2399 + 0.0000i 1.5906 + 0.0000i 1.7951 + 0.0000i -0.1523 + 1.0992i

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)]

Solve Bessel Differential Equation for Modified Bessel Functions


Solve this second-order differential equation. The solutions are the modified Bessel
functions of the first and the second kind.
syms nu w(z)
dsolve(z^2*diff(w, 2) + z*diff(w) -(z^2 + nu^2)*w == 0)

ans =
C2*besseli(nu, z) + C3*besselk(nu, z)

Verify that the modified Bessel function of the first kind is a valid solution of the
modified Bessel differential equation.
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

Special Values of Modified Bessel Function of First Kind


If the first parameter is an odd integer multiplied by 1/2, besseli rewrites the Bessel
functions in terms of elementary functions:

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))

Differentiate Modified Bessel Function of First Kind


Differentiate the expressions involving the modified Bessel functions of the first kind:

syms x y
diff(besseli(1, x))
diff(diff(besseli(0, x^2 + x*y -y^2), x), y)

ans =
besseli(0, x) - besseli(1, x)/x

ans =
besseli(1, x^2 + x*y - y^2) +...
(2*x + y)*(besseli(0, x^2 + x*y - y^2)*(x - 2*y) -...
(besseli(1, x^2 + x*y - y^2)*(x - 2*y))/(x^2 + x*y - y^2))

Bessel Function for Matrix Input


Call besseli for the matrix A and the value 1/2. The result is a matrix of the modified
Bessel functions besseli(1/2, A(i,j)).

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]

Plot the Modified Bessel Functions of the First Kind

Plot the modified Bessel functions of the first kind for .

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

The modified Bessel differential equation

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.

[2] Antosiewicz, H. A. Bessel Functions of Fractional 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

Symbolic number, variable, expression, function, or a vector or matrix of symbolic


numbers, variables, expressions, or functions. If nu is a vector or matrix, besseli
returns the Bessel function of the first kind for each element of nu.

Symbolic number, variable, expression, or function, or a vector or matrix of symbolic


numbers, variables, expressions, or functions. If z is a vector or matrix, besseli returns
the Bessel function of the first kind for each element of z.

Examples

Find Bessel Function of First Kind


Compute the Bessel functions of the first kind for these numbers. Because these numbers
are not symbolic objects, you get floating-point results.

4-132
besselj

[besselj(0, 5), besselj(-1, 2), besselj(1/3, 7/4),...


besselj(1, 3/2 + 2*i)]
ans =
-0.1776 + 0.0000i -0.5767 + 0.0000i 0.5496 + 0.0000i 1.6113 + 0.3982i

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.

[besselj(sym(0), 5), besselj(sym(-1), 2),...


besselj(1/3, sym(7/4)), besselj(sym(1), 3/2 + 2*i)]

ans =
[ besselj(0, 5), -besselj(1, 2), besselj(1/3, 7/4), besselj(1, 3/2 + 2i)]

For symbolic variables and expressions, besselj also returns unresolved symbolic calls:

syms x y
[besselj(x, y), besselj(1, x^2), besselj(2, x - y), besselj(x^2, x*y)]

ans =
[ besselj(x, y), besselj(1, x^2), besselj(2, x - y), besselj(x^2, x*y)]

Solve Bessel Differential Equation for Bessel Functions


Solve this second-order differential equation. The solutions are the Bessel functions of
the first and the second kind.

syms nu w(z)
dsolve(z^2*diff(w, 2) + z*diff(w) +(z^2 - nu^2)*w == 0)

ans =
C2*besselj(nu, z) + C3*bessely(nu, z)

Verify that the Bessel function of the 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

Special Values of Bessel Function of First Kind


If the first parameter is an odd integer multiplied by 1/2, besselj rewrites the Bessel
functions in terms of elementary functions:
syms x
besselj(1/2, x)

ans =
(2^(1/2)*sin(x))/(x^(1/2)*pi^(1/2))

besselj(-1/2, x)

ans =
(2^(1/2)*cos(x))/(x^(1/2)*pi^(1/2))

besselj(-3/2, x)

ans =
-(2^(1/2)*(sin(x) + cos(x)/x))/(x^(1/2)*pi^(1/2))

besselj(5/2, x)

ans =
-(2^(1/2)*((3*cos(x))/x - sin(x)*(3/x^2 - 1)))/(x^(1/2)*pi^(1/2))

Differentiate Bessel Function of First Kind


Differentiate the expressions involving the Bessel functions of the first kind:
syms x y
diff(besselj(1, x))
diff(diff(besselj(0, x^2 + x*y -y^2), x), y)

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))

Find Bessel Function for Matrix Input


Call besselj for the matrix A and the value 1/2. The result is a matrix of the Bessel
functions besselj(1/2, A(i,j)).

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]

Plot Bessel Functions of First Kind

Plot the Bessel functions of the first kind for .

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

The Bessel differential equation

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.

[2] Antosiewicz, H. A. Bessel Functions of Fractional 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

Symbolic number, variable, expression, function, or a vector or matrix of symbolic


numbers, variables, expressions, or functions. If nu is a vector or matrix, besseli
returns the modified Bessel function of the second kind for each element of nu.

Symbolic number, variable, expression, or function, or a vector or matrix of symbolic


numbers, variables, expressions, or functions. If z is a vector or matrix, besseli returns
the modified Bessel function of the second kind for each element of z.

Examples

Find Modified Bessel Function of Second Kind


Compute the modified Bessel functions of the second kind for these numbers. Because
these numbers are not symbolic objects, you get floating-point results.

4-138
besselk

[besselk(0, 5), besselk(-1, 2), besselk(1/3, 7/4),...


besselk(1, 3/2 + 2*i)]
ans =
0.0037 + 0.0000i 0.1399 + 0.0000i 0.1594 + 0.0000i -0.1620 - 0.1066i

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.

[besselk(sym(0), 5), besselk(sym(-1), 2),...


besselk(1/3, sym(7/4)), besselk(sym(1), 3/2 + 2*i)]

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)]

Special Values of Modified Bessel Function of Second Kind


If the first parameter is an odd integer multiplied by 1/2, besselk rewrites the Bessel
functions in terms of elementary functions:

syms x
besselk(1/2, x)

ans =
(2^(1/2)*pi^(1/2)*exp(-x))/(2*x^(1/2))

besselk(-1/2, x)

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))

Solve Bessel Differential Equation for Bessel Functions


Solve this second-order differential equation. The solutions are the modified Bessel
functions of the first and the second kind.

syms nu w(z)
dsolve(z^2*diff(w, 2) + z*diff(w) -(z^2 + nu^2)*w == 0)

ans =
C2*besseli(nu, z) + C3*besselk(nu, z)

Verify that the modified Bessel function of the second kind is a valid solution of the
modified Bessel differential equation:

syms nu z
isAlways(z^2*diff(besselk(nu, z), z, 2) + z*diff(besselk(nu, z), z)...
- (z^2 + nu^2)*besselk(nu, z) == 0)

ans =
logical
1

Differentiate Modified Bessel Function of Second Kind


Differentiate the expressions involving the modified Bessel functions of the second kind:

syms x y
diff(besselk(1, x))
diff(diff(besselk(0, x^2 + x*y -y^2), x), y)

ans =
- besselk(1, x)/x - besselk(0, x)

ans =
(2*x + y)*(besselk(0, x^2 + x*y - y^2)*(x - 2*y) +...
(besselk(1, x^2 + x*y - y^2)*(x - 2*y))/(x^2 + x*y - y^2)) -...
besselk(1, x^2 + x*y - y^2)

4-140
besselk

Find Bessel Function for Matrix Input


Call besselk for the matrix A and the value 1/2. The result is a matrix of the modified
Bessel functions besselk(1/2, A(i,j)).

syms x
A = [-1, pi; x, 0];
besselk(1/2, A)

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]

Plot Modified Bessel Functions of Second Kind

Plot the modified Bessel functions of the second kind for .

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

The modified Bessel differential equation

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.

[2] Antosiewicz, H. A. Bessel Functions of Fractional 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

Symbolic number, variable, expression, function, or a vector or matrix of symbolic


numbers, variables, expressions, or functions. If nu is a vector or matrix, bessely
returns the Bessel function of the second kind for each element of nu.

Symbolic number, variable, expression, or function, or a vector or matrix of symbolic


numbers, variables, expressions, or functions. If z is a vector or matrix, bessely returns
the Bessel function of the second kind for each element of z.

Examples
Find Bessel Function of Second Kind
Compute the Bessel functions of the second kind for these numbers. Because these
numbers are not symbolic objects, you get floating-point results.
[bessely(0, 5), bessely(-1, 2), bessely(1/3, 7/4), bessely(1, 3/2 + 2*i)]
ans =

4-145
4 Functions Alphabetical List

-0.3085 + 0.0000i 0.1070 + 0.0000i 0.2358 + 0.0000i -0.4706 + 1.5873i

Compute the Bessel functions of the second kind for the numbers converted to symbolic
objects. For most symbolic (exact) numbers, bessely returns unresolved symbolic calls.
[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)]

Solve Bessel Differential Equation for Bessel Functions


Solve this second-order differential equation. The solutions are the Bessel functions of
the first and the second kind.
syms nu w(z)
dsolve(z^2*diff(w, 2) + z*diff(w) +(z^2 - nu^2)*w == 0)

ans =
C2*besselj(nu, z) + C3*bessely(nu, z)

Verify that the Bessel function of the second kind is a valid solution of the Bessel
differential equation:
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

Special Values of Bessel Function of Second Kind


If the first parameter is an odd integer multiplied by 1/2, bessely rewrites the Bessel
functions in terms of elementary functions:

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))

Differentiate Bessel Functions of Second Kind


Differentiate the expressions involving the Bessel functions of the second kind:

syms x y
diff(bessely(1, x))
diff(diff(bessely(0, x^2 + x*y -y^2), x), y)

ans =
bessely(0, x) - bessely(1, x)/x

ans =
- bessely(1, x^2 + x*y - y^2) -...
(2*x + y)*(bessely(0, x^2 + x*y - y^2)*(x - 2*y) -...
(bessely(1, x^2 + x*y - y^2)*(x - 2*y))/(x^2 + x*y - y^2))

Find Bessel Function for Matrix Input


Call bessely for the matrix A and the value 1/2. The result is a matrix of the Bessel
functions bessely(1/2, A(i,j)).

syms x

4-147
4 Functions Alphabetical List

A = [-1, pi; x, 0];


bessely(1/2, A)

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]

Plot Bessel Functions of Second Kind

Plot the Bessel functions of the second kind for .

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

The Bessel differential equation

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:

J ( z ) cos (np ) - J-n ( z )


Yn ( z ) = n
sin (np )

Here J(z) are the Bessel function 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.

[2] Antosiewicz, H. A. Bessel Functions of Fractional 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

Symbolic number, variable, expression, function, or a vector or matrix of symbolic


numbers, variables, expressions, or functions. If x is a vector or matrix, beta returns the
beta function for each element of x.

Symbolic number, variable, expression, function, or a vector or matrix of symbolic


numbers, variables, expressions, or functions. If y is a vector or matrix, beta returns the
beta function for each element of y.

Examples
Compute the beta function for these numbers. Because these numbers are not symbolic
objects, you get floating-point results:

[beta(1, 5), beta(3, sqrt(2)), beta(pi, exp(1)), beta(0, 1)]

ans =
0.2000 0.1716 0.0379 Inf

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

Expand these beta functions:


syms x y
expand(beta(x, y))
expand(beta(x + 1, y - 1))

ans =
(gamma(x)*gamma(y))/gamma(x + y)

ans =
-(x*gamma(x)*gamma(y))/(gamma(x + y) - y*gamma(x + y))

More About
Beta Function

This integral defines the 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]

To concatenate A and B into a matrix, specify dimension dim as 1.


cat(1,A,B)

ans =
[ a1, a2, a3, a4]
[ b1, b2, b3, b4]

Alternatively, use the syntax [A;B].


[A;B]

4-156
cat

ans =
[ a1, a2, a3, a4]
[ b1, b2, b3, b4]

Concatenate Two Vectors into One Vector


To concatenate two vectors into one vector, specify dimension dim as 2.
A = sym('a%d',[1 4]);
B = sym('b%d',[1 4]);
cat(2,A,B)

ans =
[ a1, a2, a3, a4, b1, b2, b3, b4]

Alternatively, use the syntax [A B].


[A B]

ans =
[ a1, a2, a3, a4, b1, b2, b3, b4]

Concatenate Multidimensional Arrays Along Their Third Dimension


Create arrays A and B.
A = sym('a%d%d',[2 2]);
A(:,:,2) = -A
B = sym('b%d%d', [2 2]);
B(:,:,2) = -B

A(:,:,1) =
[ a11, a12]
[ a21, a22]
A(:,:,2) =
[ -a11, -a12]
[ -a21, -a22]

B(:,:,1) =
[ b11, b12]
[ b21, b22]
B(:,:,2) =
[ -b11, -b12]
[ -b21, -b22]

4-157
4 Functions Alphabetical List

Concatenate A and B by specifying dimension dim as 3.

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

Dimension to concatenate arrays along, specified as a positive integer.

A1,...,AN Input arrays


symbolic variables | symbolic vectors | symbolic matrices | symbolic multidimensional
arrays

Input arrays, specified as symbolic variables, vectors, matrices, or multidimensional


arrays.

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

Set the number of digits to 10 and approximate the Catalan constant:


old = digits(10);
vpa(catalan)

ans =
0.9159655942

Restore the default number of digits:


digits(old)

4-159
4 Functions Alphabetical List

More About
Catalan Constant

The Catalan constant is defined as follows:

( - 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.

ccode(s,'file',fileName) writes an optimized C code fragment that evaluates


the symbolic expression s to the file named fileName. Optimized means intermediate
variables are automatically generated in order to simplify the code. MATLAB generates
intermediate variables as a lowercase letter t followed by an automatically generated
number, for example t32.

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')

return a file named ccodetest containing the following:

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

Introduced before R2006a

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

Introduced before R2006a

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.

S = cell2sym(C,flag) uses the technique specified by flag for converting floating-


point numbers to symbolic numbers.

Examples
Convert Cell Array of Scalars
Convert a cell array of only scalar elements to a symbolic array.

4-164
cell2sym

Create a cell array of scalar elements.

C = {'x','y','z'; 1 2 3}

C =
23 cell array
'x' 'y' 'z'
[1] [2] [3]

Convert this cell array to a symbolic array.

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

Convert Cell Array Containing Nonscalar Elements


Convert a cell array whose elements are scalars, vectors, and matrices into a symbolic
array. Such conversion is possible only if the contents of the cell array can be
concatenated into an N-dimensional rectangle.

Create a cell array, the elements of which are a scalar, a row vector, a column vector, and
a matrix.

C = {'x' [2 3 4]; ['y'; sym(9)] [6 7 8; 10 11 12]}

C =
22 cell array
'x' [13 double]
[21 sym] [23 double]

Convert this cell array to a symbolic array.

S = cell2sym(C)

4-165
4 Functions Alphabetical List

S =
[ x, 2, 3, 4]
[ y, 6, 7, 8]
[ 9, 10, 11, 12]

Choose Conversion Technique for Floating-Point Values


When converting a cell array containing floating-point numbers, you can explicitly
specify the conversion technique.

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.

flag Conversion technique


'r' (default) | 'd' | 'e' | 'f'

Conversion technique, specified as one of the characters listed in this table.

'r' In the rational mode, cell2sym converts floating-point numbers obtained by


evaluating expressions of the form p/q, p*pi/q, sqrt(p), 2^q, and 10^q
for modest sized integers p and q to the corresponding symbolic form. This
approach effectively compensates for the round-off error involved in the
original evaluation, but might not represent the floating-point value precisely.
If cell2sym cannot find simple rational approximation, then it uses the same
technique as it would use with the flag 'f'.
'd' In the decimal mode, cell2sym takes the number of digits from the
current setting of digits. Conversions with fewer than 16 digits lose some
accuracy, while more than 16 digits might not be warranted. For example,
cell2sym({4/3},'d') with the 10-digit accuracy returns 1.333333333,
while with the 20-digit accuracy it returns 1.3333333333333332593. The
latter does not end in 3s, but it is an accurate decimal representation of the
floating-point number nearest to 4/3.
'e' In the estimate error mode, cell2sym supplements a result obtained in the
rational mode by a term involving the variable eps. This term estimates the
difference between the theoretical rational expression and its actual floating-
point value. For example, cell2sym({3*pi/4},'e') returns (3*pi)/4 -
(103*eps)/249.

4-167
4 Functions Alphabetical List

'f' In the floating-point mode, cell2sym represents all values


in the form N*2^e or -N*2^e, where N >= 0 and e are
integers. For example, cell2sym({1/10},'f') returns
3602879701896397/36028797018963968. The returned rational value is
the exact value of the floating-point number that you convert to a symbolic
number.

Output Arguments
S Resulting symbolic array
symbolic array

Resulting symbolic array, returned as a 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

Symbolic scalar or symbolic array.

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.

Convert a symbolic matrix to a 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

char can change term ordering in an expression.

See Also
sym | double | pretty

Introduced before R2006a

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.

charpoly(A,var) returns the characteristic polynomial of A in terms of var.

Input Arguments
A

Matrix.

var

Free symbolic variable.

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 )

Here In is the n-by-n identity matrix.

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

First Five Chebyshev Polynomials of the First Kind


Find the first five Chebyshev polynomials of the first kind for the variable x.

syms x
chebyshevT([0, 1, 2, 3, 4], x)

ans =
[ 1, x, 2*x^2 - 1, 4*x^3 - 3*x, 8*x^4 - 8*x^2 + 1]

Chebyshev Polynomials for Numeric and Symbolic Arguments


Depending on its arguments, chebyshevT returns floating-point or exact symbolic
results.

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.

chebyshevT(5, [1/6, 1/4, 1/3, 1/2, 2/3, 3/4])

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.

chebyshevT(5, sym([1/6, 1/4, 1/3, 1/2, 2/3, 3/4]))

ans =
[ 361/486, 61/64, 241/243, 1/2, -118/243, -57/64]

Evaluate Chebyshev Polynomials with Floating-Point Numbers


Floating-point evaluation of Chebyshev polynomials by direct calls of chebyshevT is
numerically stable. However, first computing the polynomial using a symbolic variable,
and then substituting variable-precision values into this expression can be numerically
unstable.

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

Approximate the polynomial coefficients by using vpa, and then substitute x =


sym(1/3) into the result. This approach is also numerically unstable.

4-175
4 Functions Alphabetical List

subs(vpa(T500), x, sym(1/3))

ans =
1202292431349342132757038366720.0

Plot Chebyshev Polynomials of the First Kind


Plot the first five Chebyshev polynomials of the first kind.

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

Degree of the polynomial, specified as a nonnegative integer, symbolic variable,


expression, or function, or as a vector or matrix of numbers, symbolic numbers, variables,
expressions, or functions.

4-177
4 Functions Alphabetical List

x Evaluation point
number | symbolic number | symbolic variable | symbolic expression | symbolic
function | vector | matrix

Evaluation point, specified as a number, symbolic number, variable, expression, or


function, or as a vector or matrix of numbers, symbolic numbers, variables, expressions,
or functions.

More About
Chebyshev Polynomials of the First Kind

Chebyshev polynomials of the first kind are defined as Tn(x) = cos(n*arccos(x)).

These polynomials satisfy the recursion formula

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

and Gegenbauer polynomials

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

chebyshevT acts element-wise on nonscalar inputs.


At least one input argument must be a scalar or both arguments must be vectors or
matrices of the same size. If one input argument is a scalar and the other one is a
vector or a matrix, then chebyshevT expands the scalar into a vector or matrix of the
same size as the other argument with all elements equal to that scalar.

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

First Five Chebyshev Polynomials of the Second Kind


Find the first five Chebyshev polynomials of the second kind for the variable x.

syms x
chebyshevU([0, 1, 2, 3, 4], x)

ans =
[ 1, 2*x, 4*x^2 - 1, 8*x^3 - 4*x, 16*x^4 - 12*x^2 + 1]

Chebyshev Polynomials for Numeric and Symbolic Arguments


Depending on its arguments, chebyshevU returns floating-point or exact symbolic
results.

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.

chebyshevU(5, [1/6, 1/3, 1/2, 2/3, 4/5])

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.

chebyshevU(5, sym([1/6, 1/4, 1/3, 1/2, 2/3, 4/5]))

ans =
[ 208/243, 33/32, 230/243, 0, -308/243, -3432/3125]

Evaluate Chebyshev Polynomials with Floating-Point Numbers


Floating-point evaluation of Chebyshev polynomials by direct calls of chebyshevU is
numerically stable. However, first computing the polynomial using a symbolic variable,
and then substituting variable-precision values into this expression can be numerically
unstable.

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

Approximate the polynomial coefficients by using vpa, and then substitute x =


sym(1/3) into the result. This approach is also numerically unstable.

4-181
4 Functions Alphabetical List

subs(vpa(U500), x, sym(1/3))

ans =
-1878009301399851172833781612544.0

Plot Chebyshev Polynomials of the Second Kind


Plot the first five Chebyshev polynomials of the second kind.

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

Degree of the polynomial, specified as a nonnegative integer, symbolic variable,


expression, or function, or as a vector or matrix of numbers, symbolic numbers, variables,
expressions, or functions.

4-183
4 Functions Alphabetical List

x Evaluation point
number | symbolic number | symbolic variable | symbolic expression | symbolic
function | vector | matrix

Evaluation point, specified as a number, symbolic number, variable, expression, or


function, or as a vector or matrix of numbers, symbolic numbers, variables, expressions,
or functions.

More About
Chebyshev Polynomials of the Second Kind

Chebyshev polynomials of the second kind are defined as follows:

sin ( ( n + 1 ) a cos ( x ) )
U ( n, x) =
sin ( a cos ( x) )

These polynomials satisfy the recursion formula

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

and Gegenbauer polynomials

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(expr) returns a vector containing the child subexpressions of the symbolic


expression expr. For example, the child subexpressions of a sum are its terms.

children(A) returns a cell array containing the child subexpressions of each expression
in A.

Input Arguments
expr

Symbolic expression, equation, or inequality.

Vector or matrix of symbolic expressions, equations, or inequalities.

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.

children(x^2 - x*y - y^2)

ans =
[ -x*y, x^2, -y^2]

The child subexpression of a variable is the variable itself:

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]

Find the child subexpressions of this inequality. The child subexpressions of an


inequality are the left and right sides of that inequality.

children(sin(x) < cos(x))

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

To access the contents of cells in the cell array, use braces:


s{1:4}

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).

[T,p,S] = chol(A) returns a permutation matrix S, such that T'*T = S'*A*S,


and the value p = 0 if matrix A is Hermitian positive definite. Otherwise, it returns a
positive integer p and an empty object