0% found this document useful (0 votes)
2K views2,350 pages

MATLAB 2023b Symbolic Math Toolbox

Uploaded by

do.dinh.khai
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)
2K views2,350 pages

MATLAB 2023b Symbolic Math Toolbox

Uploaded by

do.dinh.khai
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/ 2350

Symbolic Math Toolbox™

User's Guide

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


1 Apple Hill Drive
Natick, MA 01760-2098
Symbolic Math Toolbox™ User's Guide
© COPYRIGHT 1993–2023 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)
March 2017 Online only Revised for Version 7.2 (Release 2017a)
September 2017 Online only Revised for Version 8.0 (Release 2017b)
March 2018 Online only Revised for Version 8.1 (Release 2018a)
September 2018 Online only Revised for Version 8.2 (Release 2018b)
March 2019 Online only Revised for Version 8.3 (Release 2019a)
September 2019 Online only Revised for Version 8.4 (Release 2019b)
March 2020 Online only Revised for Version 8.5 (Release 2020a)
September 2020 Online only Revised for Version 8.6 (Release 2020b)
March 2021 Online only Revised for Version 8.7 (Release 2021a)
September 2021 Online only Revised for Version 9.0 (Release 2021b)
March 2022 Online only Revised for Version 9.1 (Release 2022a)
September 2022 Online only Revised for Version 9.2 (Release 2022b)
March 2023 Online only Revised for Version 9.3 (Release 2023a)
September 2023 Online only Revised for Version 23.2 (R2023b)
Contents

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

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

Create Symbolic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9

Create Symbolic Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11


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

Create Symbolic Matrix Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-13

Use Symbolic Objects to Represent Mathematical Objects . . . . . . . . . . . 1-20


Symbolic Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-20
Symbolic Scalar Variable, Function, and Expression . . . . . . . . . . . . . . . . 1-21
Symbolic Equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-21
Symbolic Vector and Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-22
Symbolic Matrix Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-23
Symbolic Matrix Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-24
Comparison of Symbolic Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-25

Perform Symbolic Computations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-28


Differentiate Symbolic Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-28
Integrate Symbolic Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-29
Solve Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-30
Simplify Symbolic Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-32
Substitutions in Symbolic Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . 1-33
Plot Symbolic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-35

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

Computational Mathematics in Symbolic Math Toolbox . . . . . . . . . . . . . 1-44

Next Step Suggestions for Symbolic Workflows in Live Editor . . . . . . . . 1-57

v
Symbolic Computations in MATLAB
2
Find Symbolic Variables in Expressions, Functions, and Matrices . . . . . . 2-2
Find a Default Symbolic Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2

Choose syms or sym Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4

Change Output Format of Symbolic and Variable-Precision Arithmetic


.......................................................... 2-8

Change Output Display Format of Symbolic Results in the Live Editor . 2-11

Add Subscripts, Superscripts, and Accents to Symbolic Variables in the


Live Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14

Copy and Paste Symbolic Output in Live Editor . . . . . . . . . . . . . . . . . . . . 2-18

Check Symbolic Equations, Inequalities, and Conditional Statements . 2-23

Numeric to Symbolic Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-29

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


Double-Precision Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-32
Variable-Precision Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-32
Symbolic Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-33
Comparisons of Numeric and Symbolic Arithmetic . . . . . . . . . . . . . . . . . 2-34

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

Compute Binomial Coefficients Exactly . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-38

Find Almost Integers with High-Precision Arithmetic . . . . . . . . . . . . . . . 2-41

Decimal Digits of PI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-45

Units of Measurement Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-47

Unit Conversions and Unit Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-53


Convert Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-53
Temperature Unit Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-54
Convert to SI, CGS, or US Unit Systems . . . . . . . . . . . . . . . . . . . . . . . . . 2-54
Define Custom Unit System from Existing System . . . . . . . . . . . . . . . . . . 2-56
Define Custom Unit System Directly . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-57
Unit System Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-58

Units and Unit Systems List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-60


Units List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-60
SI Unit Prefixes List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-70
Unit Systems List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-71
Defining Constants of SI Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-72

Units in Physics Calculations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-74

vi Contents
The Physics of the Damped Harmonic Oscillator . . . . . . . . . . . . . . . . . . . 2-78

Evaluating the Average Power Delivered by a Wind Turbine . . . . . . . . . . 2-88

Developing an Algorithm for Undistorting an Image . . . . . . . . . . . . . . . . 2-93

Electric Dipole Moment and Radiation Power . . . . . . . . . . . . . . . . . . . . . 2-99

Validate Simulink Model Using Symbolic Math Toolbox . . . . . . . . . . . . 2-102

Mathematics
3
Solve Algebraic Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Solve an Equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Return the Full Solution to an Equation . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Work with the Full Solution, Parameters, and Conditions Returned by solve
...................................................... 3-4
Visualize and Plot Solutions Returned by solve . . . . . . . . . . . . . . . . . . . . . 3-5
Simplify Complicated Results and Improve Performance . . . . . . . . . . . . . . 3-6

Solve System of Algebraic Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-7

Troubleshoot Equation Solutions from solve Function . . . . . . . . . . . . . . 3-17


Return Only Real Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-17
Apply Simplification Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-17
Use Assumptions to Narrow Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-18
Simplify Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-19
Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-19

Solve Equations Numerically . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-21

Solve System of Linear Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-30


Solve System of Linear Equations Using linsolve . . . . . . . . . . . . . . . . . . . 3-30
Solve System of Linear Equations Using solve . . . . . . . . . . . . . . . . . . . . 3-31

Select Numeric or Symbolic Solver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-33

Solve Parametric Equations in ReturnConditions Mode . . . . . . . . . . . . . 3-34

Solve Algebraic Equation Using Live Editor Task . . . . . . . . . . . . . . . . . . . 3-36

Solve Differential Equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-43


First-Order Linear ODE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-43
Solve Differential Equation with Condition . . . . . . . . . . . . . . . . . . . . . . . 3-43
Nonlinear Differential Equation with Initial Condition . . . . . . . . . . . . . . . 3-44
Second-Order ODE with Initial Conditions . . . . . . . . . . . . . . . . . . . . . . . 3-44
Third-Order ODE with Initial Conditions . . . . . . . . . . . . . . . . . . . . . . . . . 3-44
More ODE Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-45

Solve a System of Differential Equations . . . . . . . . . . . . . . . . . . . . . . . . . . 3-47

vii
Solve a Second-Order Differential Equation Numerically . . . . . . . . . . . . 3-52

Solve Partial Differential Equation of Tsunami Model . . . . . . . . . . . . . . . 3-54

Solve Differential Algebraic Equations (DAEs) . . . . . . . . . . . . . . . . . . . . . 3-61

Solve Semilinear DAE System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-70

Solve DAEs Using Mass Matrix Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-77


Step 1. Convert DAEs to Function Handles . . . . . . . . . . . . . . . . . . . . . . . 3-77
Step 2. Find Initial Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-78
Step 3. Solve DAE System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-79

Analyze and Manipulate Differential Algebraic Equations . . . . . . . . . . . 3-82

Derive and Apply Inverse Kinematics to Two-Link Robot Arm . . . . . . . . 3-89

Gauss-Laguerre Quadrature Evaluation Points and Weights . . . . . . . . . . 3-96

Simulate a Stochastic Process Using the Feynman–Kac Formula . . . . . 3-106

The Black–Scholes Formula for Call Option Price . . . . . . . . . . . . . . . . . 3-114

Choose Function to Rearrange Expression . . . . . . . . . . . . . . . . . . . . . . . 3-119


Combine Terms of Same Algebraic Structures . . . . . . . . . . . . . . . . . . . 3-119
Expand Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-120
Factor Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-121
Extract Subexpressions from Expression . . . . . . . . . . . . . . . . . . . . . . . 3-123
Collect Terms with Same Powers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-123
Rewrite Expressions in Terms of Other Functions . . . . . . . . . . . . . . . . . 3-124
Compute Partial Fraction Decompositions of Expressions . . . . . . . . . . . 3-125
Compute Normal Forms of Rational Expressions . . . . . . . . . . . . . . . . . . 3-125
Represent Polynomials Using Horner Nested Forms . . . . . . . . . . . . . . . 3-126

Extract Numerators and Denominators of Rational Expressions . . . . . 3-127

Simplify Symbolic Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-129


Simplify Using Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-130
Simplify Using Assumptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-132
Simplify Fractions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-132

Simplify Symbolic Expressions Using Live Editor Task . . . . . . . . . . . . . 3-134

Substitute Variables in Symbolic Expressions . . . . . . . . . . . . . . . . . . . . 3-140

Substitute Elements in Symbolic Matrices . . . . . . . . . . . . . . . . . . . . . . . 3-142

Substitute Scalars with Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-144

Evaluate Symbolic Expressions Using subs . . . . . . . . . . . . . . . . . . . . . . . 3-146

Abbreviate Common Terms in Long Expressions . . . . . . . . . . . . . . . . . . 3-147

Harmonic Analysis of Transfer Function Output . . . . . . . . . . . . . . . . . . 3-150

viii Contents
Explore Single-Period Asset Arbitrage . . . . . . . . . . . . . . . . . . . . . . . . . . 3-156

Analytical Solutions of the Inverse Kinematics of a Humanoid Robot 3-160

Differentiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-171
Derivatives of Expressions with Several Variables . . . . . . . . . . . . . . . . . 3-172
More Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-173

Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-176
Integration with Real Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-178
Integration with Complex Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . 3-179
High-Precision Numerical Integration Using Variable-Precision Arithmetic
.................................................... 3-180

Taylor Series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-182

Fourier and Inverse Fourier Transforms . . . . . . . . . . . . . . . . . . . . . . . . . 3-184


Fourier Transform Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-184
Concept: Using Symbolic Workflows . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-184
Calculate Beam Deflection Using Fourier Transform . . . . . . . . . . . . . . . 3-184

Solve Differential Equations of RLC Circuit Using Laplace Transform 3-188

Solve Difference Equations Using Z-Transform . . . . . . . . . . . . . . . . . . . . 3-195

Symbolic Summation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-200


Comparing symsum and sum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-200
Computational Speed of symsum versus sum . . . . . . . . . . . . . . . . . . . . 3-200
Output Format Differences Between symsum and sum . . . . . . . . . . . . . 3-201

Padé Approximant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-202

Limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-209
One-Sided Limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-209

Find Asymptotes, Critical, and Inflection Points . . . . . . . . . . . . . . . . . . 3-212

Functional Derivatives Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-217

Learn Calculus in the Live Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-222

Differentiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-227

Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-235

Interactive Calculus in Live Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-239

Maxima, Minima, and Inflection Points . . . . . . . . . . . . . . . . . . . . . . . . . . 3-241

Find Extremum of Multivariate Function and Its Approximation . . . . . 3-250

Padé Approximant of Time-Delay Input . . . . . . . . . . . . . . . . . . . . . . . . . . 3-254

Solve Partial Differential Equation of Nonlinear Heat Transfer . . . . . . 3-260

ix
Symbolic Matrix Computation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-267

Linear Algebraic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-274


Symbolic Hilbert Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-274
Symbolic Linear Algebra Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-274
Variable-Precision Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-275
Symbolic Investigation of Singular Value . . . . . . . . . . . . . . . . . . . . . . . 3-276

Basic Algebraic Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-278

Singular Value Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-280

Eigenvalues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-282

Jordan Canonical Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-286

Eigenvalues of the Laplace Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-288

Hilbert Matrices and Their Inverses . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-298

Markov Chain Analysis and Stationary Distribution . . . . . . . . . . . . . . . 3-302

Matrix Rotations and Transformations . . . . . . . . . . . . . . . . . . . . . . . . . . 3-307

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


Check Assumptions Set on Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-315
Effects of Assumptions on Computations . . . . . . . . . . . . . . . . . . . . . . . . 3-316

Recognize and Avoid Round-Off Errors . . . . . . . . . . . . . . . . . . . . . . . . . . 3-317


Use Symbolic Computations When Possible . . . . . . . . . . . . . . . . . . . . . 3-317
Perform Calculations with Increased Precision . . . . . . . . . . . . . . . . . . . 3-317
Compare Symbolic and Numeric Results . . . . . . . . . . . . . . . . . . . . . . . . 3-319
Plot the Function or Expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-319

Increase Speed by Reducing Precision . . . . . . . . . . . . . . . . . . . . . . . . . . 3-321

Prime Factorizations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-323

Handling Large Integers to Solve the 196 Problem . . . . . . . . . . . . . . . . 3-326

Graphics
4
Create Plots of Symbolic Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2

Transform Spherical Coordinates to Cartesian Coordinates and Plot


Analytically . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-10

Tangent Plane and Normal Line of Implicit Surface . . . . . . . . . . . . . . . . 4-17

Analytical Plotting with Symbolic Math Toolbox . . . . . . . . . . . . . . . . . . . 4-21

x Contents
Simulate the Motion of the Periodic Swing of a Pendulum . . . . . . . . . . . 4-38

Animation and Solution of Double Pendulum Motion . . . . . . . . . . . . . . . 4-53

Animation and Model of Automotive Piston . . . . . . . . . . . . . . . . . . . . . . . 4-60

Code Generation
5
Generate C or Fortran Code from Symbolic Expressions . . . . . . . . . . . . . . 5-2

Generate MATLAB Functions from Symbolic Expressions . . . . . . . . . . . . . 5-3


Generating a Function Handle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3
Control the Order of Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3
Generate a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4
Name Output Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5

Generate MATLAB Function Blocks from Symbolic Expressions . . . . . . . 5-6


Generate and Edit a Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-6
Control the Order of Input Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-6
Name the Output Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7

Generate Simscape Equations from Symbolic Expressions . . . . . . . . . . . . 5-8


Convert Algebraic and Differential Equations . . . . . . . . . . . . . . . . . . . . . . 5-8
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9

Deploy Generated MATLAB Functions from Symbolic Expressions with


MATLAB Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10

Generate C Code from Symbolic Expressions Using the MATLAB Coder


App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-16

Derive Quadrotor Dynamics for Nonlinear Model Predictive Control . . . 5-30

Using Symbolic Mathematics with Optimization Toolbox Solvers . . . . . . 5-37

Improving Accuracy and Performance in Optimization . . . . . . . . . . . . . . 5-46

Analytical Model of Cantilever Truss Structure for Simscape . . . . . . . . . 5-52

Customize and Extend Simscape Libraries for a Custom DC Motor . . . . 5-60

Estimate Model Parameters of a Symbolically Derived Plant Model in


Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-69

xi
MuPAD to MATLAB Migration
6
MuPAD Engines and MATLAB Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2

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


Convert a MuPAD Notebook .mn to a MATLAB Live Script .mlx . . . . . . . . . 6-3
Convert MuPAD Graphics to MATLAB Graphics . . . . . . . . . . . . . . . . . . . . 6-4
Known Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-4

Troubleshoot MuPAD to MATLAB Translation Errors . . . . . . . . . . . . . . . . . 6-8

Troubleshoot MuPAD to MATLAB Translation Warnings . . . . . . . . . . . . . 6-15

Differences Between MATLAB and MuPAD Syntax . . . . . . . . . . . . . . . . . . 6-20

Call Built-In MuPAD Functions from MATLAB . . . . . . . . . . . . . . . . . . . . . 6-22


evalin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-22
feval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-22
evalin vs. feval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-23
Floating-Point Arguments of evalin and feval . . . . . . . . . . . . . . . . . . . . . 6-23

Functions
7

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-9
• “Create Symbolic Matrices” on page 1-11
• “Create Symbolic Matrix Variables” on page 1-13
• “Use Symbolic Objects to Represent Mathematical Objects” on page 1-20
• “Perform Symbolic Computations” on page 1-28
• “Use Assumptions on Symbolic Variables” on page 1-41
• “Computational Mathematics in Symbolic Math Toolbox” on page 1-44
• “Next Step Suggestions for Symbolic Workflows in Live Editor” on page 1-57
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. In the MATLAB Live Editor, you can
get next-step suggestions for symbolic workflows. The toolbox provides functions in common
mathematical areas such as calculus, linear algebra, algebraic and differential equations, equation
simplification, and equation manipulation.

Symbolic Math Toolbox lets you analytically perform differentiation, integration, simplification,
transforms, and equation solving. You can perform dimensional computations and convert between
units. Your computations can be performed either analytically or using variable-precision arithmetic,
with the results displayed in mathematical typeset.

You can share your symbolic work with other MATLAB users as live scripts or convert them to HTML,
Word, LaTex or PDF documents. You can generate MATLAB functions, Simulink® Function blocks, and
Simscape™ equations directly from symbolic expressions.

1-2
Create Symbolic Numbers, Variables, and Expressions

Create Symbolic Numbers, Variables, and Expressions

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

Create Symbolic Numbers with Exact Representations

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

Create symbolic numbers by using sym and compare them to the same floating-point numbers.
a1Sym = sym(1/3)

a1Sym =
1
3

a1 = 1/3

a1 = 0.3333

a2Sym = sym(pi)

a2Sym = π

a2 = pi

a2 = 3.1416

The symbolic numbers are represented in exact rational form, while the floating-point numbers are
decimal approximations.

Calculations on symbolic numbers are exact. Demonstrate this exactness by finding sin(pi)
symbolically and numerically. The symbolic result is exact, while the numeric result is an
approximation.
bSym = sin(sym(pi))

bSym = 0

b = sin(pi)

b = 1.2246e-16

When you use sym on a numeric input, the numeric expression is first evaluated to the MATLAB®
default double-precision number that can be less accurate. Then, sym is applied on that double-
precision number. To represent an exact number without evaluating it to double precision, use a
character vector with quotes. For example, create a symbolic number to represent a very large
integer exactly.
inaccurateNum = sym(123456789012345678)

inaccurateNum = 123456789012345680

accurateNum = sym('123456789012345678')

accurateNum = 123456789012345678

1-3
1 Getting Started

You can also create symbolic complex numbers, by specifying the imaginary part of a number as 1i,
2i, and so on.

sym('1234567 + 1i')

ans = 1234567 + i

To learn more about symbolic representation of numbers, see “Numeric to Symbolic Conversion” on
page 2-29.

Create Symbolic Numbers with Variable Precision

You can create symbolic numbers with variable-precision floating-point arithmetic by using vpa. By
default, vpa calculates values to 32 significant digits.

piVpa = vpa(pi)

piVpa = 3.1415926535897932384626433832795

When you use vpa on a numeric expression, such as log(2), the expression is first evaluated to the
MATLAB default double-precision number that has less than 32 significant digits. Then, vpa is
applied on that double-precision number, which can be less accurate. For more accurate results,
convert double-precision numbers in an expression to symbolic numbers with sym and then use vpa
to evaluate the results with variable precision. For example, find log(2) with 17- and 20- digit
precision.

vpaOnDouble = vpa(log(2))

vpaOnDouble = 0.69314718055994528622676398299518

vpaOnSym_17 = vpa(log(sym(2)),17)

vpaOnSym_17 = 0.69314718055994531

vpaOnSym_20 = vpa(log(sym(2)),20)

vpaOnSym_20 = 0.69314718055994530942

When you convert large numbers, use quotes to represent them exactly.

inaccurateNum = vpa(123456789012345678)

inaccurateNum = 123456789012345680.0

accurateNum = vpa('123456789012345678')

accurateNum = 123456789012345678.0

Create Symbolic Variables

You can create symbolic variables using either syms or sym. Typical uses of these functions include:

• sym – Create numbered symbolic variables, symbolic variables in MATLAB functions, or symbolic
numbers whose values differ from their names in the MATLAB workspace.
• syms – Create fresh symbolic variables for interactive symbolic workflows, that is, for symbolic
variable creation at the MATLAB command line or in MATLAB live scripts. A fresh symbolic
variable does not have any assumptions.

1-4
Create Symbolic Numbers, Variables, and Expressions

The syms command is shorthand for the sym syntax, but the two functions handle assumptions
differently. syms clears the assumptions when creating variables. However, recreating a variable
using sym does not clear its assumptions. For more details about the differences of these two
functions, see “Choose syms or sym Function” on page 2-4.

Create the symbolic variables x and y using syms and sym, respectively.
syms x
y = sym('y')

y = y

The first command creates a symbolic variable x in the MATLAB workspace with the value x assigned
to the variable x. The second command creates a symbolic variable y with the value y.

With syms, you can create multiple variables in one command. Create the variables a, b, and c.
syms a b c

Create Array of Symbolic Variables

If you want to create a MATLAB array of numbered symbolic variables, you can use the sym or the
syms syntax.

Use sym to create an array of many numbered symbolic variables. Clear the workspace. Create a row
vector containing the symbolic variables a1, …, a10 and assign it to the MATLAB variable A. Display
the variable in the MATLAB workspace.
clear
A = sym('a',[1 10])

A = a1 a2 a3 a4 a5 a6 a7 a8 a9 a10

whos

Name Size Bytes Class Attributes

A 1x10 8 sym

A is a 1-by-10 array of 10 automatically generated elements. These generated elements of A do not


appear in the MATLAB workspace.

Use syms to create many fresh symbolic variables with corresponding variable names in the MATLAB
workspace. Clear the workspace. Create the fresh symbolic variables a1, ..., a10. Display the
variables in the MATLAB workspace.
clear
syms a [1 10]
whos

Name Size Bytes Class Attributes

a 1x10 8 sym
a1 1x1 8 sym
a10 1x1 8 sym
a2 1x1 8 sym
a3 1x1 8 sym
a4 1x1 8 sym

1-5
1 Getting Started

a5 1x1 8 sym
a6 1x1 8 sym
a7 1x1 8 sym
a8 1x1 8 sym
a9 1x1 8 sym

The MATLAB workspace contains 10 MATLAB variables in the workspace that are symbolic variables.

The syms command is a convenient shorthand for the sym syntax, and its typical use is to create fresh
symbolic variables for interactive symbolic workflows. Use the sym syntax to create the following:

• Symbolic variables in MATLAB functions


• Many numbered symbolic variables
• Symbolic variable whose value differs from its name in the MATLAB workspace
• Symbolic number, such as sym(3)/11
• Symbolic variable that inherits the assumptions from a previously used symbolic variable having
the same name

Create Symbolic Expressions

1+ 5
Suppose you want to use a symbolic variable to represent the golden ratio φ = 2
.

Use sym to create the golden ratio.

phi = (1 + sqrt(sym(5)))/2;

Now you can perform various mathematical operations on phi. For example:

f = phi^2 - phi - 1

f =
5 1 2 5 3
+ − −
2 2 2 2

Next, suppose you want to study the quadratic function f = ax2 + bx + c. First, create the symbolic
variables a, b, c, and x.

syms a b c x

Then, create a symbolic expression f that represents the arithmetical expression ax2 + bx + c.

f = a*x^2 + b*x + c

f = a x2 + b x + c

Solve the quadratic equation f = 0 for x by using solve.

x_0 = solve(f == 0,x)

x_0 =
2
b+ b −4ac

2a
2
b− b −4ac

2a

1-6
Create Symbolic Numbers, Variables, and Expressions

You can also apply a mathematical function to an arithmetical expression. For example, apply the
Bessel function of the first kind J0 to the arithmetical expression f and find its derivative with respect
to x.

J_0 = besselj(0,f)

J_0 = J0 a x2 + b x + c

DJ_0 = diff(J_0,x)

DJ_0 = − J1 a x2 + b x + c b + 2 a x

To create a symbolic number in a symbolic expression, use sym. Do not use syms to create a symbolic
expression that is a constant. For example, to create an expression whose value is 5, enter f =
sym(5). The command f = 5 does not define f as a symbolic expression.

You can also create symbolic expressions from strings by using str2sym when reading expressions
from text files or when specifying numbers exactly.

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 removes the previously defined expression from the variable.

For example, create a symbolic expression f.

syms a b
f = a + b

f = a+b

If you recreate f, then MATLAB removes the value a + b from the expression f.

syms f
f

f = f

You can use the syms command to clear variables of definitions that you previously assigned to them
in your MATLAB session. syms clears the assumptions of the variables. These assumptions (which can
be real, integer, rational, and positive) are stored separately from the symbolic object. However,
recreating a variable using sym does not clear its assumptions. For more information, see “Use
Assumptions on Symbolic Variables” on page 1-41.

See Also
sym | syms | vpa

More About
• “Create Symbolic Functions” on page 1-9
• “Create Symbolic Matrices” on page 1-11
• “Create Symbolic Matrix Variables” on page 1-13
• “Use Symbolic Objects to Represent Mathematical Objects” on page 1-20

1-7
1 Getting Started

• “Choose syms or sym Function” on page 2-4


• “Perform Symbolic Computations” on page 1-28
• “Choose Numeric or Symbolic Arithmetic” on page 2-32
• “Add Subscripts, Superscripts, and Accents to Symbolic Variables in the Live Editor” on page 2-
14

1-8
Create Symbolic Functions

Create Symbolic Functions


Symbolic functions represent math functions. Use symbolic functions for differentiation, integration,
solving ODEs, and other math operations. Create symbolic functions by using syms.

Note Symbolic functions must be functions of symbolic variables. The Symbolic Math Toolbox
currently does not support composite symbolic functions, or symbolic functions that are functions of
another symbolic functions.

Create a symbolic function f with variables x and y by using syms. Creating f automatically creates
x and y.

syms f(x,y)

Assign a mathematical expression to f.

f(x,y) = x^2*y

f(x, y) =
x^2*y

Find the value of f at (3,2).

f(3,2)

ans =
18

Symbolic functions accept array inputs. Calculate f for multiple values of x and y.

xVal = 1:5;
yVal = 3:7;
f(xVal,yVal)

ans =
[ 3, 16, 45, 96, 175]

You can differentiate symbolic functions, integrate or simplify them, substitute their arguments with
values, and perform other mathematical operations. For example, find the derivative of f(x,y) with
respect to x. The result dfx is also a symbolic function.

dfx = diff(f,x)

dfx(x,y) =
2*x*y

Calculate df(x,y) at x = y + 1.

dfx(y+1,y)

ans =
2*y*(y + 1)

If you are creating a constant function, such as f(x,y) = 1, you must first create f(x,y). If you do
not create f(x,y), then the assignment f(x,y) = 1 throws an error.

1-9
1 Getting Started

See Also

More About
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Create Symbolic Matrices” on page 1-11
• “Create Symbolic Matrix Variables” on page 1-13
• “Use Symbolic Objects to Represent Mathematical Objects” on page 1-20
• “Perform Symbolic Computations” on page 1-28
• “Use Assumptions on Symbolic Variables” on page 1-41

1-10
Create Symbolic Matrices

Create Symbolic Matrices


In this section...
“Use Existing Symbolic Variables” on page 1-11
“Generate Elements While Creating a Matrix” on page 1-11
“Create Matrix of Symbolic Numbers” on page 1-12

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.

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:

1-11
1 Getting Started

A = sym('A', [2 4])

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

To control the format of the generated names of matrix elements, use %d in the first argument:

A = sym('A%d%d', [2 4])

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

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)

you can obtain the precise symbolic form of the 3-by-3 Hilbert matrix:

A =
[ 1, 1/2, 1/3]
[ 1/2, 1/3, 1/4]
[ 1/3, 1/4, 1/5]

For more information on numeric to symbolic conversions, see “Numeric to Symbolic Conversion” on
page 2-29.

See Also

More About
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Create Symbolic Functions” on page 1-9
• “Create Symbolic Matrix Variables” on page 1-13
• “Use Symbolic Objects to Represent Mathematical Objects” on page 1-20
• “Perform Symbolic Computations” on page 1-28
• “Use Assumptions on Symbolic Variables” on page 1-41

1-12
Create Symbolic Matrix Variables

Create Symbolic Matrix Variables

Since R2021a

Symbolic matrix variables represent matrices, vectors, and scalars in compact matrix notation. When
mathematical formulas involve matrices and vectors, writing them using symbolic matrix variables is
more concise and clear than writing them componentwise. When you do this, you can take vector-
based expressions and equations from textbooks, enter them in Symbolic Math Toolbox™, perform
mathematical operations on them, and derive further equations from them.

Derived equations involving symbolic matrix variables are displayed in typeset as they would be in
textbooks. For example, create three symbolic matrix variables A, x, and y by using syms. Find the
differential of the expression yT Ax with respect to the vector x.

syms A [3 4] matrix
syms x [4 1] matrix
syms y [3 1] matrix
eq = y.'*A*x

eq = yT A x

D = diff(eq,x)

D = yT A

Comparison Between Matrix of Symbolic Scalar Variables and Symbolic Matrix Variables

Symbolic matrix variables are an alternative to symbolic scalar variables. The two options are of
different types and displayed differently.

For example, create two 2-by-3 matrices of symbolic scalar variables by using syms. For brevity,
matrices of symbolic scalar variables are sometimes called symbolic matrices. These matrices are
displayed by listing their components.

syms A B [2 3]
A

A =
A1, 1 A1, 2 A1, 3
A2, 1 A2, 2 A2, 3

B =
B1, 1 B1, 2 B1, 3
B2, 1 B2, 2 B2, 3

A matrix of symbolic scalar variables is of type sym.

class(A)

ans =
'sym'

1-13
1 Getting Started

Applying symbolic math operations to these matrices can result in a complex solution expressed in
terms of the matrix components. For example, multiply the matrices A and B'.

C = A*B'

C =
A1, 1 B1, 1 + A1, 2 B1, 2 + A1, 3 B1, 3 A1, 1 B2, 1 + A1, 2 B2, 2 + A1, 3 B2, 3
A2, 1 B1, 1 + A2, 2 B1, 2 + A2, 3 B1, 3 A2, 1 B2, 1 + A2, 2 B2, 2 + A2, 3 B2, 3

To create symbolic matrix variables of the same size, use the syms command followed by the variable
names, their size, and the matrix keyword. Symbolic matrix variables are displayed in bold to
distinguish them from symbolic scalar variables.

syms A B [2 3] matrix
A

A = A

B = B

Symbolic matrix variables are of type symmatrix.

class(A)

ans =
'symmatrix'

Applying symbolic math operations to symbolic matrix variables results in a concise display. For
example, multiply A and B'.

C = A*B'

T
C = A B

Mathematical Operations with Symbolic Matrix Variables

Symbolic matrix variables are recognized as noncommutative objects. They support common math
operations, and you can use these operations to build symbolic matrix variable expressions.

syms A B [2 2] matrix
A*B - B*A

ans = A B − B A

For example, check the commutation relation for multiplication between two symbolic matrix
variables.

isequal(A*B,B*A)

ans = logical
0

Check the commutation relation for addition.

isequal(A+B,B+A)

1-14
Create Symbolic Matrix Variables

ans = logical
1

If an operation has any arguments of type symmatrix, the result is automatically converted to type
symmatrix. For example, multiply a matrix A that is represented by symbolic matrix variable and a
scalar c that is represented by symbolic scalar variable. The result is of type symmatrix.
syms A [2 2] matrix
syms c
class(A)

ans =
'symmatrix'

class(c)

ans =
'sym'

M = c*A

M = cA

class(M)

ans =
'symmatrix'

Multiply three matrices that are represented by symbolic matrix variables. The result X is a
symmatrix object.
syms V [2 1] matrix
X = V.'*A*V

X = VT A V

class(X)

ans =
'symmatrix'

You can pass symmatrix objects as arguments to math functions. For example, perform a
mathematical operation to X by taking the differential of X with respect to V.
diff(X,V)

ans = V T AT + V T A

Create Symbolic Matrix Variable from Array of Symbolic Scalar Variables

You can convert an array of symbolic scalar variables to a single symbolic matrix variable using the
symmatrix function. Symbolic matrix variables that are converted in this way are displayed
elementwise.
syms A [3 4]
class(A)

ans =
'sym'

1-15
1 Getting Started

B = symmatrix(A)

B =
Σ1

where

A1, 1 A1, 2 A1, 3 A1, 4


Σ1 = A2, 1 A2, 2 A2, 3 A2, 4
A3, 1 A3, 2 A3, 3 A3, 4

class(B)

ans =
'symmatrix'

Convert Symbolic Matrix Variable into Array of Symbolic Scalar Variables

You can create symbolic matrix variables, derive equations, and then convert the result to arrays of
symbolic scalar variables using the symmatrix2sym function.

For example, find the matrix product of two symbolic matrix variables A and B. The result X is of type
symmatrix.

syms A B [2 2] matrix
X = A*B

X = AB

class(X)

ans =
'symmatrix'

Convert the symbolic matrix variable X to array of symbolic scalar variables. The converted matrix Y
is of type sym.

Y = symmatrix2sym(X)

Y =
A1, 1 B1, 1 + A1, 2 B2, 1 A1, 1 B1, 2 + A1, 2 B2, 2
A2, 1 B1, 1 + A2, 2 B2, 1 A2, 1 B1, 2 + A2, 2 B2, 2

class(Y)

ans =
'sym'

Check that the product obtained by converting symbolic matrix variables is equal to the product of
two arrays of symbolic scalar variables.

syms A B [2 2]
isequal(Y,A*B)

ans = logical
1

1-16
Create Symbolic Matrix Variables

Indexing into Symbolic Matrix Variables

Indexing into a symbolic matrix variable returns corresponding matrix elements in the form of
another symbolic matrix variable.

syms A [2 3] matrix
a = A(2,3)

a = A2, 3

class(a)

ans =
'symmatrix'

Alternatively, convert the symbolic matrix variable A to a matrix of symbolic scalar variables. Then,
index into that matrix.

Asym = symmatrix2sym(A)

Asym =
A1, 1 A1, 2 A1, 3
A2, 1 A2, 2 A2, 3

asym = Asym(2,3)

asym = A2, 3

class(asym)

ans =
'sym'

Note that both results are equal.

isequal(a,symmatrix(asym))

ans = logical
1

Display of Operations Involving Symbolic Matrix Variables

Matrices like those returned by eye, zeros, and ones often have special meaning with specific
notation in symbolic workflows. Declaring these matrices as symbolic matrix variables display the
matrices in bold along with the matrix dimensions.

symmatrix(eye(3))

ans = I3

symmatrix(zeros(2,3))

ans = 02, 3

symmatrix(ones(3,5))

ans = 13, 5

1-17
1 Getting Started

If the inputs to a componentwise operation in MATLAB® are symbolic matrix variables, so is the
output. These operations are displayed in special notations which follow conventions from textbooks.

syms A B [3 3] matrix
A.*B

ans = A ⊙ B

A./B

ans = A ⊘ B

A.\B

ans = B ⊘ A

A.*hilb(3)

ans =
A ⊙ Σ1

where

1 1
1
2 3
1 1 1
Σ1 =
2 3 4
1 1 1
3 4 5

A.^(2*ones(3))

∘ 2 13, 3
ans = A

A.^B

ans = A ∘ B

kron(A,B)

ans = A ⊗ B

adjoint(A)

ans = adj A

trace(A)

ans = Tr A

See Also
syms | symmatrix | symmatrix2sym

More About
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Create Symbolic Functions” on page 1-9

1-18
Create Symbolic Matrix Variables

• “Create Symbolic Matrices” on page 1-11


• “Use Symbolic Objects to Represent Mathematical Objects” on page 1-20
• “Perform Symbolic Computations” on page 1-28

1-19
1 Getting Started

Use Symbolic Objects to Represent Mathematical Objects


To solve mathematical problems with Symbolic Math Toolbox, you can define symbolic objects to
represent various mathematical objects. This example discusses the usage of these symbolic objects
in the Command Window:

• symbolic number
• symbolic scalar variable, function, and expression
• symbolic equation
• symbolic vector and matrix
• symbolic matrix variable
• symbolic matrix function

Symbolic Number
Defining a number as a symbolic number instructs MATLAB to treat the number as an exact form
instead of using a numeric approximation. For example, use a symbolic number to represent the
−1
argument of an inverse trigonometric function θ = sin (1/ 2).

Create the symbolic number 1/ 2 using sym, and assign it to a.

a = sym(1/sqrt(2))

a =
2^(1/2)/2

Find the inverse sine of a. The result is the symbolic number pi/4.

thetaSym = asin(a)

thetaSym =
pi/4

You can convert a symbolic number to variable-precision arithmetic by using vpa. The result is a
decimal number with 32 significant digits.

thetaVpa = vpa(thetaSym)

thetaVpa =
0.78539816339744830961566084581988

To convert the symbolic number to a double-precision number, use double. For more information
about whether to use numeric or symbolic arithmetic, see “Choose Numeric or Symbolic Arithmetic”
on page 2-32.

thetaDouble = double(thetaSym)

thetaDouble =
0.7854

1-20
Use Symbolic Objects to Represent Mathematical Objects

Symbolic Scalar Variable, Function, and Expression


Defining variables, functions, and expressions as symbolic objects enables you to perform algebraic
operations with those symbolic objects, including simplifying formulas and solving equations. For
example, use a symbolic scalar variable, function, and expression to represent the quadratic function
f (x) = x2 + x − 2. For brevity, a symbolic scalar variable is also called a symbolic variable.

Create a symbolic scalar variable x using syms. You can also use sym to create a symbolic scalar
variable. For more information about whether to use syms or sym, see “Choose syms or sym
Function” on page 2-4.

Define a symbolic expression x^2 + x - 2 to represent the right side of the quadratic equation and
assign it to f(x). The identifier f(x) now refers to a symbolic function that represents the quadratic
function. A symbolic function accepts scalars as input arguments.

syms x
f(x) = x^2 + x - 2

f(x) =
x^2 + x -2

You can then evaluate the quadratic function by providing its input argument inside the parentheses.
For example, evaluate f(2).

fVal = f(2)

fVal =
4

You can also solve the quadratic equation f (x) = 0. Use solve to find the roots of the quadratic
equation. solve returns the two solutions as a vector of two symbolic numbers.

sols = solve(f)

sols =
-2
1

Symbolic Equation
Defining a mathematical equation as a symbolic equation enables you to find the solution of the
equation. For example, use a symbolic equation to solve the trigonometric problem 2sin(t)cos(t) = 1.

Create a symbolic function g(t) using syms. Assign the symbolic expression 2*sin(t)*cos(t) to
g(t).

syms g(t)
g(t) = 2*sin(t)*cos(t)

1-21
1 Getting Started

g(t) =
2*cos(t)*sin(t)

To define the equation, use the == operator and assign the mathematical relation g(t) == 1 to eqn.
The identifier eqn is a symbolic equation that represents the trigonometric problem.

eqn = g(t) == 1

eqn =
2*cos(t)*sin(t) == 1

Use solve to find the solution of the trigonometric problem.

sol = solve(eqn)

sol =
pi/4

Symbolic Vector and Matrix


Use a symbolic vector and matrix to represent and solve a system of linear equations.

x + 2y = u
4x + 5y = v

You can represent the system of equations as a vector of two symbolic equations. You can also
represent the system of equations as a matrix problem involving a matrix of symbolic numbers and a
vector of symbolic variables. For brevity, any vector of symbolic objects is called a symbolic vector
and any matrix of symbolic objects is called a symbolic matrix.

Create two symbolic equations eq1 and eq2. Combine the two equations into a symbolic vector.

syms u v x y
eq1 = x + 2*y == u;
eq2 = 4*x + 5*y == v;
eqns = [eq1, eq2]

eqns =
[x + 2*y == u, 4*x + 5*y == v]

Use solve to find the solutions of the system of equations represented by eqns. solve returns a
structure S with fields named after each of the variables in the equations. You can access the
solutions using dot notation, as S.x and S.y.

S = solve(eqns);
S.x

ans =
(2*v)/3 - (5*u)/3

S.y

1-22
Use Symbolic Objects to Represent Mathematical Objects

ans =
(4*u)/3 - v/3

Another way to solve the system of linear equations is to convert it to matrix form. Use
equationsToMatrix to convert the system of equations to matrix form and assign the output to A
and b. Here, A is a symbolic matrix and b is a symbolic vector. Solve the matrix problem by using the
matrix division \ operator.
[A,b] = equationsToMatrix(eqns,x,y)

A =
[1, 2]
[4, 5]

b =
u
v

sols = A\b

sols =
(2*v)/3 - (5*u)/3
(4*u)/3 - v/3

Symbolic Matrix Variable


Since R2021a

Use symbolic matrix variables to evaluate differentials with respect to vectors.

α = yTAx
∂α
= y TA
∂x
∂α
= xTA T
∂y

Symbolic matrix variables represent matrices, vectors, and scalars in compact matrix notation.
Symbolic matrix variables offer a concise display in typeset and show mathematical formulas with
more clarity. You can enter vector- and matrix-based expressions as symbolic matrix variables in
Symbolic Math Toolbox.

Create three symbolic matrix variables x, y, and A using the syms command with the matrix syntax.
Nonscalar symbolic matrix variables are displayed as bold characters in the Command Window and in
the Live Editor.
syms x [4 1] matrix
syms y [3 1] matrix
syms A [3 4] matrix

1-23
1 Getting Started

x
y
A

x =
x

y =
y

A =
A

Define alpha. Find the differential of alpha with respect to the vectors x and y that are represented
by the symbolic matrix variables x and y.
alpha = y.'*A*x

alpha =
y.'*A*x

Dx = diff(alpha,x)

Dx =
y.'*A

Dy = diff(alpha,y)

Dy =
x.'*A.'

Substitute y with [1; 2; 3] in Dx and substitute x with [-1; 2; 0; 1] in Dy using subs. When
evaluating a symbolic expression, you must substitute values that have the same size as the defined
symbolic matrix variables.
Dx = subs(Dx,y,[1; 2; 3])

Dx =
symmatrix([1;2;3]).'*A

Dy = subs(Dy,x,[-1; 2; 0; 1])

Dx =
symmatrix([-1;2;0;1]).'*A.'

Symbolic Matrix Function


Since R2022a

Use a symbolic matrix function to evaluate a matrix polynomial.

f (A) = A2 − 3A + I2

A symbolic matrix function represents a parameter-dependent function that accepts matrices,


vectors, and scalars as input arguments. Symbolic matrix function operates on matrices in compact
matrix notation, offering a concise display in typeset and showing mathematical formulas with more
clarity. You can enter vector- and matrix-based formulas as symbolic matrix functions in Symbolic
Math Toolbox.

1-24
Use Symbolic Objects to Represent Mathematical Objects

Create a 2-by-2 symbolic matrix variable A using the syms command with the matrix syntax. Create
a symbolic matrix function f(A) that accepts A as an input argument using the syms command with
the matrix keepargs syntax to keep the previous definition of A.

syms A 2 matrix
syms f(A) 2 matrix keepargs

Assign the polynomial expression to the symbolic matrix function.

f(A) = A^2 - 3*A + 2*eye(2)

f(A) =

2*symmatrix(eye(2)) - 3*A + A^2

Evaluate the function for the matrix value A = [1 2; -2 -1]. When evaluating a symbolic matrix
function, you must substitute values that have the same size as the defined input arguments.

fEval = f([1 2; -2 -1])

fEval =

- 3*symmatrix([1,2;-2,-1]) + symmatrix([1,2;-2,-1])^2 + 2*symmatrix(eye(2))

Convert the evaluated function from the symmatrix data type to the sym data type.

fSym = symmatrix2sym(fEval)

fSym =
[-4, -6]
[ 6, 2]

Comparison of Symbolic Objects


This table compares the symbolic objects that are available in Symbolic Math Toolbox.

Symbolic Object Examples of MATLAB Size of Symbolic Data Type


Command Object
Symbolic number a = 1/sqrt(sym(2)) 1-by-1 sym
theta = asin(a)

a =
2^(1/2)/2

theta =
pi/4
Symbolic scalar variable syms x y u v 1-by-1 sym

1-25
1 Getting Started

Symbolic Object Examples of MATLAB Size of Symbolic Data Type


Command Object
Symbolic function syms x • Size of • Data type of
f(x) = x^2 + x - 2 unevaluated unevaluated
syms g(t) [1 3] function, such function, such
g as size(g), is as class(g),
f(x) = 1-by-1. is symfun.
x^2 + x - 2 • Size of • Data type of
evaluated evaluated
g(t) = function, such function, such
[g1(t), g2(t), g3(t)]
as as
size(g(t)), is class(g(t)),
m-by-n, where m is sym.
is the row size
and n is the
column size.
Symbolic expression syms x 1-by-1 sym
expr = x^2 + x - 2
expr2 = 2*sin(x)*cos(x)

expr =
x^2 + x - 2

expr2 =
2*cos(x)*sin(x)
Symbolic equation syms u v x y 1-by-1 sym
eq1 = x + 2*y == u
eq2 = 4*x + 5*y == v

eq1 =
x + 2*y == u

eq2 =
4*x + 5*y == v
Symbolic vector syms u v 1-by-n or m-by-1, sym
b = [u v] where m is the row
size and n is the
b =
[u, v]
column size

Symbolic matrix syms A x y m-by-n, where m is sym


A = [x y; x*y y^2] the row size and n
is the column size
A =
[ x, y]
[x*y, y^2]

1-26
Use Symbolic Objects to Represent Mathematical Objects

Symbolic Object Examples of MATLAB Size of Symbolic Data Type


Command Object
Symbolic multidimensional syms A [2 1 2] sz1-by-sz2-...-szn, sym
array A where szn is the
size of the nth
A(:,:,1) =
A1_1
dimension
A2_1

A(:,:,2) =
A1_2
A2_2
Symbolic matrix variable syms A B [2 3] matrix m-by-n, where m is symmatrix
A the row size and n
(since R2021a) B is the column size
A =
A

B =
B
Symbolic matrix function syms X Y [2 2] matrix • Size of • Data type of
syms f(X,Y) [2 2] matrix keepargs
unevaluated unevaluated
(since R2022a) f(X,Y) = X*Y - Y*X matrix function, matrix function,
f(X, Y) =
such as such as
X*Y - Y*X size(f), is 1- class(f), is
by-1. symfunmatrix
• Size of .
evaluated • Data type of
function, such evaluated
as function, such
size(f(X,Y)) as
, is m-by-n, class(f(X,Y)
where m is the ), is
row size and n symmatrix.
is the column
size.

See Also
syms | sym | symfun | symmatrix | symfunmatrix | symfunmatrix2symfun | symmatrix2sym |
str2sym

More About
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Create Symbolic Functions” on page 1-9
• “Create Symbolic Matrices” on page 1-11
• “Create Symbolic Matrix Variables” on page 1-13
• “Choose syms or sym Function” on page 2-4
• “Choose Numeric or Symbolic Arithmetic” on page 2-32

1-27
1 Getting Started

Perform Symbolic Computations

In this section...
“Differentiate Symbolic Expressions” on page 1-28
“Integrate Symbolic Expressions” on page 1-29
“Solve Equations” on page 1-30
“Simplify Symbolic Expressions” on page 1-32
“Substitutions in Symbolic Expressions” on page 1-33
“Plot Symbolic Functions” on page 1-35

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

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:

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

ans =
2*cos(x)*sin(x)

For the complete set of rules MATLAB applies for choosing a default variable, see “Find a Default
Symbolic Variable” on page 2-2.

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

1-28
Perform Symbolic Computations

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


• Integration of multivariable expressions

For in-depth information on the int command including integration with real and complex
parameters, see “Integration” on page 3-176.

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:

1-29
1 Getting Started

syms x y n
f = x^n + y^n;
int(f)

ans =
x*y^n + (x*x^n)/(n + 1)

For the complete set of rules MATLAB applies for choosing a default variable, see “Find a Default
Symbolic Variable” on page 2-2.

You also can integrate the expression f = x^n + y^n with respect to y

syms x y n
f = x^n + y^n;
int(f, y)

ans =
x^n*y + (y*y^n)/(n + 1)

If the integration variable is n, enter

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

1-30
Perform Symbolic Computations

• 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:

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

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

y =
0

1-31
1 Getting Started

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
f = (x ^2- 1)*(x^4 + x^3 + x^2 + x + 1)*(x^4 - x^3 + x^2 - x + 1);
expand(f)

ans =
x^10 - 1

The factor simplification function shows the polynomial roots. If a polynomial cannot be factored
over the rational numbers, the output of the factor function is the standard polynomial form. For
example, to factor the third-order polynomial, enter:

syms x
g = x^3 + 6*x^2 + 11*x + 6;
factor(g)

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

The nested (Horner) representation of a polynomial is the most efficient for numerical evaluations:

1-32
Perform Symbolic Computations

syms x
h = x^5 + x^4 + x^3 + x^2 + x;
horner(h)

ans =
x*(x*(x*(x*(x + 1) + 1) + 1) + 1)

For a list of Symbolic Math Toolbox simplification functions, see “Choose Function to Rearrange
Expression” on page 3-119.

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:

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)

1-33
1 Getting Started

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)

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-34
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 3-142.

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.
• 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 x3 − 6x2 + 11x − 6.
syms x
f = x^3 - 6*x^2 + 11*x - 6;
fplot(f)

1-35
1 Getting Started

Add labels for the x- and y-axes. Generate the title by using texlabel(f). Show the grid by using
grid on. For details, see “Add Title and Axis Labels to Chart”.

xlabel('x')
ylabel('y')
title(texlabel(f))
grid on

1-36
Perform Symbolic Computations

Implicit Function Plot

Plot equations and implicit functions using fimplicit.

4 2
Plot the equation (x2 + y2) = (x2 − y2) over −1 < x < 1.

syms x y
eqn = (x^2 + y^2)^4 == (x^2 - y^2)^2;
fimplicit(eqn, [-1 1])

1-37
1 Getting Started

3-D Plot

Plot 3-D parametric lines by using fplot3.

Plot the parametric line

x = t2sin(10t)
y = t2cos(10t)
z = t.

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

1-38
Perform Symbolic Computations

Create Surface Plot

Create a 3-D surface by using fsurf.

Plot the paraboloid z = x2 + y2.

syms x y
fsurf(x^2 + y^2)

1-39
1 Getting Started

See Also

More About
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Create Symbolic Functions” on page 1-9
• “Create Symbolic Matrices” on page 1-11
• “Use Assumptions on Symbolic Variables” on page 1-41

1-40
Use Assumptions on Symbolic Variables

Use Assumptions on Symbolic Variables

You can set mathematical assumptions or conditions on symbolic variables to restrict the domain and
range of the variables. This example shows how to set, check, and clear assumptions.

Default Assumption

In Symbolic Math Toolbox™, symbolic variables are complex variables by default. For example, if you
create z as a symbolic variable, then Symbolic Math Toolbox assumes that z is a complex variable.

syms z

You can check if a symbolic variable is assumed to be complex by using assumptions. If z is


complex, then assumptions(z) returns an empty symbolic object.

assumptions(z)

ans =

Empty sym: 1-by-0

Set Assumptions

To set mathematical assumptions or conditions on symbolic variables, use the assume function. For
example, assume that the variable x is larger than 2.

syms x
assume(x > 2)

assume replaces all previous assumptions on the variable with the new assumption. If you want to
add a new assumption to the existing assumptions, then use assumeAlso. For example, add the
assumption that x is also an integer. Now the variable x is an integer larger than 2.

assumeAlso(x,"integer")

assume and assumeAlso let you state that a variable or an expression belongs to these sets: real
numbers, rational numbers, integers, and positive numbers. You can also use assume and
assumeAlso to set mathematical conditions on symbolic variables or expressions, such as x > 2.

Alternatively, you can set assumptions when declaring symbolic variables using sym or syms, where
the assumptions are limited to these sets: real numbers, rational numbers, integers, and positive
numbers. For example, create the real symbolic variables a and b, and the positive symbolic variable
c using sym.

a = sym("a","real");
b = sym("b","real");
c = sym("c","positive");

You can also use syms to create these symbolic variables with assumptions.

syms a b real
syms c positive

1-41
1 Getting Started

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 set
on the variable x.

assumptions(x)

ans = x ∈ ℤ 2 < x

To see all assumptions set on all symbolic variables in the MATLAB® workspace, use assumptions
without input arguments.

assumptions

ans = a ∈ ℝ b ∈ ℝ x ∈ ℤ 0 < c 2 < x

Delete Symbolic Objects and Their Assumptions

Symbolic objects and their assumptions are stored separately. When you set an assumption that the
symbolic variable x is real, you actually create a symbolic object x and the assumption that the object
is real. The object is stored in the MATLAB workspace, and the assumption is stored in the symbolic
engine. When you delete a symbolic object from the MATLAB workspace using clear, the
assumption that x is real stays in the symbolic engine.

syms x
assume(x,"real")
clear x

If you recreate a variable using sym, then the existing assumptions apply. If you recreate a variable
using syms, then the existing assumptions on that variable are cleared.

For example, the assumption that x is real causes the polynomial x^2 + 1 == 0 to have no roots.

x = sym("x");
solve(x^2 + 1 == 0, x)

ans =

Empty sym: 0-by-1

The complex roots of this polynomial do not appear as solutions because the symbolic variable x still
has the assumption that x is real stored in the symbolic engine. To clear the assumption, recreate the
variable using syms.

syms x

Solve the same polynomial equation again.

solve(x^2 + 1 == 0, x)

ans =
−i
i

1-42
Use Assumptions on Symbolic Variables

If you want to delete both the symbolic object and its assumption, first clear the assumption on the
symbolic object using assume(x,"clear") and then clear the object using clear x.

assume(x,"clear")
clear x

For details on clearing symbolic variables, see “Clear Assumptions and Reset the Symbolic Engine”
on page 3-314.

See Also

More About
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Create Symbolic Functions” on page 1-9
• “Create Symbolic Matrices” on page 1-11
• “Perform Symbolic Computations” on page 1-28

1-43
1 Getting Started

Computational Mathematics in Symbolic Math Toolbox

This example provides an overview of the Symbolic Math Toolbox™ which offers a complete set of
tools for computational and analytical mathematics.

This example includes

• Variables, Expressions, Functions and Equations


• Substitution and Solving
• Simplification and Manipulation
• Calculus (Differentiation, Integration, Limits, Series)
• Differential Equations
• Linear Algebra
• Graphics

For more details see “Get Started with Symbolic Math Toolbox”. For more details on documenting and
sharing your mathematics see “Create Live Scripts in the Live Editor”.

Variables, Expressions, Functions and Equations

Variables in MATLAB® are by default double-precision. The Symbolic Math Toolbox extends this by
allowing you to express numbers in exact symbolic form using sym and with variable-precision using
vpa.

1-44
Computational Mathematics in Symbolic Math Toolbox

pi/6 + pi/4

ans = 1.3090

sym(pi/6) + sym(pi/4)

ans =

12

vpa(pi/6) + vpa(pi/4)

ans = 1.3089969389957471826927680763665

Symbolic variables can be used in mathematical expressions, functions and equations including
trigonometric, logarithmic, exponential, and special functions. You can create symbolic expressions
and perform mathematical calculations on them.

syms x y
log(x) + exp(y)

ans = ey + log x

You can also create piecewise functions.

y(x) = piecewise(x<0, -1, x>0, 1)

y(x) =
−1 if x < 0
1 if 0 < x

Create and evaluate “Create Symbolic Functions” on page 1-9. Find the value of f at x = − 5.

syms f(x)
f(x) = x^4-2*x^3+6*x^2-2*x+10

f(x) = x4 − 2 x3 + 6 x2 − 2 x + 10

f(-5)

ans = 1045

Find the intersection between lines y1 and y2 using solve. Equate the lines using the == operator.

syms y1 y2
y1 = x+3; y2 = 3*x;
solve(y1 == y2)

ans =
3
2

Make assume on symbolic variables. There are 4 solutions to x4 = 1, two real and two complex.
Assuming that x is real and x > 0, there is only one solution.

syms x
solve(x^4 == 1)

ans =

1-45
1 Getting Started

−1
1
−i
i

assume(x,'real')
assumeAlso( x > 0)
assumptions(x)

ans = x ∈ ℝ 0 < x

solve(x^4 == 1)

ans = 1

assume(x,'clear')

Substitution and Solving

The Symbolic Math Toolbox supports evaluation of mathematical functions by substituting for any
part of an expression using subs. You can substitute numeric values, other symbolic variables or
expressions, vectors, or matrices. The Symbolic Math Toolbox supports the solving of equations and
systems of equations using solve. It supports solving multivariate equations, solving inequalities and
solving with assumptions. Solutions can be found symbolically or numerically with high precision by
using variable-precision arithmetic.

Make substitutions with your symbolic variables. Substitute x = xo − 1 into x2 + 1

syms x xo
subs(x^2+1,x,xo-1)

2
ans = xo − 1 +1

Substitute multiple values. For example, evaluate cos(a) + sin(b) − e2C by substituting
π π
a = , b = , c = − 1.
2 4

syms a b c
subs(cos(a) + sin(b) - exp(2*c), [a b c], [pi/2 pi/4 -1])

ans =
2
− e−2
2

Create and solve equations. Find the zeros of 9x2 − 1 = 0.

solve(9*x^2 - 1 == 0)

ans =
1

3
1
3

Solve the general quadratic equation ax2 + bx + c = 0 and use subs to evaluate that solution for
a = 9, b = 0, c = − 1.

1-46
Computational Mathematics in Symbolic Math Toolbox

eqn = a*x^2 + b*x + c == 0;


sol = solve(eqn)

sol =
2
b+ b −4ac

2a
2
b− b −4ac

2a

subs(sol,[a b c],[9 0 -1])

ans =
1

3
1
3

Solve equations symbolically or with variable-precision arithmetic when exact results or high
precision is needed. The graph of f x = 6x7 − 2x6 + 3x3 − 8 is very flat near its root.

syms x f(x)
assume(x>0)
f(x) = 6*x^7-2*x^6+3*x^3-8;
fplot(f)
xlim([-10 10])
ylim([-1e3 1e3])

1-47
1 Getting Started

doubleSol = roots([6 -2 0 0 3 0 0 -8]) % double-precision

doubleSol = 7×1 complex

1.0240 + 0.0000i
0.7652 + 0.8319i
0.7652 - 0.8319i
-0.8808 + 0.5043i
-0.8808 - 0.5043i
-0.2297 + 0.9677i
-0.2297 - 0.9677i

symsSol = solve(f) % exact. The roots object stores the zeros for symbolic computations

symsSol =
z6 z3 4
root z7 − + − , z, 5
3 2 3

vpaSol = vpasolve(f) % variable-precision

vpaSol =
1.0240240759053702941448316563337
−0.88080620051762149639205672298326 + 0.50434058840127584376331806592405 i
−0.88080620051762149639205672298326 − 0.50434058840127584376331806592405 i
−0.22974795226118163963098570610724 + 0.96774615576744031073999010695171 i
−0.22974795226118163963098570610724 − 0.96774615576744031073999010695171 i
0.7652087814927846556172932675903 + 0.83187331431049713218367239317121 i
0.7652087814927846556172932675903 − 0.83187331431049713218367239317121 i

Simplification and Manipulation

The Symbolic Math Toolbox supports the “Formula Manipulation and Simplification” of mathematical
functions. Most mathematical expressions can be represented in different, but mathematically
equivalent forms and the Symbolic Math Toolbox supports a number of operations, including
factoring or expanding expressions, combining terms, rewriting or rearranging expressions, and
simplification based on assumptions.

Perform polynomial multiplication and simplify the results, show that


(x − 1)(x + 1)(x2 + x + 1)(x2 + 1)(x2 − x + 1)(x4 − x2 + 1) simplifies to x12 − 1.

simplify((x - 1)*(x + 1)*(x^2 + x + 1)*(x^2 + 1)*(x^2 - x + 1)*(x^4 - x^2 + 1))

ans = x12 − 1

1 − cos(2x)
Apply trigonometric identities to simplifications, for example sin2(x) = .
2

combine(2*sin(x)*cos(x) + (1- cos(2*x))/2 + cos(x)^2,'sincos')

ans = sin 2 x + 1

Factor or expand multivariate polynomials.

syms x y
factor(y^6-x^6)

1-48
Computational Mathematics in Symbolic Math Toolbox

ans = −1 x − y x + y x2 + x y + y2 x2 − x y + y2

f(x) = (x^3 + 7);


expand(f(y-1))

ans = y3 − 3 y2 + 3 y + 6

Find the functional composition f (g(x)).


f(x) = sqrt(log(x));
g(x) = sqrt(1-x);
h = compose(g,f,x)

h(x) = 1 − log x

Calculus (Differentiation, Integration, Limits, Series, etc)

The Symbolic Math Toolbox has a full set of calculus tools for applied mathematics. It can perform
multivariate symbolic integration and differentiation. It can generate, manipulate, and perform
calculations with series.

d
Find the derivative of sin(x) .
dx
diff(sin(x))

ans = cos x

d 2
Find the derivative of x + sin(2x4) + 1 using the chain rule.
dx
diff(x^2+sin(2*x^4)+1,x)

ans = 2 x + 8 x3 cos 2 x4

−x2
Find the indefinite integral ∫ f (x) dx for f (x) = e 2 .

int(exp(-x^2/2),x)

ans =
2x
2 π erf 2
2


b
Find the definite integral f (x) dx for f (x) = xlog(1 + x) from 0 to 1.
a

int(x*log(1+x),0,1)

ans =
1
4

(n)
sin(x) n f (a)
Show that = 1 at x = 0 by computing the Taylor series expansion ∑ (x − a) for
x n!
sin(x)
f (x) = around the point x = 0.
x

1-49
1 Getting Started

syms x
T = taylor(sin(x)/x)

T =
x4 x2
− +1
120 6

subs(T,x,0)

ans = 1

π
Show that tan(x) is discontinuous at x = by showing that the left and right limits are not equal.
2
lim tan(x) ≠ lim tan(x).
π+ π−
x→ x→
2 2

limit(tan(x),x,pi/2,'left')

ans = ∞

limit(tan(x),x,pi/2,'right')

ans = − ∞

limit(tan(x),x,pi/2)

ans = NaN

Differential Equations

The Symbolic Math Toolbox can analytically solve systems of “Solve a System of Differential
Equations” on page 3-47 using dsolve.

dy
Solve the first order ODE = − ay.
dx

syms a b y(x)
dsolve(diff(y) == -a*y)

ans = C1 e−a x

Solve the same ODE with the initial condition y(0) = b.

dsolve(diff(y)== -a*y,y(0)==b)

ans = b e−a x

dx dy
Solve the system of coupled first order ODEs = y and = − x.
dt dt

syms x(t) y(t)


z = dsolve(diff(x) == y, diff(y) == -x);
disp([z.x;z.y])

C1 cos t + C2 sin t
C2 cos t − C1 sin t

1-50
Computational Mathematics in Symbolic Math Toolbox

Linear Algebra

The Symbolic Math Toolbox can work with symbolic vectors and matrices. It can compute eig of
symbolic matrices.

a b
Perform matrix multiplicationAx = b where A = and x = x1, x2]
c d

syms a b c d
syms x1 x2
x = [x1; x2];
A = [a b ; c d];
b = A*x

b =
a x1 + b x2
c x1 + d x2

Find the determinant of A.

det(A)

ans = a d − b c

Find the eigenvalues of A.

lambda = eig(A)

lambda =
2
a d a2 − 2 a d + d + 4 b c
+ −
2 2 2
2
a d a2 − 2 a d + d + 4 b c
+ +
2 2 2

Graphics

The Symbolic Math Toolbox supports analytical plotting in 2D and 3D.

fplot(tan(x))

1-51
1 Getting Started

Plot the parametric curve x(t) = t * sin(5t) and y(t) = t * cos(5t).

syms t
x = t*sin(5*t);
y = t*cos(5*t);
fplot(x, y)
grid on

1-52
Computational Mathematics in Symbolic Math Toolbox

|t| |t|
Plot the 3D parametric curve x(t) = e 10 sin(5 | t | ), y(t) = e 10 cos(5 | t | ) and z(t) = t from [-10,10]
with a dashed red line.

syms t
xt = exp(abs(t)/10).*sin(5*abs(t));
yt = exp(abs(t)/10).*cos(5*abs(t));
zt = t;
h = fplot3(xt,yt,zt, [-10,10],'--r');

1-53
1 Getting Started

Plot the 3D surface f (x, y) = sin(x) + cos(y).

syms x y
fsurf(sin(x) + cos(y))

1-54
Computational Mathematics in Symbolic Math Toolbox

Plot the 2D contours of the same surface.

fcontour(sin(x) + cos(y))

1-55
1 Getting Started

1-56
Next Step Suggestions for Symbolic Workflows in Live Editor

Next Step Suggestions for Symbolic Workflows in Live Editor

Starting in R2021b, when you run code that generates a symbolic output in the Live Editor, Live
Editor provides a context menu with next step suggestions that are specific to the output. To open the
suggestion menu, you can point your mouse to the symbolic output and click the three-dot icon , or
you can right-click the symbolic output. When reopening your symbolic workflow live script, run the
code again to get the next step suggestions.

Starting in R2023b, you can also use keyboard shortcuts to navigate to the next step suggestions
after you run your code. To move between code and output in the Live Editor, use the Up/Down
Arrow when the output is inline, or use Ctrl+Shift+O (on macOS systems, use Option+Command
+O instead) when the output is on the right. Activate the symbolic output by pressing the Return
key. Use the shortcut Shift+F10 to open the suggestion menus.

Using these suggestion menus, you can insert and execute function calls or Live Editor tasks into live
scripts. Typical uses of these suggestion menus include:

• Evaluate and convert symbolic expressions to numeric values.


• Simplify and manipulate, or solve symbolic math equations.
• Plot symbolic expressions.
• Perform matrix and vector operations, such as finding the inverse and determinant of a matrix,
and finding the Jacobian and curl of a vector.
• Perform calculus functions, such as differentiation, integration, transforms, and solving
differential equations.
• Convert between units of measurement and verify unit dimensions.

For example, in a new live script, create a symbolic expression.

expr = (pi + sym(2))^2

2
expr = π + 2

Click Run to see the result, which is a symbolic output. When you first run code that generates a
symbolic output, Live Editor shows the three-dot icon for suggested next steps with a pop-up
notification. You can also point to the symbolic output to bring up the three-dot icon. To suppress the
pop-up notification in the rest of your workflow, select Don't show again.

Click the three-dot icon located to the right of the output to bring up the suggestion menu. When
you point to a menu item, Live Editor gives you a preview of what happens when you select the menu

1-57
1 Getting Started

item. For instance, if you point to Approximate numerically, you see the new line of code it
suggests.

Select Approximate numerically to add the suggested new line of code. Live Editor inserts the vpa
function into the code region and automatically runs the current section to evaluate the expression
numerically.

var = vpa(expr)

var = 26.435975015448531572685064532994

As another example, create a symbolic equation. Run a live script to generate the symbolic output.
Solve the equation numerically using symbolic suggestions for next steps.

syms x a
eqn = (2*x^2 + a)/(x + 1) == 3

eqn =
2 x2 + a
=3
x+1

To open the suggestion menu, you can also right-click the symbolic output. Select Solving equations
> Solve equation numerically.

1-58
Next Step Suggestions for Symbolic Workflows in Live Editor

When you click the Solve equation numerically suggestion, Live Editor inserts the vpasolve
function into the code region. Live Editor then automatically runs the current section to solve the
equation numerically.

var2 = vpasolve(eqn,x)

var2 =
0.75 − 0.25 33.0 − 8.0 a
0.25 33.0 − 8.0 a + 0.75

The following sections provide more examples showing how to use the interactive suggestion menus
in symbolic workflows.

Simplify Symbolic Expression

Create a symbolic expression that contains exponential functions and imaginary numbers. Run the
following code to generate the symbolic output.

syms x
expr = 1i*(exp(-1i*x) - exp(1i*x))/(exp(-1i*x) + exp(1i*x))

expr =
e−x i i − ex i i
e−x i + ex i

To simplify the expression, right-click the symbolic output and select Rewriting and simplifying
expressions > Simplify expression.

1-59
1 Getting Started

Live Editor inserts and applies the Simplify Symbolic Expression live task to interactively simplify
or rearrange symbolic expressions. Change the computational effort to Medium to get a simpler
result.

1-60
Next Step Suggestions for Symbolic Workflows in Live Editor

Substitute Coefficients and Solve Quadratic Equation

Create a quadratic equation with coefficients a, b, and c. Run the following code to generate the
symbolic output.

syms a b c x
eqn = a*x^2 + b*x + c == 0

eqn = a x2 + b x + c = 0

To substitute the coefficients in the equation, right-click the output and select Substitute variables.

Live Editor inserts the subs function to substitute the coefficients and variables in the equations. For
the subs function, Live Editor does not run the function automatically. To substitute a = 3, b = 2, and
c = 0, change the second and third arguments of the subs function to [a,b,c] and [3,2,0]. Run
the Live Editor section afterwards to apply the subs function.

var3 = subs(eqn,[a,b,c],[3,2,0])

var3 = 3 x2 + 2 x = 0

To solve the quadratic equation, right-click the output and select Solve equation analytically.

1-61
1 Getting Started

Live Editor inserts and applies the Solve Symbolic Equation live task to interactively find analytic
solutions of symbolic equations.

1-62
Next Step Suggestions for Symbolic Workflows in Live Editor

Plot Explicit and Implicit Functions

Create three symbolic variables x, y, and z and a sinusoidal function. Run the following code to
generate the symbolic output.

syms x y z
f = sin(2*x)

f = sin 2 x

To plot the sinusoidal function, right-click the output and select Plotting functions > Plot function.

1-63
1 Getting Started

Live Editor plots the sinusoidal function using fplot.

fplot(f)

1-64
Next Step Suggestions for Symbolic Workflows in Live Editor

Next, create an equation that represents a hyperbola. Run the following code to generate the
symbolic output.

eqn = x^2 - y^2 == 1

eqn = x2 − y2 = 1

To plot the sinusoidal function, right-click the output and select Plotting functions > Plot implicit
equation in 2-D.

1-65
1 Getting Started

Live Editor plots the hyperbola using fimplicit.

fimplicit(eqn)

1-66
Next Step Suggestions for Symbolic Workflows in Live Editor

Next, create a symbolic function that represents a torus. Run the following code to generate the
symbolic output.

f(x,y,z) = (x^2 + y^2 + z^2 + 3^2 - 2^2)^2 - 4*3^2*(x^2+y^2)

2
f(x, y, z) = x2 + y2 + z2 + 5 − 36 x2 − 36 y2

To plot the torus, right-click the output and select Plot implicit equation in 3-D.

1-67
1 Getting Started

Live Editor plots the torus using fimplicit3.

fimplicit3(f)

1-68
Next Step Suggestions for Symbolic Workflows in Live Editor

Apply Matrix Functions

Create three symbolic variables x, y, and z and a symbolic matrix. Run the following code to generate
the symbolic output.

syms x y z
M1 = sym([x^2 + a, x; y + 2, 3*y^2])

M1 =
x2 + a x
y + 2 3 y2

To invert the matrix, right-click the output and select Applying matrix functions > Invert matrix.
Note that the Applying matrix functions > Invert matrix suggestion is available only if the
symbolic output is a symbolic matrix.

1-69
1 Getting Started

Live Editor inserts and applies the inv function to invert the matrix.

var4 = inv(M1)

var4 =
3 y2 x

σ1 σ1

y+2 x2 + a

σ1 σ1

where

σ1 = −3 x2 y2 + x y + 2 x − 3 a y2

Next, create a 1-by-3 symbolic vector. Run the following code to generate the symbolic output.

M2 = sym([x*y*z, y^2, x + z])

M2 = x y z y2 x + z

To compute the Jacobian of the vector, right-click the output and select Applying matrix functions
> Compute Jacobian matrix of vector. Note that the Applying matrix functions > Compute
Jacobian matrix of vector suggestion is available only if the symbolic output is a symbolic vector.

1-70
Next Step Suggestions for Symbolic Workflows in Live Editor

Live Editor inserts and applies the jacobian function to compute the Jacobian of the vector.

var5 = jacobian(M2)

var5 =
yz xz xy
0 2y 0
1 0 1

Next, create another 1-by-3 symbolic vector. Run the following code to generate the symbolic output.

M3 = sym([x^2*y, 2*x, z])

M3 = x2 y 2 x z

To compute the curl of the vector, right-click the output and select Applying matrix functions >
Compute curl of vector field.

1-71
1 Getting Started

Live Editor inserts and applies the curl function to compute the curl of the vector.

var6 = curl(M3)

var6 =
0
0
2 − x2

Solve Differential Equation, Compute Integral Transform, and Find Poles

Create a second-order differential equation. Run the following code to generate the symbolic output.

syms f(x) s
eqn = diff(f,x,x) == -9*f

eqn(x) =
∂2
f x = −9 f x
∂x2

To solve the differential equation, right-click the output and select Solve differential equation. Note
that the Solve differential equation suggestion is available only if the symbolic output is a
differential equation.

1-72
Next Step Suggestions for Symbolic Workflows in Live Editor

Live Editor inserts and applies the dsolve function to solve the differential equation.

var7 = dsolve(eqn)

var7 = C1 cos 3 x − C2 sin 3 x

Next, find the Laplace transform of the solution. Right-click the output of dsolve and select
Computing integral transforms > Compute Laplace transform.

1-73
1 Getting Started

Live Editor inserts and applies the laplace function to compute the Laplace transform.

var8 = laplace(var7)

var8 =
C1 s 3 C2
− 2
s2 + 9 s +9

Finally, find the poles of the Laplace transform. Right-click the output of the Laplace transform and
select Applying calculus functions > Compute poles of function.

1-74
Next Step Suggestions for Symbolic Workflows in Live Editor

Live Editor inserts and applies the poles function to compute the poles.

var9 = poles(var8,s)

var9 =
−3 i
3 i

Convert Units and Check Consistency of Units

Create a ratio of two lengths with different units. Run the following code to generate the symbolic
output.

u = symunit;
ratio = (7*u.mi)/(420*u.ft)

ratio =
1 mi
60 ft

Convert the units to the meter-gram-second system. Right-click the output and select Applying
physical unit functions > Convert units. Note that the Applying physical unit functions
suggestion is available only if the symbolic output contains symbolic units.

1-75
1 Getting Started

Live Editor inserts and applies the unitConvert function to convert the units to the meter-gram-
second system.
var10 = unitConvert(ratio,[symunit('m'),symunit('g'),symunit('s')])

var10 = 88

Next, create two symbolic expressions x and y that describe the x- and y-coordinates of a moving
projectile. Create a symbolic equation r that compares the units of x and y to the length units m and
ft. Run the following code to generate the symbolic output.
syms theta ts x y r
g = 9.81*u.m/u.s^2;
v = 10*u.m/u.s;
t = ts*u.s;
x = v*cos(theta)*t;
y = v*sin(theta)*t + (-g*t^2)/2;
r = [x == u.m y == u.ft]

r =
981 ts2
10 ts cos θ m = m 10 ts sin θ m − m = ft
200

Check the consistency of units in r. Right-click the output and select Applying physical unit
functions > Check consistency of units.

1-76
Next Step Suggestions for Symbolic Workflows in Live Editor

Live Editor inserts and applies the checkUnits function to check the consistency and compatibility
of the units in r.

The checkUnits function returns a structure containing the fields Consistent and Compatible.
The Consistent field returns logical 1(true) if all terms in r have the same dimension and same
unit with a conversion factor of 1. The Compatible field returns logical 1(true) if all terms have
the same dimension, but not necessarily the same unit.

var11 = checkUnits(r)

var11 = struct with fields:


Consistent: [1 0]
Compatible: [1 1]

1-77
2

Symbolic Computations in MATLAB

• “Find Symbolic Variables in Expressions, Functions, and Matrices” on page 2-2


• “Choose syms or sym Function” on page 2-4
• “Change Output Format of Symbolic and Variable-Precision Arithmetic” on page 2-8
• “Change Output Display Format of Symbolic Results in the Live Editor” on page 2-11
• “Add Subscripts, Superscripts, and Accents to Symbolic Variables in the Live Editor”
on page 2-14
• “Copy and Paste Symbolic Output in Live Editor” on page 2-18
• “Check Symbolic Equations, Inequalities, and Conditional Statements” on page 2-23
• “Numeric to Symbolic Conversion” on page 2-29
• “Choose Numeric or Symbolic Arithmetic” on page 2-32
• “Increase Precision of Numeric Calculations” on page 2-36
• “Compute Binomial Coefficients Exactly” on page 2-38
• “Find Almost Integers with High-Precision Arithmetic” on page 2-41
• “Decimal Digits of PI” on page 2-45
• “Units of Measurement Tutorial” on page 2-47
• “Unit Conversions and Unit Systems” on page 2-53
• “Units and Unit Systems List” on page 2-60
• “Units in Physics Calculations” on page 2-74
• “The Physics of the Damped Harmonic Oscillator” on page 2-78
• “Evaluating the Average Power Delivered by a Wind Turbine” on page 2-88
• “Developing an Algorithm for Undistorting an Image” on page 2-93
• “Electric Dipole Moment and Radiation Power” on page 2-99
• “Validate Simulink Model Using Symbolic Math Toolbox” on page 2-102
2 Symbolic Computations in MATLAB

Find Symbolic Variables in Expressions, Functions, and


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 =
[ b, t]

Notice that the first two variables in this case are not a and b. When you call symvar with two
arguments, it finds symbolic variables by their proximity to x before sorting them alphabetically.

When you call symvar on a symbolic function, symvar returns the function inputs before other
variables.
syms x y w z
f(w, z) = x*w + y*z;
symvar(f)

ans =
[ w, z, x, y]

When called with two arguments for symbolic functions, symvar also follows this behavior.
symvar(f, 2)

ans =
[ w, z]

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:

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

syms s t
f = s + t;
symvar(f, 1)

ans =
t

syms sx tx
f = sx + tx;
symvar(f, 1)

ans =
tx

For more information on choosing the default symbolic variable, see symvar.

2-3
2 Symbolic Computations in MATLAB

Choose syms or sym Function

In Symbolic Math Toolbox™, you can create symbolic objects by using either syms or sym. These two
functions are conceptually different.

• The syms function creates a symbolic object that is automatically assigned to a MATLAB®
variable with the same name.
• The sym function refers to a symbolic object that can be assigned to a MATLAB variable with the
same name or a different name.

The following examples discuss the differences between the syms and sym functions. For more
examples on the use cases of each function, see syms or sym.

Assign Symbolic Variables to MATLAB Variables

The syms function creates a variable dynamically. For example, the command syms x creates the
symbolic variable x and automatically assigns it to a MATLAB variable with the same name.
syms x
x

x = x

You can then use the variable x in the MATLAB workspace for symbolic workflow, such as finding the
roots of a polynomial.
f = x^2 + x - 6

f = x2 + x − 6

x0 = solve(f)

x0 =
−3
2

The sym function refers to a symbolic variable, which you can then assign to a MATLAB variable with
a different name. For example, the command f1 = sym('x') refers to the symbolic variable x and
assigns it to the MATLAB variable f1.
clear
f1 = sym('x')

f1 = x

You can then use the variable f1 in the MATLAB workspace for symbolic workflow, such as finding
the zeros of a sine function.
f2 = sin(f1)

f2 = sin x

[solx,parameters,conditions] = solve(f2,f1,'ReturnConditions',true)

solx = π k

parameters = k

2-4
Choose syms or sym Function

conditions = k ∈ ℤ

Create Symbolic Number

Use the syms function to create a symbolic variable x and automatically assign it to a MATLAB
variable x. When you assign a number to the MATLAB variable x, the number is represented in
double-precision and this assignment overwrites the previous assignment to a symbolic variable. The
class of x becomes double.

syms x
x = 1/33

x = 0.0303

class(x)

ans =
'double'

Use the sym function to refer to an exact symbolic number without floating-point approximation. You
can then assign this number to the MATLAB variable x. The class of x is sym.

x = sym('1/33')

x =
1
33

class(x)

ans =
'sym'

Create Symbolic Variable with Assumptions

When you create a symbolic variable with an assumption, MATLAB stores the symbolic variable and
its assumption separately.

Use syms to create a symbolic variable that is assigned to a MATLAB variable with the same name.
You get a fresh symbolic variable with no assumptions. If you declare a variable using syms, existing
assumptions are cleared.

syms x positive
syms x
assumptions

ans =

Empty sym: 1-by-0

Use sym to refer to an existing symbolic variable. If this symbolic variable was used in your MATLAB
session before, then sym refers to it and its current assumption. If it was not used before, then sym
creates it with no assumptions.

syms x positive
x = sym('x');
assumptions

2-5
2 Symbolic Computations in MATLAB

ans = 0 < x

Create Many Symbolic Variables

To create many symbolic variables simultaneously, using the syms function is more convenient. You
can create multiple variables in one line of code.
syms a b c

When you use sym, you have to declare MATLAB variables one by one and refer them to the
corresponding symbolic variables.
a = sym('a');
b = sym('b');
c = sym('c');

Create Array of Symbolic Variables

To declare a symbolic array that contains symbolic variables as its elements, you can use either syms
or sym.

The command syms a [1 3] creates a 1-by-3 symbolic array a and the symbolic variables a1, a2,
and a3 in the workspace. The symbolic variables a1, a2, and a3 are automatically assigned to the
symbolic array a.
clear
syms a [1 3]
a

a = a1 a2 a3

whos

Name Size Bytes Class Attributes

a 1x3 8 sym
a1 1x1 8 sym
a2 1x1 8 sym
a3 1x1 8 sym

The command a = sym('a',[1 3]) refers to the symbolic variables a1, a2, and a3, which are
assigned to the symbolic array a in the workspace. The elements a1, a2, and a3 are not created in
the workspace.
clear
a = sym('a',[1 3])

a = a1 a2 a3

whos

Name Size Bytes Class Attributes

a 1x3 8 sym

Create Symbolic Variable in Parallel For Loop

To create a symbolic variable in each worker for parallel computation, use sym. For example, you can
create a symbolic variable k in a parfor loop that performs sums of series using symsum.

2-6
Choose syms or sym Function

S = zeros(1,10);
parfor i = 1:10
k = sym('k');
S(i) = symsum(1/k^i,k,1,Inf);
end

Starting parallel pool (parpool) using the 'Processes' profile ...


Connected to the parallel pool (number of workers: 6).

You cannot use syms to create a symbolic variable in a parfor loop because it modifies the global
state of the workspace.

Create Symbolic Variable in Function

To declare a symbolic variable within a function, use sym. For example, you can explicitly define a
MATLAB variable x in the parent function workspace and refer x to a symbolic variable with the same
name.

function primaryFx
x = sym('x')
function nestedFx
...
end
end

Functions make the workspace static, so you cannot dynamically add variables using syms.

See Also

Related Examples
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Find Symbolic Variables in Expressions, Functions, and Matrices” on page 2-2
• “Use Assumptions on Symbolic Variables” on page 1-41

2-7
2 Symbolic Computations in MATLAB

Change Output Format of Symbolic and Variable-Precision


Arithmetic

Symbolic Math Toolbox™ enables you to perform analytical calculations by using symbolic numbers,
variables, functions, and expressions to represent mathematical objects in their exact form. You can
also use variable-precision arithmetic to specify the significant digits used in symbolic computations.
However, symbolic outputs in their analytical form can be long and complicated. You can change the
display format of symbolic outputs by setting preferences for the toolbox.

This example shows how to:

• Use sym and syms to create symbolic numbers, variables, functions, and expressions to perform
analytical calculations.
• Use digits and vpa to evaluate symbolic objects with variable-precision arithmetic to specified
significant digits.
• Use sympref to set the output display format of symbolic objects to a short, fixed-decimal format
with four digits after the decimal point, without affecting the precision used in symbolic
computations.

If you want to use the results of your symbolic computations in numeric computations using
MATLAB® (without Symbolic Math Toolbox), you can convert symbolic values to numeric values by
using the double and matlabFunction functions.

Symbolic Arithmetic

Symbolic Math Toolbox provides the sym and syms functions to create symbolic objects for symbolic
computations. In symbolic arithmetic, you can perform analytical computations involving numbers
and variables in their exact form, such as 5/11, pi, or x^(1/2).

11
For example, create the number 35
in its exact form by using sym.

a = sqrt(sym(11)/35)

a =
11 35
35

Create a symbolic variable x using syms. Create a symbolic function y(x) that takes the variable x
as an input argument.

syms x
y(x) = a*x^2

y(x) =
11 35 x2
35

Evaluate y for x = sqrt(35).

y_eval = y(sqrt(35))

y_eval = 11 35

2-8
Change Output Format of Symbolic and Variable-Precision Arithmetic

Variable-Precision Arithmetic

To specify the number of significant digits when performing calculations in Symbolic Math Toolbox
with variable-precision arithmetic, you can use the digits and vpa functions.

For example, specify 10 significant digits and evaluate the previous symbolic values and functions to
the specified precision.

digits(10)
a_vpa = vpa(a)

a_vpa = 0.5606119106

y_vpa(x) = vpa(y)

y_vpa(x) = 0.5606119106 x2

y_vpaeval = y_vpa(sqrt(35))

y_vpaeval = 19.62141687

Change Output Display Format

The results of symbolic computations in their analytical form can be long and complicated. To change
the display format of symbolic results, you can use the sympref function. This function sets the
preferences used in symbolic computations.

For example, set the "FloatingPointOutput" preference to true. Then display the values and
functions from the previous symbolic and variable-precision arithmetic examples. The output of all
symbolic calculations are now in the short, fixed-decimal format with four digits after the decimal
point.

sympref("FloatingPointOutput",true);
a

a = 0.5606

a_vpa

a_vpa = 0.5606

y(x) = 0.5606 x2

y_vpa

y_vpa(x) = 0.5606 x2

y_eval

y_eval = 19.6214

y_vpaeval

y_vpaeval = 19.6214

Setting the "FloatingPointOutput" preference affects only the output display format and does not
affect the floating-point precision in symbolic computations. For example, restore the default setting

2-9
2 Symbolic Computations in MATLAB

of the symbolic preference by using sympref("default"). The variables y_eval and y_vpaeval
still contain the exact symbolic arithmetic and 10-digit variable-precision arithmetic, respectively.

sympref("default");
y_eval

y_eval = 11 35

y_vpaeval

y_vpaeval = 19.62141687

Convert Symbolic Values to Numeric Values

You can also convert symbolic values to the default MATLAB double-precision values.

For example, you can use the double function to convert symbolic numbers to double-precision
numbers.

a_num = double(a)

a_num = 0.5606

You can use matlabFunction to generate a MATLAB function that operates on the double data
type from an existing symbolic function.

y_num = matlabFunction(y)

y_num = function_handle with value:


@(x)(sqrt(1.1e+1).*sqrt(3.5e+1).*x.^2)./3.5e+1

Evaluate the generated function y_num for x = sqrt(35).

y_numeval = y_num(sqrt(35))

y_numeval = 19.6214

Setting the "FloatingPointOutput" preference using sympref affects only the output display
format of symbolic results. To change the output display format for MATLAB numeric results, use the
format function.

See Also

Related Examples
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Change Output Display Format of Symbolic Results in the Live Editor” on page 2-11

2-10
Change Output Display Format of Symbolic Results in the Live Editor

Change Output Display Format of Symbolic Results in the Live


Editor

This example shows how to modify the output display format of symbolic results in the MATLAB®
Live Editor by using the sympref function. To demonstrate the use of the function, this example uses
a third-degree polynomial.

Modify Output Order of Third-Degree Polynomial

Create a third-degree polynomial consisting of one variable and three coefficients. Define the variable
and coefficients as symbolic variables by using the syms command.

syms x a b c
f(x) = (a*x^2 + b)*(b*x - a) + c

f(x) = c − a x2 + b a − b x

Symbolic preferences persist through successive MATLAB sessions. Restore all symbolic preferences
to the default values. Expand the polynomial and return the output in the default order.

sympref('default');
poly = expand(f)

2
poly(x) = −a2 x2 + a b x3 − a b + b x + c

The default output format displays the terms of a symbolic polynomial in alphabetical order, without
distinguishing the different symbolic variables in each monomial term.

To change the output order of a polynomial, set the 'PolynomialDisplayStyle' preference. The
'ascend' option sorts the output in an ascending order based on the standard mathematical
notation for polynomials. Here, the variable x with the highest order in a monomial term is displayed
last.

sympref('PolynomialDisplayStyle','ascend');
poly

2
poly(x) = c − a b + b x − a2 x2 + a b x3

Modify Output Display of Polynomial Roots

By default, symbolic results in Live Scripts are typeset in standard mathematical notation, long
expressions are abbreviated, and matrices are set in parentheses (round brackets). You can modify
the output display format by setting the symbolic preferences.

Find the roots or zeros of the third-degree polynomial using solve. In Symbolic Math Toolbox™, the
root function represents the roots of a polynomial.

sols = solve(poly,x)

sols =

2-11
2 Symbolic Computations in MATLAB

root σ1, z, 1
root σ1, z, 2
root σ1, z, 3

where
2
σ1 = a b z3 − a2 z2 + b z − a b + c

To display the results without being abbreviated, set 'AbbreviateOutput' preference to false.

sympref('AbbreviateOutput',false);
sols

sols =
2
root a b z3 − a2 z2 + b z − a b + c, z, 1
2
root a b z3 − a2 z2 + b z − a b + c, z, 2
2
root a b z3 − a2 z2 + b z − a b + c, z, 3

To display the symbolic matrix with square brackets, rather than parentheses, set
'MatrixWithSquareBrackets' preference to true.

sympref('MatrixWithSquareBrackets',true);
sols

sols =
2
root a b z3 − a2 z2 + b z − a b + c, z, 1
2
root a b z3 − a2 z2 + b z − a b + c, z, 2
2
root a b z3 − a2 z2 + b z − a b + c, z, 3

To display the results in ASCII characters instead of in typeset mathematical notation, set
'TypesetOutput' preference to false.

sympref('TypesetOutput',false);
sols

sols =

root(a*b*z^3 - a^2*z^2 + b^2*z - a*b + c, z, 1)


root(a*b*z^3 - a^2*z^2 + b^2*z - a*b + c, z, 2)
root(a*b*z^3 - a^2*z^2 + b^2*z - a*b + c, z, 3)

The preferences you set using sympref persist through your current and future MATLAB sessions.
Restore the symbolic preferences to the default values for the next step.

sympref('default');

Display Floating-Point Output of Symbolic Numbers

Replace the polynomial coefficients with symbolic numbers using subs. The function returns the
solutions without any approximation.

2-12
Change Output Display Format of Symbolic Results in the Live Editor

numSols = subs(sols,[a b c],[sqrt(2) pi 0.001])

numSols =
root σ1, z, 1
root σ1, z, 2
root σ1, z, 3

where

σ1 = 1000 π 2 z3 − 2000 z2 + 1000 z π2 − 1000 π 2 + 1

To display the results in floating-point format, set 'FloatingPointOutput' preference to true.


This option displays symbolic numbers in fixed-decimal format with 4 digits after the decimal point.
For a complex result of class 'sym', this preference affects the real and imaginary parts
independently.

sympref('FloatingPointOutput',true);
numSols

numSols =
0.4501
4.6427e−05 − 1.4904 i
4.6427e−05 + 1.4904 i

The display preferences you set do not affect the computation of symbolic results. You can use the
vpa function to approximate symbolic numbers in floating-point precision with 4 significant digits.

vpaSols = vpa(numSols,4)

vpaSols =
0.4501
−1.4904 i
1.4904 i

Restore the default value of 'FloatingPointOutput' by specifying the 'default' option.

sympref('FloatingPointOutput','default');

See Also

Related Examples
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Change Output Format of Symbolic and Variable-Precision Arithmetic” on page 2-8

2-13
2 Symbolic Computations in MATLAB

Add Subscripts, Superscripts, and Accents to Symbolic


Variables in the Live Editor

Starting in R2019a, MATLAB® Live Editor displays symbolic variables with subscripts, superscripts,
and accents in standard mathematical notation. This example shows how to add subscripts,
superscripts, and accents to symbolic variables in the MATLAB Live Editor.

Add Subscripts and Superscripts

To add subscripts to symbolic variables in live scripts, append the corresponding index to the variable
using one underscore (_). For example, create two symbolic variables with subscripts using syms.
Use these variables in an expression.

syms F_a F_b


Ftot = F_a + F_b

Ftot = Fa + Fb

You can also use sym to create a symbolic variable with a subscript and assign the variable to a
symbolic expression.

Fa = sym("F_a")

Fa = Fa

To add superscripts to symbolic variables, append the corresponding index to the variable using two
underscores (__). For example, create two symbolic variables with superscripts.

syms F__a F__b


Ftot = F__a + F__b

Ftot = Fa + Fb

When you assign symbolic variables to an expression, the symbolic expression is displayed in ASCII
format.

Add Accents

To add accents to symbolic variables in live scripts, append the corresponding suffix to the variable
using an underscore (_). For example, create symbolic variables with one dot and two dots over the
symbol x. Use these variables in an equation.

syms x x_dot x_ddot c m k


eq1 = m*x_ddot - c*x_dot + k*x == 0

eq1 = k x − c ẋ + m ẍ = 0

When you compute the complex conjugate of a symbolic variable with an accent, a bar notation is
added above the variable. For example, find the complex conjugate of x_dot using the conj function.

xConj = conj(x_dot)

xConj = ẋ

2-14
Add Subscripts, Superscripts, and Accents to Symbolic Variables in the Live Editor

This accent list shows the supported accent suffixes and the corresponding display output. The
dagger accent with † symbol is available since R2022b and the degree accent with ° symbol is
available since R2023a.

suffix = ["ast"; "dag"; "deg"; "hat"; "tilde"; ...


"vec"; "bar"; "ubar"; "dot"; "ddot"; "tdot"; ...
"qdot"; "prime"; "dprime"; "tprime"; "qprime"];
accentList = [suffix, sym("x_" + suffix)]

accentList =
ast x*
dag x†
deg x°
hat x
tilde ∼
x
vec x
bar x
ubar x
dot ẋ
ddot ẍ

tdot x

qdot x
prime x′
dprime x′′
tprime x′′′
qprime x′′′′

When you compute the complex conjugate transpose of a matrix containing symbolic variables, a bar
notation is also added above each variable. For example, find the complex conjugate transpose of the
symbolic variables in accentList(:,2) using the ctranspose or ' function.

conjVar = accentList(:,2)'

conjVar =
⃛ ⃛
x* x† x° x ∼
x x x x ẋ ẍ x x x′ x′′ x′′′ x′′′′

When you compute the nonconjugate transpose of a matrix containing symbolic variables, the display
output is unchanged. For example, find the nonconjugate transpose of the symbolic variables in
accentList(:,2) using the transpose or .' function.

nonconjVar = accentList(:,2).'

nonconjVar =
⃛ ⃛
x* x† x° x ∼
x x x x ẋ ẍ x x x′ x′′ x′′′ x′′′′

Add Multiple Subscripts, Superscripts, and Accents

You can create symbolic variables with multiple subscripts, superscripts, and accents. The multiple
suffixes are assigned to the symbolic variables from left to right.

Create symbolic variables with multiple subscripts and superscripts. If you add multiple subscripts
and superscripts, then the input indices are separated with a comma and displayed from left to right.

2-15
2 Symbolic Computations in MATLAB

x1 = sym("x_b_1__a__1")

a, 1
x1 = xb, 1

x2 = sym("x__b_1_a__1")

b, 1
x2 = x1, a

Now create symbolic variables with multiple accents. If you add multiple accents, then the input
accents are assigned from left to right to the closest preceding variable or index.

v1 = sym("v_prime_vec")

v1 =
v′

v2 = sym("v_vec_prime")

v2 = v ′

va = sym("v__a_bar_prime")

va = va′

vb = sym("v_bar__b_prime")

vb = vb′

Adding suffixes to symbolic variables can produce similar output. However, the variables are equal
only if their suffixes are also in the same order. For example, create three symbolic variables that
produce similar output.

syms F_t__a
F1 = F_t__a

F1 = Fta

F2 = sym("F_t__a")

F2 = Fta

F3 = sym("F__a_t")

F3 = Fta

Determine if the symbolic variables are equal to each other using the isequal function.

tf_12 = isequal(F1,F2)

tf_12 = logical
1

tf_23 = isequal(F2,F3)

2-16
Add Subscripts, Superscripts, and Accents to Symbolic Variables in the Live Editor

tf_23 = logical
0

Add Signs to Subscripts and Superscripts

Starting in R2022b, you can also add signs as suffixes when creating symbolic variables. The
supported signs are −, +, ±, and #. This sign list shows the supported sign suffixes and the
corresponding display output.

suffix = ["minus"; "plus"; "plusmn"; "hash"];


signList = [suffix, sym("A_" + suffix)]

signList =
minus A−
plus A+
plusmn A±
hash A#

You can add these signs in combinations with other symbols when creating symbolic variables. To
combine these signs with other subscripts or superscripts, you can use one underscore (_) or two
underscores (__) with other suffixes, respectively. For example:

A1 = sym("A_minus_x_bar")

A1 = A−x

A2 = sym("A__plusmn__c")

A2 = A±c

A3 = sym("A_hash_123")

A3 = A#123

A4 = sym("A_minus_x_plus_y__r__theta")

r, θ
A4 = A−x, +y

See Also

Related Examples
• “Create Symbolic Numbers, Variables, and Expressions” on page 1-3
• “Find Symbolic Variables in Expressions, Functions, and Matrices” on page 2-2
• “Use Assumptions on Symbolic Variables” on page 1-41

2-17
2 Symbolic Computations in MATLAB

Copy and Paste Symbolic Output in Live Editor

This example shows how to copy symbolic output and paste it as MATLAB® code or equation typeset
in the MATLAB Live Editor. To demonstrate this capability, this example uses a cubic (third-degree)
polynomial.

Copy Output and Paste as MATLAB Code

Solve the cubic polynomial x3 + bx + c = 0. The solutions are displayed in terms of the abbreviated
expression σ1.

syms b c x
S = solve(x^3 + b*x + c == 0,x,"MaxDegree",3)

S =
b
σ1 −
3 σ1
b
σ1 3 3 σ + σ1 i
b 1
− −
6 σ1 2 2
b
σ1 3 3 σ + σ1 i
b 1
− +
6 σ1 2 2

where

3 1/3
b c2 c
σ1 = + −
27 4 2

After you run your code, right-click the symbolic output. Select Copy Output to copy the symbolic
expressions that represent the roots of the cubic polynomial.

Starting in R2023b, you can also use keyboard shortcuts to navigate to the symbolic output. To move
between code and output in the Live Editor, use the Up/Down Arrow when the output is inline, or
use Ctrl+Shift+O (on macOS systems, use Option+Command+O instead) when the output is on
the right. Use the shortcut Shift+F10 to open the menu selection to copy output.

2-18
Copy and Paste Symbolic Output in Live Editor

Insert code in the live script and assign the polynomial roots to the variable Sol. Then paste the
output as MATLAB code using Ctrl + V (or right-click and select Paste). Pasting the output as
MATLAB code automatically expands the abbreviated expression.

Sol = [(sqrt(b^3/27 + c^2/4) - c/2)^sym(1/3) - b/(3*(sqrt(b^3/27 + c^2/4) - c/2)^sym(1/3));


b/(6*(sqrt(b^3/27 + c^2/4) - c/2)^sym(1/3)) - (sqrt(b^3/27 + c^2/4) - c/2)^sym(1/3)/2 - (sq
b/(6*(sqrt(b^3/27 + c^2/4) - c/2)^sym(1/3)) - (sqrt(b^3/27 + c^2/4) - c/2)^sym(1/3)/2 + (sq

Sol =

2-19
2 Symbolic Computations in MATLAB

b
σ1 −
3 σ1
b
σ1 3 3 σ + σ1 i
b 1
− −
6 σ1 2 2
b
σ1 3 3 σ + σ1 i
b 1
− +
6 σ1 2 2

where

3 1/3
b c2 c
σ1 = + −
27 4 2

Copy Selected Output and Paste as MATLAB Code

Select the first solution of the cubic polynomial. When selecting a subexpression, you can copy and
paste only the subexpression that is on the right side of the equal sign. Right-click the existing
selection and choose Copy (Ctrl + C) in the context menu.

2-20
Copy and Paste Symbolic Output in Live Editor

Insert code in the live script and assign the first root of the polynomial to the variable S1. Then paste
the output as MATLAB code using Ctrl + V (or right-click and select Paste). Pasting the output as
MATLAB code automatically expands the abbreviated expression.

S1 = (sqrt(b^3/27 + c^2/4) - c/2)^sym(1/3) - b/(3*(sqrt(b^3/27 + c^2/4) - c/2)^sym(1/3))

S1 =
3 1/3
b c2 c b
+ − −
27 4 2 3 1/3
b c2 c
3 27
+ 4
− 2

2-21
2 Symbolic Computations in MATLAB

Copy Selected Output and Paste as Equation Typeset

You can also paste a selection as equation typeset. Select the second solution of the cubic polynomial.
Right-click the selection and choose Copy (Ctrl + C) in the context menu.

Then paste the selection as equation typeset in the live script using Ctrl + V (or right-click and select
Paste). The equation typeset is rendered as an editable equation. Note that when you paste the
output as equation typeset, abbreviated expressions are not expanded.

b
3 + σ1 i
b σ1 3 σ1
6 σ1
− 2
− 2

2-22
Check Symbolic Equations, Inequalities, and Conditional Statements

Check Symbolic Equations, Inequalities, and Conditional


Statements

Symbolic Math Toolbox™ provides several functions to check symbolic equations, inequalities, and
conditional statements that involve symbolic objects. This example discusses the use cases of these
functions:

• Use isequal to check if two symbolic inputs are equal (from a coding perspective).
• Use logical to check if symbolic conditions involving relational operators (such as &, |, >, ~=,
and so on) are true.
• Use isAlways to check if symbolic conditions are always mathematically true.

For more details, the descriptions of these functions are:

• isequal(A,B) checks if A and B are the same size and their contents are equal (from a coding
perspective). isequal is useful only to check equality between two expressions without applying
mathematical transformations and simplifications. isequal returns a scalar logical value 1
(true) if A and B are the same expressions. Otherwise, it returns logical 0 (false). Note that
isequal does not consider NaN (not a number) values as equal. To consider NaN values as equal,
you can use isequaln.
• logical(cond) checks if the symbolic statements in cond hold true without applying
mathematical transformations and simplifications. It also ignores assumptions on symbolic
variables. logical returns a logical array with elements 1 (true) for the elements in cond that
are true and 0 (false) for the elements in cond that are false.
• isAlways(cond) checks if the symbolic statements in cond are always true for all possible
values of the symbolic variables in cond. When verifying cond, isAlways applies mathematical
transformations and simplifications. isAlways also considers all assumptions on the variables in
cond. isAlways returns a logical array with elements 1 (true) for the elements in cond that are
mathematically true and 0 (false) for the elements in cond that are not mathematically true. In
almost all cases, you can use isAlways to check symbolic equalities, inequalities, and conditional
statements.

Check If Expressions Are Equal

isequal(a,b) only checks if a and b have the same contents but does not check if they are
2
mathematically equal. If you use isequal to check different expressions, such as x + 1 and
x2 + 2x + 1, then it returns 0 (false), even though they are mathematically equal.
syms x
tf = isequal((x+1)^2,x^2+2*x+1)

tf = logical
0

2
Expand the expression x + 1 , and use isequal to test if the expanded expression is equal to
x2 + 2x + 1.
expr = expand((x+1)^2)

expr = x2 + 2 x + 1

2-23
2 Symbolic Computations in MATLAB

tf = isequal(expr,x^2+2*x+1)

tf = logical
1

sin x
Next, check if the equation tan x = cos x
is true for all values of x by using isAlways.

tf = isAlways(tan(x) == sin(x)/cos(x))

tf = logical
1

sin x
Test if the expressions tan x and cos x
are equal. The isequal function returns 0 (false) because
the expressions are different, even though they are mathematically equal.
tf = isequal(tan(x),sin(x)/cos(x))

tf = logical
0

Rewrite the expression tan x in terms of sin x and cos x . Test if rewrite correctly rewrites tan x
sin x
as cos x
.

expr = rewrite(tan(x),"sincos")

expr =
sin x
cos x

tf = isequal(expr,sin(x)/cos(x))

tf = logical
1

Check Equation with and without Simplifications

To check an equation that requires simplifications, use isAlways. For example, check the equality of
x + 1 and x2 + 2x + 1 / x + 1 .

syms x
tf = isAlways(x+1 == (x^2+2*x+1)/(x+1))

tf = logical
1

If you use logical to check an equality with different expressions on both sides, then it returns 0
(false).
tf = logical(x+1 == (x^2+2*x+1)/(x+1))

tf = logical
0

2-24
Check Symbolic Equations, Inequalities, and Conditional Statements

Simplify the condition represented by the symbolic equation using simplify. The simplify
function returns the symbolic logical constant symtrue because the equation is always true for all
values of x.

cond = simplify(x+1 == (x^2+2*x+1)/(x+1))

cond = symtrue

Using logical on symtrue converts it to logical 1 (true).

tf = logical(cond)

tf = logical
1

As shown in the previous section, if you use isequal to check expressions that are different, then it
returns 0 (false).

tf = isequal(x+1,(x^2+2*x+1)/(x+1))

tf = logical
0

Simplify the expression x2 + 2x + 1 / x + 1 . Use isequal to check if the simplified expression is


equal to x + 1.

expr = simplify((x^2+2*x+1)/(x+1))

expr = x + 1

tf = isequal(x+1,expr)

tf = logical
1

Check Equation with Assumptions

Check if the equation sin 2nπ = 0 holds true for all integers n. When you create n as a symbolic
variable, Symbolic Math Toolbox treats it as a general complex quantity. To test if the equation holds
true for integers, set an assumption on n and check the equation using isAlways.

syms n
assume(n,"integer")
tf = isAlways(sin(2*n*pi) == 0)

tf = logical
1

Note that logical ignores assumptions on variables. It returns logical 0 (false) in this case.

tf = logical(sin(2*n*pi) == 0)

tf = logical
0

2-25
2 Symbolic Computations in MATLAB

Check Conditions Involving Equations and Inequalities

To check conditions involving equations and inequalities, you can use logical or isAlways.
However, logical does not apply mathematical transformations and simplifications when checking
the conditions.

For example, test the condition 1 < 2 AND exp log x = x. Note that if a condition uses other
functions, such as exp and log, then these functions are evaluated when defining the condition.

syms x
cond1 = 1 < 2 & exp(log(x)) == x

cond1 = x = x

Check this condition by using isAlways.

tf = isAlways(cond1)

tf = logical
1

You can also use logical to check a condition that does not require mathematical transformations
and simplifications.

tf = logical(cond1)

tf = logical
1

Do not use logical to check if a condition holds true when mathematical transformations are
required. For example, logical returns an error when testing the conditional statement
2 2
sin x + cos x = 1 OR x2 > 0. Instead, use isAlways to test this conditional statement.

cond2 = sin(x)^2 + cos(x)^2 == 1 | x^2 > 0

2 2
cond2 = 0 < x2 ∨ cos x + sin x =1

tf = isAlways(cond2)

tf = logical
1

Check Multiple Conditions

To check multiple conditions, you can represent them as a symbolic array.

For example, create two symbolic arrays where each array has three different expressions.

syms x
expr1 = [tan(x); x+1; exp(log(x))]

expr1 =
tan x
x+1
x

2-26
Check Symbolic Equations, Inequalities, and Conditional Statements

expr2 = [sin(x)/cos(x); (x^2+2*x+1)/(x+1); x]

expr2 =
sin x
cos x
x2 + 2 x + 1
x+1
x

To compare these expressions, create a symbolic array of conditional statements using the relational
operator ==.

cond = expr1 == expr2

cond =
sin x
tan x =
cos x
x2 + 2 x + 1
x+1=
x+1
x=x

Check if these multiple conditions are always mathematically true using isAlways. isAlways
returns a 3-by-1 array with logical values 1 (true) because each condition is mathematically true.

tf = isAlways(cond)

tf = 3x1 logical array

1
1
1

Check if these conditions hold true using logical. logical returns a 3-by-1 array, where the first
two elements are 0 (false) because logical does not apply mathematical transformations or
simplifications.

tf = logical(cond)

tf = 3x1 logical array

0
0
1

Check if each corresponding element in the two 3-by-1 symbolic arrays, expr1 and expr2, is equal
using isequal. isequal returns a logical scalar 0 (false) because some of the corresponding
elements are not equal.

tf = isequal(expr1,expr2)

tf = logical
0

Next, simplify the second symbolic array using simplify.

2-27
2 Symbolic Computations in MATLAB

expr2 = simplify(expr2,Steps=10)

expr2 =
tan x
x+1
x

Check if each simplified expression in expr2 is equal to the corresponding expression in expr1 using
logical.

tf = logical(expr1 == expr2)

tf = 3x1 logical array

1
1
1

Check if all simplified expressions in expr2 are equal to expr1 using isequal.

tf = isequal(expr1,expr2)

tf = logical
1

See Also
isequal | logical | isAlways | isequaln

2-28
Numeric to Symbolic Conversion

Numeric to Symbolic Conversion

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

To convert numeric input to symbolic form, use the sym command. By default, sym returns a rational
approximation of a numeric expression.
t = 0.1;
sym(t)

ans =
1
10

1
sym determines that the double-precision value 0.1 approximates the exact symbolic value 10 . In
general, sym tries to correct the round-off error in floating-point inputs to return the exact symbolic
1
p pπ p 2
form. Specifically, sym corrects round-off error in numeric inputs that match the forms q , q , q
,
q q
2 , and 10 , where p and q are modest-sized integers.

For these forms, demonstrate that sym converts floating-point inputs to the exact symbolic form.
1 1
First, numerically approximate 7 , π, and .
2

N = [1/7 pi 1/sqrt(2)]

N = 1×3

0.1429 3.1416 0.7071

Convert the numeric approximations to exact symbolic form. sym corrects the round-off error.
S = sym(N)

S =
1 2
π
7 2

You can force sym to accept the input as is by placing the input in quotes. Demonstrate this behavior
on the previous input 0.142857142857143. The sym function does not convert the input to 1/7.
sym('0.142857142857143')

ans = 0.142857142857143

When you convert large numbers, use quotes to exactly represent them. Demonstrate this behavior
by comparing sym(133333333333333333333) with sym('133333333333333333333').
sym(1333333333333333333)

ans = 1333333333333333248

sym('1333333333333333333')

2-29
2 Symbolic Computations in MATLAB

ans = 1333333333333333333

You can specify the technique used by sym to convert floating-point numbers using the optional
second argument, which can be 'f', 'r', 'e', or 'd'. The default flag is 'r', for rational form.

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.

t = 0.1;
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
e
numeric value by using N ⋅ 2 , 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 1
+
40 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.

sym(t,'d')

ans = 0.10000000000000000555111512312578

Change the number of significant digits by using digits.

2-30
Numeric to Symbolic Conversion

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

ans = 0.1

For further calculations, restore the old value of digits.

digits(digitsOld)

Conversion to Variable Precision

You can create symbolic numbers with variable-precision floating-point arithmetic by using vpa. By
default, vpa calculates values to 32 significant digits.

piVpa = vpa(pi)

piVpa = 3.1415926535897932384626433832795

When you use vpa on a numeric input, such as log(2), the numeric expression is first evaluated to
the MATLAB® default double-precision number that has less than 32 significant digits. Then, vpa is
applied on that double-precision number, which can be less accurate. For more accurate results,
convert numeric expressions to symbolic expressions with sym and then use vpa to evaluate the
results with variable precision. For example, find log(2) with 17 and 20 digits precision.

vpaOnDouble = vpa(log(2))

vpaOnDouble = 0.69314718055994528622676398299518

vpaOnSym_17 = vpa(log(sym(2)),17)

vpaOnSym_17 = 0.69314718055994531

vpaOnSym_20 = vpa(log(sym(2)),20)

vpaOnSym_20 = 0.69314718055994530942

When you convert large numbers, use quotes to exactly represent them.

inaccurateNum = vpa(123456789012345678)

inaccurateNum = 123456789012345680.0

accurateNum = vpa('123456789012345678')

accurateNum = 123456789012345678.0

See Also

More About
• “Conversion Between Symbolic and Numeric”

2-31
2 Symbolic Computations in MATLAB

Choose Numeric or Symbolic Arithmetic


Symbolic Math Toolbox operates on numbers by using either numeric or symbolic arithmetic. In
numeric arithmetic, you represent numbers in floating-point format using either double precision or
variable precision. In symbolic arithmetic, you represent numbers in their exact form. This topic
compares double-precision, variable-precision, and symbolic arithmetic.

Double-Precision Arithmetic
Numeric computations in MATLAB use double-precision arithmetic by default. For example, evaluate
the expressions 10001/1001, π, and 2. The results are converted to double-precision values.

x = 10001/1001
y = pi
z = sqrt(2)

x =
9.9910

y =
3.1416

z =
1.4142

For more information about double-precision arithmetic, see “Floating-Point Numbers”. This
arithmetic is recommended when you do not have Symbolic Math Toolbox or are using functions that
do not accept symbolic input. Otherwise, exact symbolic arithmetic and variable-precision arithmetic
are recommended. To convert a symbolic value to double precision, use the double function.

Variable-Precision Arithmetic
Variable-precision arithmetic using vpa is the recommended approach for numeric calculations in
Symbolic Math Toolbox. You can specify the number of significant digits when performing
calculations with variable-precision arithmetic.

For example, use vpa to evaluate the fraction 10001/1001. By default, vpa evaluates inputs to 32
significant digits. Approximate the fraction 10001/1001 to at least 32 significant digits.

vpa(10001/1001)

ans =
9.991008991008991008991008991009

Approximate the fraction to at least 8 significant digits. Change the number of significant digits by
using the digits function.

digits(8);
vpa(10001/1001)

ans =
9.991009

2-32
Choose Numeric or Symbolic Arithmetic

In variable-precision arithmetic, you can increase the number of significant digits on page 2-36 for
greater precision. Alternatively, you can decrease the number of significant digits on page 3-321 for
faster computations and decreased memory usage.

Symbolic Arithmetic
Symbolic Math Toolbox provides the sym and syms functions to perform exact symbolic computations
on page 1-28. In symbolic arithmetic, you can perform computations involving numbers and variables
in their exact form, such as x/2, 2^(1/2), or pi. The following three examples show several
calculations that are performed in symbolic arithmetic.

Express Irrational Numbers

Use sym to create symbolic numbers. Express the irrational numbers π and 2 in symbolic form.
x = sym(pi)
y = sqrt(sym(2))

x =
pi

y =
2^(1/2)

Perform Calculations with Large Integers

When you declare a number, MATLAB automatically converts the number to double precision. For
example, declare the integer 80435758145817515 as the input argument of sym. The number loses
its accuracy since it is bigger than the largest consecutive integer flintmax in double precision,
which is 2^53.
Z = 80435758145817515
Zinaccurate = sym(80435758145817515)

Z =
8.0436e+16

Zinaccurate =
80435758145817520

To declare a large integer as symbolic number accurately, use a character vector with single
quotation marks as the input argument of sym.
Zaccurate = sym('80435758145817515')

Zaccurate =
80435758145817515

You can then perform calculations with large integers using symbolic arithmetic accurately. For
example, evaluate the sum of the cubes of three large integers.
Z1 = sym('80435758145817515')
Z2 = sym('12602123297335631')
Z3 = sym('-80538738812075974')
Zsum = Z1^3 + Z2^3 + Z3^3

Z1 =
80435758145817515

2-33
2 Symbolic Computations in MATLAB

Z2 =
12602123297335631

Z3 =
-80538738812075974

Zsum =
42

Solve Mathematical Equations

With symbolic arithmetic, you can solve a mathematical equation. For example, solve the quadratic
equation ax2 + bx + c = 0. Use syms to declare the variable x and the coefficients a, b, and c in the
quadratic equation.

syms a b c x
eqn = a*x^2 + b*x + c == 0;

Find the solutions using solve and return them as symbolic expressions.

sols = solve(eqn,x)

sols =
-(b + (b^2 - 4*a*c)^(1/2))/(2*a)
-(b - (b^2 - 4*a*c)^(1/2))/(2*a)

Use subs to substitute symbolic values for the coefficients. Set a = 1, b = 2, and c = 3. Return the
solutions of the quadratic equation as symbolic numbers.

solsSym = subs(sols,[a b c],[1 2 3])

solsSym =
- (8^(1/2)*1i)/2 - 1
(8^(1/2)*1i)/2 - 1

You can then convert the symbolic solutions to floating-point format in double precision or variable
precision.

digits(32);
solsDouble = double(solsSym)
solsVpa = vpa(solsSym)

solsDouble =
-1.0000 - 1.4142i
-1.0000 + 1.4142i

solsVpa =
- 1.0 - 1.4142135623730950488016887242097i
- 1.0 + 1.4142135623730950488016887242097i

Comparisons of Numeric and Symbolic Arithmetic


The table below compares double-precision, variable-precision, and symbolic arithmetic.

2-34
Choose Numeric or Symbolic Arithmetic

Double Precision Variable Precision Symbolic


Example 1: a = pi b = vpa(pi) c = sym(pi)
Evaluate sin(π) sin(pi) sin(b) sin(c)

a = b = c =
3.1416 3.1415926535897932384626433832795
pi
ans = ans = ans =
1.2246e-16 -3.2101083013100396069547145883568e-40
0
Example 2: a = 4/3 digits(16); c = sym(4)/3
Evaluate 1 - 1 - 3*(a - 1) b = vpa(4/3) 1 - 3*(c - 1)
3*(4/3 - 1) 1 - 3*(b - 1)
a = c =
1.3333 b = 4/3
ans = 1.333333333333333 ans =
2.2204e-16 ans = 0
3.308722450212111e-24
Functions Used double vpa sym
digits
Data Type double sym sym
Round-Off Errors Yes, the answer has 16 Yes, the number of digits No, the results are exact.
digits of precision. depends on the precision
used.
Speed Faster Faster, depending on the Slowest
precision used
Memory Usage Least Variable, depending on Greatest
the precision used

See Also

More About
• “Numeric to Symbolic Conversion” on page 2-29
• “Increase Precision of Numeric Calculations” on page 2-36
• “Find Almost Integers with High-Precision Arithmetic” on page 2-41

2-35
2 Symbolic Computations in MATLAB

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 Numeric or Symbolic Arithmetic” on page 2-32. You can set a
higher precision by using the digits function.

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

vpa(1/3) + 1/2

ans =
0.83333333333333333333333333333333

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

Increase the precision to 50 digits by using digits and save the old value of digits in digitsOld.
Repeat the sum.

digitsOld = digits(50);
sum50 = vpa(1/3) + 1/2

sum50 =
0.83333333333333333333333333333333333333333333333333

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

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.

2-36
Increase Precision of Numeric Calculations

digitsOld = digits(500);
vpa(pi)
digits(digitsOld)

ans =
3.1415926535897932384626433832795028841971693993751058209749
445923078164062862089986280348253421170679821480865132823066
470938446095505822317253594081284811174502841027019385211055
596446229489549303819644288109756659334461284756482337867831
652712019091456485669234603486104543266482133936072602491412
737245870066063155881748815209209628292540917153643678925903
600113305305488204665213841469519415116094330572703657595919
530921861173819326117931051185480744623799627495673518857527
248912279381830119491

digits and vpa control the number of significant decimal digits. For example, approximating 1/111
with four-digit accuracy returns six digits after the decimal point because the first two digits are
zeros.

vpa(1/111,4)

ans =
0.009009

Note If you want to increase performance by decreasing precision, see “Increase Speed by Reducing
Precision” on page 3-321.

2-37
2 Symbolic Computations in MATLAB

Compute Binomial Coefficients Exactly

This example shows how to get precise values for binomial coefficients and find probabilities in coin-
tossing experiments using the Symbolic Math Toolbox™.

Define the symbolic function, P(n,k), that computes the probability for the heads to come up exactly
k times out of n tosses.
syms P(n,k)
P(n,k) = nchoosek(n,k)/2^n

P(n, k) =
n
k
n
2

Suppose you toss a coin 2000 times. The probability that heads comes up in half of the tosses is P(n,
n/2), where n = 2000. The result is a rational expression with large numbers in both the numerator
and denominator. Symbolic Math Toolbox returns the exact result.
n = 2000;
central = P(n, n/2)

central =
3200236917171077678648691410907539131869413887470932865344347871362106540940755868482707803410328
17939542113660226941138018768401281000348714095135862507463167762902597834255786154010304473695410

Approximate this rational number with 10-digit accuracy using digits and vpa.
previous_digits = digits(10);
vpa(central)

ans = 0.01783901115

Compute the probability that the number of "heads" differs from the expected value by no more than
two standard deviations.
sigma = sqrt(n/4);
withinTwoSigma = symsum(P(n, k), k, ceil(n/2 - 2*sigma), floor(n/2 + 2*sigma))

2-38
Compute Binomial Coefficients Exactly

withinTwoSigma =
13683524663950565202894406832034749167239195904700934509667499858152527897032069211850781661943643
14351633690928181552910415014721024800278971276108690005970534210322078267404628923208243578956328

Approximate the result with a floating-point number.

vpa(withinTwoSigma)

ans = 0.9534471795

Compare this result with the following two estimates derived from the cumulative distribution
function (cdf) of the normal distribution. It turns out that taking the midpoint between the first
integer outside and the first integer inside the two-sigma interval gives a more precise result than
using the two-sigma interval itself.

syms cdf(x)
cdf(x) = 1/2 * (1 + erf((x - n/2)/sqrt(sym(n/2))))

cdf(x) =
10 x − 1000
erf 100 1
+
2 2

estimate1 = vpa(cdf(n/2 + 2*sigma) - cdf(n/2 - 2*sigma))

estimate1 = 0.9544997361

estimate2 = vpa(cdf(floor(n/2 + 2*sigma) + 1/2) - ...


cdf(ceil(n/2 - 2*sigma) - 1/2))

estimate2 = 0.9534201342

error1 = vpa(estimate1 - withinTwoSigma)

error1 = 0.001052556595

error2 = vpa(estimate2 - withinTwoSigma)

error2 = −0.00002704525904

Restore the default precision for floating-point computations.

digits(previous_digits);

Plot this distribution for k within the 2σ-interval. The plot is a Gaussian curve.

k = n/2 + (-2*sigma:2*sigma);
plot(k, P(n,k), '-+');
title('2000 coin tosses');
xlabel('Number of heads');
ylabel('Probability');

2-39
2 Symbolic Computations in MATLAB

2-40
Find Almost Integers with High-Precision Arithmetic

Find Almost Integers with High-Precision Arithmetic

Algorithms for finding integer relations [1], such as the PSLQ algorithm, require high-precision
arithmetic to produce accurate results. The higher the precision of the inputs to the algorithm, the
greater the level of confidence that the algorithm can find an integer relation that is not just a
numerical artifact. The PSLQ algorithm can encounter false positives, such as those caused by almost
integers.

This example shows how to find almost integers, or numbers that are very close to integers, using
variable-precision arithmetic in Symbolic Math Toolbox™. This example searches for almost integers
(or near-integers) that have the form exp π n or exp π n for the integers n = 1, . . . , 200.

First, consider a well-known example of an almost integer [2] that is the real number exp π 163 .
Create this real number as an exact symbolic number.

r = exp(pi*sqrt(sym(163)))

r = eπ 163

Evaluate this number with variable-precision arithmetic using vpa. By default, vpa calculates values
to 32 significant digits.

vpa(r)

ans = 262537412640768743.99999999999925

You can change the number of significant digits to a higher precision by using digits. Evaluate the
same number to 40 significant digits.

digits(40)
vpa(r)

ans = 262537412640768743.9999999999992500725972

This number is very close to an integer. Find the difference between this real number and its nearest
integer. Use vpa to evaluate this result to 40 significant digits.

dr = vpa(round(r)-r)

dr = 0.0000000000007499274028018143151532171817442410122968

Next, search for almost integers that have the form exp π n for the integers n = 1, . . . , 200. Create
these numbers as exact symbolic numbers.

A = exp(pi*sqrt(sym(1:200)));

Set the number of significant digits to the number of digits in the integer part of exp π 200 plus 20
decimal points.

d = log10(A(end));
digits(ceil(d) + 20)

Evaluate the differences between this series of numbers and their nearest integers. Find the almost
integers with rounding errors that are less than 0.0001. Show the results in exact symbolic form.

2-41
2 Symbolic Computations in MATLAB

B = vpa(round(A)-A);
A_nearint = A(abs(B)<0.0001)'

A_nearint =
eπ 37
eπ 58
eπ 67
eπ 163

Evaluate the almost integers with a precision of at least 20 decimal points.

A_nearint = vpa(A_nearint)

A_nearint =
199148647.9999780465518567665009238753359
24591257751.99999982221324146957619235527
147197952743.9999986624542245068292613126
262537412640768743.9999999999992500725972

Plot the histogram of the differences to show their distribution. The distribution has many
occurrences of differences that are close to zero, where the form exp π n is an almost integer.

histogram(double(B),40)

2-42
Find Almost Integers with High-Precision Arithmetic

Next, search for almost integers that have the form exp π n for the integers n = 1, . . . , 200. Create
these numbers as exact symbolic numbers.
A = exp(sym(pi)*1:200);

Set the number of significant digits to the number of digits in the integer part of exp π ⋅ 200 plus 20
decimal points.
d = log10(A(end));
digits(ceil(d) + 20)

Evaluate the differences between this series of numbers and their nearest integers. Find the almost
integers with rounding errors that are less than 0.0001. The result is an empty sym array, which
means there is no almost integer that satisfies this condition.
B = vpa(round(A)-A);
A_nearint = A(abs(B)<0.0001)

A_nearint =

Empty sym: 1-by-0

Plot the histogram of the differences. The histogram is relatively evenly distributed and shows that
the form exp π n does not have many occurrences of almost integers. For this specific example, there
is no almost integer with a rounding error that is less than 0.0001.
histogram(double(B),40)

2-43
2 Symbolic Computations in MATLAB

Finally, restore the default precision of 32 significant digits for further calculations.

digits(32)

References

[1] “Integer Relation Algorithm.” In Wikipedia, April 9, 2022. https://en.wikipedia.org/w/index.php?


title=Integer_relation_algorithm&oldid=1081697113.

[2] “Almost Integer.” In Wikipedia, December 4, 2021. https://en.wikipedia.org/w/index.php?


title=Almost_integer&oldid=1058543590.

See Also
sym | vpa | digits

More About
• “Choose Numeric or Symbolic Arithmetic” on page 2-32
• “Numeric to Symbolic Conversion” on page 2-29
• “Increase Precision of Numeric Calculations” on page 2-36

2-44
Decimal Digits of PI

Decimal Digits of PI

This example shows how to use variable-precision arithmetic to investigate the decimal digits of pi
using Symbolic Math Toolbox™.

π≈3
. 141592653589793238462643383279502884197169399375105820974944592307816406286208998628034
..
.

Joke: What do you get when you take the sun and divide its circumference by its diameter?

Answer: π in the sky!

It is an old game to search for one's birthday or telephone number in the decimal digits of π. The
precision of the built-in datatypes suffices to obtain a few digits only:

num2str(pi, 100000)

ans =
'3.141592653589793115997963468544185161590576171875'

The function vpa uses variable-precision to convert symbolic expressions into symbolic floating-point
numbers. Convert pi to a floating-point number using vpa. Increase the precision of vpa using
digits.

digits(5000);
a = vpa(pi)

a = 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117

To convert a variable-precision number into a string, use the function char.

c = char(a);

Search for your phone number in the digits of pi.

strfind(c, '1185480')

ans = 447

It is common belief that all digits occur asymptotically equally often in the decimal expansion of π,
but no proof exists yet. Find the decimal point:

pos = strfind(c, '.')

pos = 2

Convert the decimal digits to numbers, and plot a histogram of their frequency:

d = arrayfun(@str2num, c(pos+1:end));
histogram(d, 10);
title('Frequency of the decimal digits of \pi');

2-45
2 Symbolic Computations in MATLAB

2-46
Units of Measurement Tutorial

Units of Measurement Tutorial

Use units of measurement with Symbolic Math Toolbox™. This page shows how to define units, use
units in equations (including differential equations), and verify the dimensions of expressions.

Define and Convert Units

Load units by using symunit.


u = symunit;

Specify a unit by using u.unit. For example, specify a distance of 5 meters, a weight of 50
kilograms, and a speed of 10 kilometers per hour.
d = 5*u.m

d = 5m

w = 50*u.kg

w = 50 kg

s = 10*u.km/u.hr

s =
km
10
h

You can use tab expansion to find names of units. Type u., press Tab, and continue typing.

Units are treated like other symbolic expressions and can be used in any standard operation or
function. Units are not automatically simplified, which provides flexibility. Common alternate names
for units are supported. Plurals are not supported.

Add 500 meters and 2 kilometers. The resulting distance is not automatically simplified.
d = 500*u.m + 2*u.km

d = 2 km + 500 m

Simplify d by using simplify. The simplify function chooses the unit to return.
d = simplify(d)

d = 2500 m

Convert d to a specific unit by using unitConvert. Convert d to kilometers.


d = unitConvert(d,u.km)

d =
5
km
2

For more unit conversion and unit system options, see “Unit Conversions and Unit Systems” on page
2-53.

Find the speed if the distance d is traveled in 50 seconds. The result has the correct units.

2-47
2 Symbolic Computations in MATLAB

t = 50*u.s;
s = d/t

s =
1 km
20 s

Use Temperature Units in Absolute or Difference Forms

By default, temperatures are assumed to represent differences and not absolute measurements. For
example, 5*u.Celsius is assumed to represent a temperature difference of 5 degrees Celsius. This
assumption allows arithmetical operations on temperature values.

To represent absolute temperatures, use kelvin, so that you do not have to distinguish an absolute
temperature from a temperature difference.

Convert 23 degrees Celsius to kelvin, treating the temperature first as a temperature difference and
then as an absolute temperature.

u = symunit;
T = 23*u.Celsius;
diffK = unitConvert(T,u.K)

diffK = 23 K

absK = unitConvert(T,u.K,'Temperature','absolute')

absK =
5923
K
20

Because the value 0 times a symbolic unit is returned as a dimensionless 0 when using symunit, you
can use a cell array to represent 0 degrees.

For example, convert 0 degrees Celsius to degrees Fahrenheit.

TC = {0,u.Celsius};
TF = unitConvert(TC,u.Fahrenheit,'Temperature','Absolute')

TF = 32 °F

Verify Dimensions

In longer expressions, visually checking for units is difficult. You can check the dimensions of
expressions automatically by verifying the dimensions of an equation.

First, define the kinematic equation v2 = v02 + 2as, where v represents velocity, a represents
acceleration, and s represents distance. Assume s is in kilometers and all other units are in SI base
units. To demonstrate dimension checking, the units of a are intentionally set incorrectly.

syms v v0 a s
u = symunit;
eqn = (v*u.m/u.s)^2 == (v0*u.m/u.s)^2 + 2*a*u.m/u.s*s*u.km

eqn =
m2 m2 km m
v2 2 = v02 2 + 2 a s
s s s

2-48
Units of Measurement Tutorial

Observe the units that appear in eqn by using findUnits. The returned units show that both
kilometers and meters are used to represent distance.

findUnits(eqn)

ans = km m s

Check if the units have the same dimensions (such as length or time) by using checkUnits with the
'Compatible' input. MATLAB® assumes symbolic variables are dimensionless. checkUnits
returns logical 0 (false), meaning the units are incompatible and not of the same physical
dimensions.

checkUnits(eqn,'Compatible')

ans = logical
0

Looking at eqn, the acceleration a has incorrect units. Correct the units and recheck for compatibility
again. eqn now has compatible units.

eqn = (v*u.m/u.s)^2 == (v0*u.m/u.s)^2 + 2*a*u.m/u.s^2*s*u.km;


checkUnits(eqn,'Compatible')

ans = logical
1

Now, to check that each dimension is consistently represented by the same unit, use checkUnits
with the 'Consistent' input. checkUnits returns logical 0 (false) because meters and
kilometers are both used to represent distance in eqn.

checkUnits(eqn,'Consistent')

ans = logical
0

Convert eqn to SI base units to make the units consistent. Run checkUnits again. eqn has both
compatible and consistent units.

eqn = unitConvert(eqn,'SI')

eqn =
m2 m2 m2
v2 2 = v02 2 + 2000 a s 2
s s s

checkUnits(eqn)

ans = struct with fields:


Consistent: 1
Compatible: 1

After you finish working with units and only need the dimensionless equation or expression, separate
the units and the equation by using separateUnits.

eqn = separateUnits(eqn)

2-49
2 Symbolic Computations in MATLAB

eqn = v2 = v02 + 2000 a s

To calculate numeric values from your expression, substitute for symbolic variables using subs, and
convert to numeric values using double or vpa.

Solve eqn for v. Then find the value of v where v0 = 5 , a = 2 . 5 , and s = 10. Convert the result to
double.
v = solve(eqn,v);
v = v(2); % choose the positive solution
vSol = subs(v,[v0 a s],[5 2.5 10]);
vSol = double(vSol)

vSol = 223.6627

Use Units in Differential Equations

Use units in differential equations just as in standard equations. This section shows how to use units
in differential equations by deriving the velocity relations v = v0 + at and v2 = v02 + 2as starting from
dv
the definition of acceleration a = dt
.

Represent the definition of acceleration symbolically using SI units. Given that the velocity V has
units, you must differentiate V with respect to the correct units as T = t*u.s and not just t.
syms V(t) a
u = symunit;
T = t*u.s; % time in seconds
A = a*u.m/u.s^2; % acceleration in meters per second
eqn1 = A == diff(V,T)

eqn1(t) =
m ∂ 1
a 2= V t
s ∂t s

Because the velocity V is unknown and does not have units, eqn1 has incompatible and inconsistent
units.
checkUnits(eqn1)

ans = struct with fields:


Consistent: 0
Compatible: 0

Solve eqn1 for V with the condition that the initial velocity is v0. The result is the equation
v t = v0 + at.

syms v_0
cond = V(0) == v_0*u.m/u.s;
eqn2 = V == dsolve(eqn1,cond)

eqn2(t) =
1
V t = v0 m + a t m
s

Check that the result has the correct dimensions by substituting rhs(eqn2) into eqn1 and using
checkUnits.

2-50
Units of Measurement Tutorial

checkUnits(subs(eqn1,V,rhs(eqn2)))

ans = struct with fields:


Consistent: 1
Compatible: 1

Now, derive v2 = v02 + 2as. Because velocity is the rate of change of distance, substitute V with the
derivative of distance S. Again, given that S has units, you must differentiate S with respect to the
correct units as T = t*u.s and not just t.

syms S(t)
eqn2 = subs(eqn2,V,diff(S,T))

eqn2(t) =
∂ 1 1
St = v0 m + a t m
∂t s s

Solve eqn2 with the condition that the initial distance covered is 0. Get the expected form of S by
using expand.

cond2 = S(0) == 0;
eqn3 = S == dsolve(eqn2,cond2);
eqn3 = expand(eqn3)

eqn3(t) =
a t2
St = m + v0 t m
2

You can use this equation with the units in symbolic workflows. Alternatively, you can remove the
units by returning the right side using rhs, separating units by using separateUnits, and using the
resulting unitless expression.

[S units] = separateUnits(rhs(eqn3))

S(t) =
t 2 v0 + a t
2

units(t) = m

When you need to calculate numeric values from your expression, substitute for symbolic variables
using subs, and convert to numeric values using double or vpa.

Find the distance traveled in 8 seconds where v_0 = 20 and a = 1.3. Convert the result to double.

S = subs(S,[v_0 a],[20 1.3]);


dist = S(8);
dist = double(dist)

dist = 201.6000

See Also
checkUnits | findUnits | isUnit | newUnit | separateUnits | symunit2str |
unitConversionFactor | unitConvert

2-51
2 Symbolic Computations in MATLAB

More About
• “Unit Conversions and Unit Systems” on page 2-53
• “Units and Unit Systems List” on page 2-60

External Websites
• The International System of Units (SI)

2-52
Unit Conversions and Unit Systems

Unit Conversions and Unit Systems


Convert between units with Symbolic Math Toolbox. This page shows conversions between units and
between systems of units, such as SI, CGS, or a user-defined unit system.

Convert Units
Convert between units by using unitConvert.

Convert 1.2 meters to centimeters.

u = symunit;
len = 1.2*u.m;
len = unitConvert(len,u.cm)

len =
120*[cm]

Convert len to inches. The result is in exact symbolic form. Separate units and convert to double.

len = unitConvert(len,u.in)

len =
(6000/127)*[in]

[len units] = separateUnits(len);


len = double(len)

len =
47.2441

Calculate the force needed to accelerate a mass of 5 kg at 2 m/s2.

m = 5*u.kg;
a = 2*u.m/u.s^2;
F = m*a

F =
10*(([kg]*[m])/[s]^2)

Convert the result to newton.

F = unitConvert(F,u.N)

F =
10*[N]

Tip Use tab expansion to find names of units. Type u., press Tab, and continue typing.

Calculate the energy when force F is applied for 3 meters. Convert the result to joule.

d = 3*u.m;
E = F*d

E =
30*[N]*[m]

2-53
2 Symbolic Computations in MATLAB

E = unitConvert(E,u.J)

E =
30*[J]

Convert E to kilowatt-hour.
E = unitConvert(E,u.kWh)

E =
(1/120000)*[kWh]

Temperature Unit Conversion


Temperatures can represent either absolute temperatures or temperature differences. By default,
temperatures are assumed to be differences. Convert temperatures assuming temperatures are
absolute by specifying the 'Temperature' input as 'absolute'.

Convert 23 degrees Celsius to degrees Kelvin, first as a temperature difference and then as an
absolute temperature.
u = symunit;
T = 23*u.Celsius;
relK = unitConvert(T,u.K,'Temperature','difference')

relK =
23*[K]

absK = unitConvert(T,u.K,'Temperature','absolute')

absK =
(5923/20)*[K]

Because the value 0 is dimensionless and 0 degrees cannot be represented, convert 0 degrees
between temperature units by using cell input.

Convert 0 degrees Celsius to degrees Fahrenheit.


tC = {0,u.Celsius};
tF = unitConvert(tC,u.Fahrenheit,'Temperature','Absolute')

tF =
32*[Fahrenheit]

Convert to SI, CGS, or US Unit Systems


Automatically convert to the correct units by converting to a unit system. Further, converting to the
derived units of a unit system attempts to select convenient units. Available unit systems include SI,
CGS, and US. For all unit systems, see “Unit Systems List” on page 2-71. In addition, you can define
custom unit systems.

Calculate the force due to a 5 kg mass accelerating at 2 m/s2. The resulting units are hard to read.
Convert them to convenient units by specifying the SI and Derived options. unitConvert
automatically chooses the correct units of newton.
u = symunit;
m = 5*u.kg;

2-54
Unit Conversions and Unit Systems

a = 2*u.m/u.s^2;
F = m*a

F =
10*(([kg]*[m])/[s]^2)

F = unitConvert(F,'SI','Derived')

F =
10*[N]

Convert F to US units. By default, the converted units are base units. For convenience, also convert
into derived units by specifying the Derived option. The derived units are easier to read.

F = unitConvert(F,'US')

F =
(1250000000000/17281869297)*(([ft]*[lbm])/[s]^2)

F = unitConvert(F,'US','Derived')

F =
(20000000000000/8896443230521)*[lbf]

Convert F to CGS derived units.

F = unitConvert(F,'CGS','Derived')

F =
1000000*[dyn]

Convert a specification in SI to US derived units. Specify the temperatures as absolute.

loadCell = [ 3*u.kg; % capacity


50*u.mm; % length
15*u.mm; % width
10*u.mm; % height
-10*u.Celsius; % minimum temperature
40*u.Celsius; % maximum temperature
];
loadCell = unitConvert(loadCell,'US','derived','Temperature','absolute')

loadCell =
(300000000/45359237)*[lbm]
(125/762)*[ft]
(25/508)*[ft]
(25/762)*[ft]
14*[Fahrenheit]
104*[Fahrenheit]

If unitConvert does not choose your preferred unit, then adjust the result with further
unitConvert commands. Here, inches are more convenient than feet. Convert the result to inches.

loadCell = unitConvert(loadCell,u.inch)

loadCell =
(300000000/45359237)*[lbm]
(250/127)*[in]
(75/127)*[in]
(50/127)*[in]

2-55
2 Symbolic Computations in MATLAB

14*[Fahrenheit]
104*[Fahrenheit]

The exact symbolic values are hard to read. Separate the units and convert to double.

[loadCellDouble loadCellUnits] = separateUnits(loadCell);


loadCellDouble = double(loadCellDouble)

loadCellDouble =
6.6139
1.9685
0.5906
0.3937
14.0000
104.0000

Alternatively, approximate the result to high precision by using vpa. The vpa function also keeps the
symbolic units because it returns symbolic output.

loadCell = vpa(loadCell)

loadCell =
6.6138678655463274216892140403508*[lbm]
1.968503937007874015748031496063*[in]
0.5905511811023622047244094488189*[in]
0.3937007874015748031496062992126*[in]
14.0*[Fahrenheit]
104.0*[Fahrenheit]

Convert five acres (ac), whose unit is a U.S. survey acre, to metric area.

u = symunit;
area = 5*u.ac_US;
area = unitConvert(area,'SI')

area =

(313632000000/15499969)*[m]^2

Define Custom Unit System from Existing System


Custom unit systems provide flexibility in converting units. You can easily define a custom unit system
by modifying a default unit system. Alternatively, you can define the system directly. For definitions of
unit system, base units, and derived units, see “Unit System Definition” on page 2-58.

In photonics, commonly used units are nanosecond (ns), electron volt (eV), and nanometer (nm).
Define a unit system with these units by modifying the SI unit system. Get SI base and derived units
by using baseUnits and derivedUnits. Modify the units by using subs.

u = symunit;
bunits = baseUnits('SI');
bunits = subs(bunits,[u.m u.s],[u.nm u.ns])

bunits =
[ [kg], [ns], [nm], [A], [cd], [mol], [K]]

dunits = derivedUnits('SI');
dunits = subs(dunits,u.J,u.eV)

2-56
Unit Conversions and Unit Systems

dunits =
[ [F], [C], [S], [H], [V], [eV], [N], [lx], [lm], [Wb], [W], [Pa],...
[Ohm], [T], [Gy], [Bq], [Sv], [Hz], [kat], [rad], [sr], [Celsius]]

Note Do not define variables called baseUnits and derivedUnits because the variables prevent
access to the baseUnits and derivedUnits functions.

Define the new unit system by using newUnitSystem.


phSys = newUnitSystem('photonics',bunits,dunits)

phSys =
"photonics"

Calculate the energy of a photon of frequency 1 GHz and convert the result to derived units of the
phSys system. The result is in electron volts.
f = 1*u.GHz;
E = u.h_c*f;
E = unitConvert(E,phSys,'Derived')

E =
(44173801/10681177560000)*[eV]

The exact symbolic result is hard to read. Separate the units and convert to double.
[E Eunits] = separateUnits(E);
E = double(E)

E =
4.1357e-06

After completing calculations, remove the unit system.


removeUnitSystem(phSys)

Define Custom Unit System Directly


Define a custom unit system for atomic units (au).

Define these base units:

Dimension Unit Implementation


Mass Electron rest mass u.m_e
Elementary charge Electron charge u.e
Length Bohr radius (a0) u.Bohr
Time ħ/Eh Define by using newUnit.

u = symunit;
t_au = newUnit('t_au',u.hbar/u.E_h);
bunits = [u.m_e u.e u.Bohr u.t_au]

bunits =
[ [m_e], [e], [a_0], [t_au]]

2-57
2 Symbolic Computations in MATLAB

Define these derived units:

Dimension Unit Implementation


Angular momentum Reduced Planck's constant u.hbar
Energy Hartree u.E_h
Electric dipole moment ea0 Define by using newUnit.
Magnetic dipole moment 2 Bohr magneton = eħ/2me Define by using newUnit.
Electric potential Eh/e Define by using newUnit.

edm_au = newUnit('edm_au',u.e*u.bohr);
mdm_au = newUnit('mdm_au', u.e*u.hbar/(2*u.me));
ep_au = newUnit('ep_au', u.E_h/u.e);
dunits = [u.hbar u.E_h u.edm_au u.mdm_au u.ep_au]

dunits =
[ [h_bar], [E_h], [edm_au], [mdm_au], [ep_au]]

Define the unit system.

auSys = newUnitSystem('atomicUnits',bunits,dunits)

auSys =
"atomicUnits"

Convert the properties of a proton to atomic units.

proton = [ 1.672621923e-27*u.kg; % mass


1.6021766208e-19*u.C; % charge
5.4e-24*u.e*u.cm; % electric dipole moment
1.4106067873e-26*u.J/u.T; % magnetic dipole moment
];
proton = unitConvert(proton,auSys,'Derived')

proton =
1836.1526726825404620381265471117*[m_e]
0.99999999176120807953267071600981*[e]
0.0000000000000010204521072979158730257341288851*[edm_au]
0.00048415958374162452452052339364507*pi*[mdm_au]

After completing calculations, remove the unit system and the added units.

removeUnitSystem(auSys)
removeUnit([u.t_au u.edm_au u.mdm_au u.ep_au])

Unit System Definition


A unit system is a collection of base units and derived units that follows these rules:

• Base units must be independent in terms of the dimensions mass, time, length, electric current,
luminous intensity, amount of substance, and temperature. Therefore, a unit system has up to 7
base units. As long as the independence is satisfied, any unit can be a base unit, including units
such as newton or watt.
• A unit system can have less than 7 base units. For example, mechanical systems need base units
only for the dimensions length, mass, and time.

2-58
Unit Conversions and Unit Systems

• Derived units in a unit system must have a representation in terms of the products of powers of
the base units for that system. Unlike base units, derived units do not have to be independent.
• Derived units are optional and added for convenience of representation. For example, kg m/s2 is
abbreviated by newton.
• An example of a unit system is the SI unit system, which has 7 base units: kilogram, second,
meter, ampere, candela, mol, and kelvin. There are 22 derived units found by calling
derivedUnits('SI').

See Also
baseUnits | derivedUnits | newUnitSystem | removeUnit | removeUnitSystem | symunit |
unitConvert

More About
• “Units of Measurement Tutorial” on page 2-47
• “Units and Unit Systems List” on page 2-60

External Websites
• The International System of Units (SI)

2-59
2 Symbolic Computations in MATLAB

Units and Unit Systems List


List of units, SI unit prefixes, and unit systems in Symbolic Math Toolbox. For details, see “Units of
Measurement Tutorial” on page 2-47. Common alternate names for units are supported and map to
the names listed here. Plurals are not supported.

In this section...
“Units List” on page 2-60
“SI Unit Prefixes List” on page 2-70
“Unit Systems List” on page 2-71
“Defining Constants of SI Units” on page 2-72

Units List
Length

• Ao - angstrom
• a_0 - Bohr radius
• au - astronomical unit
• ch - chain
• ft - foot
• ft_US - U.S. survey foot
• ftm - fathom
• fur - furlong
• gg - gauge
• hand - hand
• in - inch
• inm - international nautical mile
• land - league
• li - link
• line - line
• ly - light-year
• m - meter (SI)
• mi - mile
• mi_US - U.S. survey mile
• mil - mil
• nmile - British imperial nautical mile
• pc - parsec
• pica - pica
• pica_US - U.S. customary pica
• pt - point

2-60
Units and Unit Systems List

• pt_US - U.S. customary point


• rod - rod
• span - span
• xu - x unit
• xu_Cu - x unit (copper)
• xu_Mo - x unit (molybdenum)
• yd - yard

Mass

• Mt - metric megaton
• ct - carat
• cwt - U.S. customary short hundredweight
• cwt_UK - British imperial short hundredweight
• dalton - atomic mass constant
• dr - dram
• g - gram (SI)
• gr - grain
• hyl - hyl
• kt - metric kiloton
• lbm - pound mass
• m_e - electron mass
• m_p - proton mass
• m_u - atomic mass constant
• oz - ounce
• quarter - quarter
• slug - slug
• stone - stone
• t - metric ton
• tn - U.S. customary short ton
• ton_UK - British imperial ton

Time

• d - day
• fortnight - 14 days
• h - hour
• min - minute
• month_30 - 30-day month
• s - second (SI)
• week - 7-day week
• year_360 - 360-day year

2-61
2 Symbolic Computations in MATLAB

• year_Julian - Julian year


• year_Gregorian - Gregorian year

Absorbed Dose or Dose Equivalent

• Gy - gray (SI)
• Rad - absorbed radiation dose
• Sv - sievert (SI)
• rem - roentgen equivalent man

Acceleration

• Gal - gal
• g_n - earth gravitational acceleration

Activity

• Bq - becquerel (SI)
• Ci - curie

Amount of Substance

• item - number of items


• mol - mole (SI)
• molecule - number of molecules

Angular Momentum

• Nms - newton meter second


• h_bar - reduced Planck constant
• h_c - Planck constant

Area

• a - are
• ac - acre
• ac_US - U.S. survey acre
• barn - barn
• circ_mil - circular mil
• circ_inch - circular inch
• ha - metric hectare
• ha_US - U.S. survey hectare
• ro - rood
• twp - township

Capacitance

• F - farad (SI)

2-62
Units and Unit Systems List

• abF - abfarad
• statF - statfarad

Capacitance Per Length

• e_0 - vacuum electric permittivity or electric constant

Catalytic Activity

• kat - katal (SI)

Conductance

• G_0 - conductance quantum


• S - siemens (SI)
• abS - absiemens
• statS - statsiemens

Data Transfer Rate

• Bd - baud
• bps - bit per second

Digital Information

• B - byte
• bit - basic unit of information

Dimensionless

• alpha - fine-structure constant


• g_e - electron g-factor
• g_p - proton g-factor

Dose Equivalent

• Sv - sievert (SI)

Dynamic Viscosity

• P - poise
• reyn - reynolds

Electric Charge

• C - coulomb (SI)
• Fr - franklin
• abC - abcoulomb
• e - elementary charge
• statC - statcoulomb

2-63
2 Symbolic Computations in MATLAB

Electric Charge Per Mole of Electrons

• F_c - Faraday constant

Electric Current

• A - ampere (SI)
• Bi - biot
• abA - abampere
• statA - statampere

Electric Dipole Moment

• debye - debye

Electric Potential or Electromotive Force

• V - volt (SI)
• abV - abvolt
• statV - statvolt

Energy or Work or Heat

• Btu_IT - British thermal unit (International Table)


• Btu_th - British thermal unit (thermochemical)
• E_h - Hartree energy
• J - joule (SI)
• Nm - newton meter
• Wh - watt hour
• Ws - watt second
• cal_4 - calorie (4 degree Celsius)
• cal_20 - calorie (20 degree Celsius)
• cal_15 - calorie (15 degree Celsius)
• cal_IT - calorie (International Table)
• cal_th - calorie (thermochemical)
• cal_mean - calorie (mean)
• eV - electronvolt
• erg - erg
• kcal_4 - kilocalorie (4 degree Celsius)
• kcal_20 - kilocalorie (20 degree Celsius)
• kcal_15 - kilocalorie (15 degree Celsius)
• kcal_IT - kilocalorie (International Table)
• kcal_th - kilocalorie (thermochemical)
• kcal_mean - kilocalorie (mean)
• kpm - kilopond meter

2-64
Units and Unit Systems List

• therm - therm

Energy Per Temperature

• k_B - Boltzmann constant

Energy Per Temperature Per Amount of Substance

• R_c - molar gas constant

European Currency

• Cent - cent
• EUR - Euro

Flow Rate

• gpm - U.S. customary gallon per minute


• gpm_UK - British imperial gallon per minute
• lpm - liter per minute

Force

• N - newton (SI)
• dyn - dyne
• kgf - kilogram force
• kip - kip
• kp - kilopond
• lbf - pound force
• ozf - ounce force
• p - pond
• pdl - poundal
• sn - sthene
• tonf - short ton force

Former European Currency

• ATS - Austrian Schilling


• BEF - Belgian Franc
• DM - German Mark
• ESP - Spanish Peseta
• FIM - Finnish Markka
• FRF - French Franc
• IEP - Irish Pound
• ITL - Italian Lire
• LUF - Luxembourgian Franc
• NLG - Dutch Gulden

2-65
2 Symbolic Computations in MATLAB

• PTE - Portuguese Escudo

Frequency

• Hz - hertz (SI)
• dv_Cs - caesium hyperfine transition frequency

Frequency of Rotation

• rpm - revolution per minute


• rps - revolution per second

Fuel Consumption

• l_100km - liter per 100 km

Fuel Economy

• mpg - mile per gallon

Gravity

• G_c - Newtonian constant of gravitation

Illuminance

• lx - lux (SI)
• nx - nox
• ph - phot

Inductance

• H - henry (SI)
• abH - abhenry
• statH - stathenry

Inductance Per Length

• mu_0 - vacuum magnetic permeability

Intensity Per Fourth Power of Absolute Temperature

• sigma - Stefan–Boltzmann constant

Ionising Dosage

• R - roentgen

Kinematic Viscosity

• St - stokes
• newt - newt

2-66
Units and Unit Systems List

Luminance

• asb - apostilb
• sb - stilb

Luminous Efficacy

• K_cd - luminous efficacy of a defined visible radiation

Luminous Flux

• lm - lumen (SI)

Luminous Intensity

• cd - candela (SI)
• cp - candlepower

Magnetic Field Strength

• Oe - oersted

Magnetic Flux

• Mx - maxwell
• Wb - weber (SI)
• abWb - abweber
• statWb - statweber
• phi_0 - magnetic flux quantum

Magnetic Flux Density

• G - gauss
• T - tesla (SI)
• abT - abtesla
• statT - stattesla

Magnetic Force

• Gb - gilbert

Mass Per Length

• den - denier
• tex - filament tex

Particle Magnetic Moment Per Angular Momentum

• gamma_e - electron gyromagnetic ratio


• gamma_p - proton gyromagnetic ratio

2-67
2 Symbolic Computations in MATLAB

Particle Per Amount of Substance

• N_A - Avogadro constant

Plane Angle

• arcsec - arcsecond
• arcmin - arcminute
• deg - degree
• rad - radian (SI)
• rev - revolution

Power or Heat Flow Rate

• HP_E - electrical horsepower


• HP_I - mechanical horsepower
• HP_UK - British imperial horsepower
• HP_DIN - metric horsepower (DIN 66036)
• PS_SAE - net horsepower (SAE J1349)
• PS_DIN - horsepower (DIN 70020)
• W - watt (SI)
• poncelet - poncelet

Pressure or Stress

• Ba - barye
• Pa - pascal (SI)
• Torr - torr
• at - technical atmosphere
• atm - standard atmosphere
• bar - bar
• cmHg - centimeter of mercury (conventional)
• cmH2O - centimeter of water (conventional)
• ftHg - foot of mercury (conventional)
• ftH2O - foot of water (conventional)
• inHg - inch of mercury (conventional)
• inH2O - inch of water (conventional)
• ksf - kip per square foot
• ksi - kip per square inch
• mH2O - meter of water (conventional)
• mHg - meter of mercury (conventional)
• mmHg - millimeter of mercury (conventional)
• mmH2O - millimeter of water (conventional)
• psf - pound force per square foot

2-68
Units and Unit Systems List

• psi - pound force per square inch


• pz - pieze

Quantum Resistance

• R_K - von Klitzing constant

Radiation

• lan - langley

Reciprocal Length

• kayser - kayser
• R_inf - Rydberg constant

Refractive Power of Lenses

• dpt - diopter

Resistance

• Ohm - ohm (SI)


• abOhm - abohm
• statOhm - statohm

Solid Angle

• sr - steradian (SI)

Substance Per Volume

• molarity - molarity

Temperature

• Celsius - degree Celsius (SI)


• Fahrenheit - degree Fahrenheit
• K - kelvin (SI)
• Rankine - degree Rankine
• Reaumur - degree Reaumur

Velocity

• Kyne - kyne
• c_0 - speed of light in vacuum
• fpm - foot per minute
• fps - foot per second
• kmh - kilometer per hour
• knot_UK - British imperial knot
• kts - international knot

2-69
2 Symbolic Computations in MATLAB

• mach - speed of sound


• mph - mile per hour

Volume

• barrel - barrel
• bbl - U.S. customary dry barrel
• bu_UK - British imperial bushel
• chaldron - chaldron
• dry_bu - U.S. customary dry bushel
• dry_gal - U.S. customary dry gallon
• dry_pk - U.S. customary dry peck
• dry_pt - U.S. customary dry pint
• dry_qt - U.S. customary dry quart
• fldr - U.S. customary fluid dram
• fldr_UK - British imperial fluid drachm (dram)
• floz - U.S. customary fluid ounce
• floz_UK - British imperial fluid ounce
• gal - U.S. customary liquid gallon
• gal_UK - British imperial gallon
• gill - U.S. customary fluid gill
• gill_UK - British imperial gill
• igal - British imperial gallon
• l - liter
• liq_pt - U.S. customary liquid pint
• liq_qt - U.S. customary liquid quart
• minim - U.S. customary minim
• minim_UK - British imperial minim
• pint - U.S. customary liquid pint
• pint_UK - British imperial pint
• pk_UK - British imperial peck
• pottle - British imperial pottle
• qt_UK - British imperial quart
• quart - U.S. customary liquid quart

SI Unit Prefixes List


SI unit prefixes in Symbolic Math Toolbox. Every unit marked by (SI) in the units list accepts SI
prefixes. For example, m accepts nm, mcm, mm, cm, km and so on.

2-70
Units and Unit Systems List

Prefix Input Forms Example using meters u.m


where u = symunit
Yotta 1024 Y, yotta u.Ym, u.yottam
21
Zetta 10 Z, zetta u.Zm, u.zettam
18
Exa 10 E, exa u.Em, u.exam
15
Peta 10 P, peta u.Pm, u.petam
12
Tera 10 T, tera u.Tm, u.teram
Giga 109 G, giga u.gigam, u.Gm
Mega 106 M, mega u.Mm, u.megam
3
Kilo 10 k, kilo u.km, u.kilom
2
Hecto 10 h, hecto u.hm, u.hectom
1
Deka 10 da, deka, deca u.dam, u.dekam, u.decam
–1
Deci 10 d, deci u.dm, u.decim
–2
Centi 10 c, centi u.cm, u.centim
–3
Milli 10 m, milli u.mm, u.millim
Micro 10–6 mc, micro, u u.mcm, u.microm, u.um
Nano 10–9 n, nano u.nm, u.nanom
–12
Pico 10 p, pico u.pm, u.picom
–15
Femto 10 f, femto u.fm, u.femtom
–18
Atto 10 a, atto u.am, u.attom
–21
Zepto 10 z, zepto u.zm, u.zeptom
–24
Yocto 10 y, yocto u.ym, u.yoctom

Unit Systems List

Available unit systems in Symbolic Math Toolbox are listed below. For details, see “Unit Conversions
and Unit Systems” on page 2-53.

Unit System Base Units Derived Units


SI units ('SI') baseUnits('SI') derivedUnits('SI')

ans = ans =
[ [kg], [s], [m], [A], [cd], [[mol],
[F], [C],
[K]] [S], [H], [V], [J], [N], [l
[Pa], [Ohm], [T], [Gy], [Bq], [Sv], [H
[Celsius]]
CGS units ('CGS') baseUnits('CGS') derivedUnits('CGS')

ans = ans =
[ [cm], [g], [s], [K]] [ [Gal], [dyn], [erg], [Ba], [P], [St],

2-71
2 Symbolic Computations in MATLAB

Unit System Base Units Derived Units


US units ('US') baseUnits('US') derivedUnits('US')

ans = ans =
[ [lbm], [s], [ft], [A], [cd],
[ [F],
[mol],
[C],
[K]]
[S], [H], [V], [Btu_IT], [l
[W], [psf], [Ohm], [T], [Gy], [Bq], [S
[sr], [Fahrenheit], [gal]]
Electrostatic units ('ESU') baseUnits('ESU') derivedUnits('ESU')

ans = ans =
[ [cm], [g], [s], [K], [statC]]
[ [Gal], [dyn], [erg], [Ba], [P], [St],
[statH], [statS], [statOhm], [statT],
Gaussian units ('GU') baseUnits('GU') derivedUnits('GU')

ans = ans =
[ [cm], [g], [s], [K], [Fr]] [ [Gal], [dyn], [erg], [Ba], [P], [St],
[Bi], [Mx], [Oe], [debye]]
Electromagnetic units ('EMU') baseUnits('EMU') derivedUnits('EMU')

ans = ans =
[ [cm], [g], [s], [K], [abA]][ [Gal], [dyn], [erg], [Ba], [P], [St],
[abF], [abH], [abS], [abOhm], [abT], [

Defining Constants of SI Units


In 2019, the seven SI base units were redefined in terms of seven physical constants that have exact
values. These constants are represented by symbolic units as listed below.

Physical Constants Symbolic Values


Caesium-133 hyperfine u = symunit;
transition frequency (dv_Cs) unitConvert(u.dv_Cs,'SI')

ans =
9192631770*(1/[s])
Speed of light (c_0) u = symunit;
unitConvert(u.c_0,'SI')

ans =
299792458*([m]/[s])
Planck constant (h_c) u = symunit;
unitConvert(u.h_c,'SI')

ans =
(132521403/200000000000000000000000000000000000000000)*(([kg]*[m]^2)
Elementary charge (e) u = symunit;
unitConvert(u.e,'SI')

ans =
(801088317/5000000000000000000000000000)*[A]*[s]

2-72
Units and Unit Systems List

Physical Constants Symbolic Values


Boltzmann constant (k_B) u = symunit;
unitConvert(u.k_B,'SI')

ans =
(1380649/100000000000000000000000000000)*(([kg]*[m]^2)/([K]*[s]^2))
Avogadro constant (N_A) u = symunit;
unitConvert(u.N_A,'SI')

ans =
602214076000000000000000*(1/[mol])
Luminous efficacy of a 540 THz u = symunit;
radiation (K_cd) unitConvert(u.K_cd,'SI')

ans =
683*(([cd]*[s]^3*[sr])/([kg]*[m]^2))

See Also
unitInfo | checkUnits | isUnit | newUnit | rewrite | separateUnits | symunit |
symunit2str | unitConversionFactor

See Also

Related Examples
• “Units of Measurement Tutorial” on page 2-47
• “Unit Conversions and Unit Systems” on page 2-53

External Websites
• The International System of Units (SI)

2-73
2 Symbolic Computations in MATLAB

Units in Physics Calculations

This example shows how to work with units in physics calculations. Calculate the terminal velocity of
a falling paratrooper in both SI and imperial units. Solve the motion of the paratrooper, taking into
account the gravitational force and the drag force.

Introduction

Imagine a paratrooper jumping out of an airplane. Assume there are only two forces acting on the
paratrooper: the gravitational force and an opposing drag force from the parachute. The drag force is
proportional to the velocity squared of the paratrooper.

The net force acting on the paratrooper can be expressed as

mass ⋅ acceleration = drag force − gravitational force,

∂ 2
m v t = cdv t − m g,
∂t

where

• m is the mass of the paratrooper


• g is the gravitational acceleration
• v(t)is the velocity of the paratrooper
• cd is the drag constant

Define and Solve Equation of Motion

Define the differential equation describing the equation of motion.

syms g m c_d
syms v(t)
eq = m*diff(v(t),t) + m*g == c_d*v(t)^2

eq =
∂ 2
m v t + g m = cd v t
∂t

2-74
Units in Physics Calculations

Assume that the parachute opens immediately at t = 0 so that the equation eq is valid for all values of
t ≥ 0. Solve the differential equation analytically using dsolve with the initial condition v 0 = 0. The
solution represents the velocity of the paratrooper as a function of time.
velocity = simplify(dsolve(eq, v(0) == 0))

velocity =
cd g t
g m tanh
m

cd

Find Unit of Drag Constant

Find the SI unit of the drag constant cd.

kg ⋅ m
The SI unit of force is the Newton N . In terms of the base units, the Newton is . Since these
s2
are equivalent, they have a unit conversion factor of 1.
u = symunit;
unitConversionFactor(u.N, u.kg*u.m/u.s^2)

ans = 1

2
The drag force cdv t must have the same unit in Newton N as the gravitational force m g. Using
dimensional analysis, solve for the unit of cd.

syms drag_units_SI
drag_units_SI = simplify(solve(drag_units_SI * (u.m / u.s)^2 == u.N))

drag_units_SI =
kg
m

Estimate Terminal Velocity

Describe the motion of the paratrooper by defining the following values.

• Mass of the paratrooper m = 70 kg


• Gravitational acceleration g = 9 . 81 m/s2
• Drag coefficient cd = 40 kg/m

Substitute these values into the velocity equation and simplify the result.
vel_SI = subs(velocity,[g,m,c_d],[9.81*u.m/u.s^2, 70*u.kg, 40*drag_units_SI])

vel_SI =
kg 981 m
t 40
m 100 s2 981 m
tanh 70 kg 100 2
70 kg s

kg
40 m

vel_SI = simplify(vel_SI)

vel_SI =

2-75
2 Symbolic Computations in MATLAB

3 763 t 1
3 763 tanh 35 s m

20 s

Compute a numerical approximation of the velocity to 3 significant digits.

digits(3)
vel_SI = vpa(vel_SI)

vel_SI =
1 m
−4.14 tanh 2.37 t
s s

The paratrooper approaches a constant velocity when the gravitational force is balanced by the drag
force. This is called the terminal velocity and it occurs when the drag force from the parachute
cancels out the gravitational force (there is no further acceleration). Find the terminal velocity by
taking the limit of t ⟶ ∞.

vel_term_SI = limit(vel_SI, t, Inf)

vel_term_SI =
m
−4.14
s

Convert Velocity to Imperial Units

Finally, convert the velocity function from SI units to imperial units.

vel_Imperial = rewrite(vel_SI,u.ft)

vel_Imperial =
1 ft
−13.6 tanh 2.37 t
s s

Convert the terminal velocity.

vel_term_Imperial = rewrite(vel_term_SI,u.ft)

vel_term_Imperial =
ft
−13.6
s

Plot Velocity over Time

To plot the velocity as a function of time, express the time t in seconds and replace t by T s, where T
is a dimensionless symbolic variable.

syms T
vel_SI = subs(vel_SI, t, T*u.s)

vel_SI =
m
−4.14 tanh 2.37 T
s

vel_Imperial = rewrite(vel_SI, u.ft)

vel_Imperial =
ft
−13.6 tanh 2.37 T
s

2-76
Units in Physics Calculations

Separate the expression from the units by using separateUnits. Plot the expression using fplot.
Convert the units to strings for use as plot labels by using symunit2str.

[data_SI, units_SI] = separateUnits(vel_SI);


[data_Imperial, units_Imperial] = separateUnits(vel_Imperial);

The velocity of the paratrooper approaches steady state when t > 1. Show how the velocity
approaches terminal velocity by plotting the velocity over the range 0 ≤ T ≤ 2.

subplot(1,2,1)
fplot(data_SI,[0 2])
title('Velocity in SI Units')
xlabel('Time in s')
ylabel(['Velocity in ' symunit2str(units_SI)])
subplot(1,2,2)
fplot(data_Imperial,[0 2])
title('Velocity in Imperial Units')
xlabel('Time in s')
ylabel(['Velocity in ' symunit2str(units_Imperial)])

See Also
Functions
symunit | unitConversionFactor | rewrite | separateUnits

2-77
2 Symbolic Computations in MATLAB

The Physics of the Damped Harmonic Oscillator

This example explores the physics of the damped harmonic oscillator by solving the equations of
motion in the case of no driving forces. This example investigates the cases of under-, over-, and
critical-damping.

Contents

1 Derive Equation of Motion


2 Solve the Equation of Motion (F = 0)
3 Underdamped Case (ζ < 1)
4 Overdamped Case (ζ > 1)
5 Critically Damped Case (ζ = 1)
6 Conclusion

1. Derive Equation of Motion

Consider a forced harmonic oscillator with damping shown below. Model the resistance force as
proportional to the speed with which the oscillator moves.

2-78
The Physics of the Damped Harmonic Oscillator

Define the equation of motion where

• m is the mass
• c is the damping coefficient
• k is the spring constant
• F is a driving force

syms x(t) m c k F(t)


eq = m*diff(x,t,t) + c*diff(x,t) + k*x == F

eq(t) =
∂2 ∂
m x t +c x t +kx t = F t
∂t 2 ∂t

Rewrite the equation using c = m γ and k = m ω02.

syms gamma omega_0


eq = subs(eq, [c k], [m*gamma, m*omega_0^2])

eq(t) =
∂2 ∂
m x t +γm x t + m x t ω02 = F t
∂t2 ∂t

Divide out the mass m. Now we have the equation in a convenient form to analyze.

eq = collect(eq, m)/m

eq(t) =
∂2 ∂ Ft
x t +γ x t + x t ω02 =
∂t2 ∂t m

2. Solve the Equation of Motion where F = 0

Solve the equation of motion using dsolve in the case of no external forces where F = 0. Use the
initial conditions of unit displacement and zero velocity.

vel = diff(x,t);
cond = [x(0) == 1, vel(0) == 0];
eq = subs(eq,F,0);
sol = dsolve(eq, cond)

sol =

2-79
2 Symbolic Computations in MATLAB

γ σ1 γ σ1
e−t 2 − 2 γ + σ1 e−t 2 + 2 γ − σ1

2 σ1 2 σ1

where

σ1 = γ − 2 ω0 γ + 2 ω0

Examine how to simplify the solution by expanding it.

sol = expand(sol)

sol =
t γ2 − 4 ω02 t γ2 − 4 ω02
σ1 σ2 σ1 e 2 γ σ1 σ2 γ σ1 e 2
+ − +
2 2 2
2 γ − 4 ω0 2 2 γ − 4 ω02
2

where
γt
σ1 = e− 2

t γ2 − 4 ω02
σ2 = e− 2

Notice that each term has a factor of σ1, or e−γt/2, use collect to gather these terms

sol = collect(sol, exp(-gamma*t/2))

sol =
−σ1 σ −σ σ γt
e e 1 γ e 1 γ e 1
+ − + e− 2
2 2 2
2 γ − 4 ω02 2
2 γ − 4 ω0 2

where

t γ2 − 4 ω02
σ1 =
2

The term γ2 − 4ω02 appears in various parts of the solution. Rewrite it in a simpler form by
γ
introducing the damping ratio ζ ≡ .
2ω0

Substituting ζ into the term above gives:

γ 2
2
γ2 − 4ω02 = 2ω0 − 1 = 2ω0 ζ − 1,
2ω0

syms zeta;
sol = subs(sol, ...
sqrt(gamma^2 - 4*omega_0^2), ...
2*omega_0*sqrt(zeta^2-1))

sol =

2-80
The Physics of the Damped Harmonic Oscillator

γt σ2 σ1 γ σ2 γ σ1
e− 2 + + −
2 2 2 2
4 ω0 ζ − 1 4 ω0 ζ − 1

where

2
σ1 = e−ω0 t ζ − 1

2
σ2 = eω0 t ζ − 1

Further simplify the solution by substituting γ in terms of ω0 and ζ ,

sol = subs(sol, gamma, 2*zeta*omega_0)

sol =
−ω0 t ζ σ2 σ1 ζ σ2 ζ σ1
e + + −
2 2 2 2
2 ζ −1 2 ζ −1

where

2
σ1 = e−ω0 t ζ − 1

2
σ2 = eω0 t ζ − 1

We have derived the general solution for the motion of the damped harmonic oscillator with no
driving forces. Next, we'll explore three special cases of the damping ratio ζ where the motion takes
on simpler forms. These cases are called

• underdamped (ζ < 1),


• overdamped (ζ > 1), and
• critically damped (ζ = 1).

3. Underdamped Case (ζ < 1)

2 2
If ζ < 1, then ζ − 1 = i 1 − ζ is purely imaginary
solUnder = subs(sol, sqrt(zeta^2-1), 1i*sqrt(1-zeta^2))

solUnder =
−ω0 t ζ σ1 σ2 ζ σ1 i ζ σ2 i
e + + −
2 2 2 2
2 1−ζ 2 1−ζ

where

2
σ1 = e−ω0 t 1 − ζ i

2
σ2 = eω0 t 1 − ζ i

2 2
Notice the terms ei ω0 t ζ −1± e−i ω0 t ζ −1 in the above equation and recall the identity
ei x = cos x + i sin x .

Rewrite the solution in terms of cos.

2-81
2 Symbolic Computations in MATLAB

solUnder = coeffs(solUnder, zeta);


solUnder = solUnder(1);
c = exp(-omega_0 * zeta * t);
solUnder = c * rewrite(solUnder / c, 'cos')

−ω0 t ζ 2
solUnder = e cos ω0 t 1 − ζ

solUnder(t, omega_0, zeta) = solUnder

−ω0 t ζ 2
solUnder(t, omega_0, zeta) = e cos ω0 t 1 − ζ

2
The system oscillates at a natural frequency of ω0 1 − ζ and decays at an exponential rate of 1/ω0 ζ.

Plot the solution with fplot as a function of ω0t and ζ .

z = [0 1/4 1/2 3/4];


w = 1;
T = 4*pi;
lineStyle = {'-','--',':k','-.'};

fplot(@(t)solUnder(t, w, z(1)), [0 T], lineStyle{1});

hold on;
for k = 2:numel(z)
fplot(@(t)solUnder(t, w, z(k)), [0 T], lineStyle{k});
end
hold off;
grid on;
xticks(T*linspace(0,1,5));
xticklabels({'0','\pi','2\pi','3\pi','4\pi'});
xlabel('t / \omega_0');
ylabel('amplitude');
lgd = legend('0','1/4','1/2','3/4');
title(lgd,'\zeta');
title('Underdamped');

2-82
The Physics of the Damped Harmonic Oscillator

4. Overdamped Case (ζ > 1)

2
If ζ > 1, then ζ − 1 is purely real and the solution can be rewritten as

solOver = sol

solOver =
−ω0 t ζ σ2 σ1 ζ σ2 ζ σ1
e + + −
2 2 2 2
2 ζ −1 2 ζ −1

where

2
σ1 = e−ω0 t ζ − 1

2
σ2 = eω0 t ζ − 1

solOver = coeffs(solOver, zeta);


solOver = solOver(1)

solOver =
2 2
−ω0 t ζ eω0 t ζ − 1 e−ω0 t ζ − 1
e +
2 2

2-83
2 Symbolic Computations in MATLAB

2 2
eω0t ζ − 1 + e−ω0t ζ − 1
ex + e−x
Notice the terms 2
and recall the identity cosh x = 2
.

Rewrite the expression in terms of cosh.

c = exp(-omega_0*t*zeta);
solOver = c*rewrite(solOver / c, 'cosh')

2 −ω0 t ζ
solOver = cosh ω0 t ζ − 1 e

solOver(t, omega_0, zeta) = solOver

2 −ω0 t ζ
solOver(t, omega_0, zeta) = cosh ω0 t ζ − 1 e

Plot the solution to see that it decays without oscillating.

z = 1 + [1/4 1/2 3/4 1];


w = 1;
T = 4*pi;
lineStyle = {'-','--',':k','-.'};

fplot(@(t)solOver(t, w, z(1)), [0 T], lineStyle{1});

hold on;
for k = 2:numel(z)
fplot(@(t)solOver(t, w, z(k)), [0 T], lineStyle{k});
end
hold off;
grid on;
xticks(T*linspace(0,1,5));
xticklabels({'0','\pi','2\pi','3\pi','4\pi'});
xlabel('\omega_0 t');
ylabel('amplitude');
lgd = legend('1+1/4','1+1/2','1+3/4','2');
title(lgd,'\zeta');
title('Overdamped');

2-84
The Physics of the Damped Harmonic Oscillator

5. Critically Damped Case (ζ = 1)

If ζ = 1, then the solution simplifies to

solCritical(t, omega_0) = limit(sol, zeta, 1)

−ω0 t
solCritical(t, omega_0) = e ω0 t + 1

Plot the solution for the critically damped case.

w = 1;
T = 4*pi;

fplot(solCritical(t, w), [0 T])


xlabel('\omega_0 t');
ylabel('x');
title('Critically damped, \zeta = 1');
grid on;
xticks(T*linspace(0,1,5));
xticklabels({'0','\pi','2\pi','3\pi','4\pi'});

2-85
2 Symbolic Computations in MATLAB

6. Conclusion

We have examined the different damping states for the harmonic oscillator by solving the ODEs which
represents its motion using the damping ratio ζ . Plot all three cases together to compare and contrast
them.

zOver = pi;
zUnder = 1/zOver;
w = 1;
T = 2*pi;
lineStyle = {'-','--',':k'};

fplot(@(t)solOver(t, w, zOver), [0 T], lineStyle{1},'LineWidth',2);


hold on;
fplot(solCritical(t, w), [0 T], lineStyle{2},'LineWidth',2)
fplot(@(t)solUnder(t, w, zUnder), [0 T], lineStyle{3},'LineWidth',2);
hold off;

textColor = lines(3);
text(3*pi/2, 0.3 , 'over-damped' ,'Color',textColor(1,:));
text(pi*3/4, 0.05, 'critically-damped','Color',textColor(2,:));
text(pi/8 , -0.1, 'under-damped');

grid on;
xlabel('\omega_0 t');
ylabel('amplitude');
xticks(T*linspace(0,1,5));

2-86
The Physics of the Damped Harmonic Oscillator

xticklabels({'0','\pi/2','\pi','3\pi/2','2\pi'});
yticks((1/exp(1))*[-1 0 1 2 exp(1)]);
yticklabels({'-1/e','0','1/e','2/e','1'});
lgd = legend('\pi','1','1/\pi');
title(lgd,'\zeta');
title('Damped Harmonic Oscillator');

See Also
Functions
diff | subs | dsolve | fplot | collect | expand | rewrite

2-87
2 Symbolic Computations in MATLAB

Evaluating the Average Power Delivered by a Wind Turbine

This example uses Symbolic Math Toolbox™ and the Statistics and Machine Learning Toolbox™ to
explore and derive a parametric analytical expression for the average power generated by a wind
turbine.

The parametric equation can be used for evaluating various wind turbine configurations and wind
farm sites. More information see Wind Resource Assessment.

Background

The total power delivered to a wind turbine can be estimated by taking the derivative of the wind's
kinetic energy. This results in the following expression:

ρ A u3
Pw = 2
(1)

• A is the swept area of turbine blades, in m2


• ρ = air density, in kg/m3
• u = wind speed, in m/s

The process of converting wind power to electrical power results in efficiency losses, as described in
the diagram below.

2-88
Evaluating the Average Power Delivered by a Wind Turbine

The electrical power output of a practical wind turbine can be described using the following equation:

Ctot ρ Au3
Pe = 2
(2) where Ctot = overall efficiency = CpCtCg

The overall efficiency is between 0.3 and 0.5, and varies with both wind speed and rotational speed of
the turbine. For a fixed rotational speed, there is a rated wind speed at which electrical power
generated by the wind turbine is near its maximum (Per), and overall efficiency at this point is
denoted CtotR.

CtotR ρ Au3
Per = 2
(3)

Assuming a fixed rotational speed, the electrical power output of the wind turbine can be estimated
using the following profile:

Where

• ur = rated wind speed


• uc = cut-in speed, the speed at which the electrical power output rises above zero and power
production starts
• uf = furling wind speed, the speed at which the turbine is shut down to prevent structural damage

As seen in the figure, we assume that output power increases between uc and ur , then is at a constant
maximum value between ur and uf . Power output is zero for all other conditions.

Derive Equation for Average Power of Wind Turbine

I. Define piecewise expression for power

We define a piecewise function that described turbine power.


syms Per C_1 C_2 k u u_c u_f u_r
Pe = piecewise(u < u_c, 0, u_c <= u <= u_r, C_1 + C_2 * u^k, (u_r <= u) <= u_f, Per, u_f < u, 0)

2-89
2 Symbolic Computations in MATLAB

Pe =
0 if u < uc

C1 + C2 uk if uc ≤ u ∧ u ≤ ur
Per if u ≤ uf ∧ ur ≤ u
0 if uf < u

Where variables C1 and C2 are defined as follows:

C_1 = (Per * u_c^k)/(u_c^k - u_r^k)

C_1 =
Per uck
uck − ur k

C_2 = Per/(u_r^k - u_c^k)

C_2 =
Per

uck − ur k

II. Define external wind conditions

The rated power output offers a good indication of a how much power a wind turbine is capable of
producing, however we'd like to estimate how much power (on average) the wind turbine will actually
deliver. To calculate average power, we need to account for external wind conditions. A Weibull
distribution does a good job at modeling the variance in wind, therefore the wind profile can be
estimated using the following probability density function:

b u b−1
a a
fu = (4)
u b
e a

In general, larger 'a' values indicate a higher median wind speed, and larger 'b' values indicate
reduced variability.

We use the Statistics and Machine Learning Toolbox to generate a “Weibull Distribution” (Statistics
and Machine Learning Toolbox) and illustrate the variability in wind at our wind farm site (a=12.5,
b=2.2):
a = 12.5;
b = 2.2;
N = 1000;
pd = makedist('Weibull','a',a,'b',b)

pd =
WeibullDistribution

Weibull distribution
A = 12.5
B = 2.2

r = wblrnd(a,b,[1 N])

r = 1×1000

2-90
Evaluating the Average Power Delivered by a Wind Turbine

6.0811 4.3679 17.3751 4.1966 8.7677 18.3517 13.9761 9.9363 3.0039 2.7

x = linspace(0,34,N);
y = pdf(pd,x);
plot(x,y,'LineWidth',2)
hold on
histogram(r,15,'Normalization','pdf')
hold off
title('Weibull Distribution of Wind Speeds')
xlabel('Wind Speed (m/s)')

III. Calculate average power

The average power output from a wind turbine can be obtained using the following integral:


Peaverage = ∫0 Pe(u) f (u)du (5)

Power is zero when wind speed is less than the cut in wind speed uc and greater than furling wind
speed uf . Therefore, the integral can be expressed as follows:

u u u
Peaverage = C1 ∫ucr f u du + C2 ∫ucr ub f u du + Per ∫u f f u du (6)
r

2-91
2 Symbolic Computations in MATLAB

There are two distinct integrals in equation (7). We plug equation (4) into these integrals and simplify
u b b u b−1
them using the substitutions: x = a
and dx = a a
du. This simplifies our original integrals to
the following:

1
∫ f u du = ∫ dx (7)
ex

x
∫ub f u du = ab ∫ dx (8)
ex

u b
Solving these integrals and then replacing x with a
yields:

syms a b x
int1 = int(exp(-x), x);
int1 = subs(int1, x, (u/a)^b)

int1 =
u b
− e− a

int2 = int(x * exp(-x) * a^b, x);


int2 = subs(int2, x, (u/a)^b)

int2 =
u b u b
−ab e− a +1
a

Substituting the results into equation (6) yields an equation for average power output of the wind
turbine.

Peavg = subs(C_1 * int1, u, u_r) - subs(C_1 * int1, u, u_c) + subs(C_2 * int2, u, u_r) - subs(C_2

Peavg =
uc b uc b ur b
uc b
uf b Per ab e− a +1 Per ab σ2 +1
− Per uck e− a Per uck σ2 a a
Per σ2 − Per e a + − − +
σ1 σ1 σ1 σ1

where

σ1 = uck − ur k

ur b
σ2 = e− a

IV. Conclusion

We have used the Symbolic Math Toolbox to develop a parametric equation which can be used to
perform simulation studies to determine the average power generated for various wind turbine
configurations and wind farm sites.

2-92
Developing an Algorithm for Undistorting an Image

Developing an Algorithm for Undistorting an Image

This example develops a mathematical model using the Symbolic Math Toolbox™ to undistort an
image and features a local function in the live script.

Background

Any real world point P X, Y, Z can be defined with respect to some 3-D world origin.

Relative to a camera lens, this 3-D point can be defined as p0, which is obtained by rotating and
translating P.

p0 = x0, y0, z0 = R P + t

The 3-D point p0 is then projected into the camera's image plane as a 2D point, (x1, y1).

x0 y0
x1 = , y1 =
z0 z0

When a camera captures an image, it does not precisely capture the real points, but rather a slightly
distorted version of the real points which can be denoted (x2, y2). The distorted points can be
described using the following function:

x2 = x1 1 + k1 r 2 + k2 r 4 + 2 p1 x1 y1 + p2 r 2 + 2 x12

y2 = y1 1 + k1 r 2 + k2 r 4 + 2 p2 x1 y1 + p1 r 2 + 2 y12

where:

k1, k2 = radial distortion coefficients of the lens

p1, p2 = tangential distortion coefficients of the lens

r = x12 + y12

Distortion

An example of lens distortion is shown below; original distorted image (left) and undistorted image
(right).

2-93
2 Symbolic Computations in MATLAB

Note the curvature of the lines toward the edges of the first image. For applications such as image
reconstruction and tracking, it is important to know the real world location of points. When we have a
distorted image, we know the distorted pixel locations (x2, y2). It's our goal to determine the
undistorted pixel locations (x1, y1) given (x2, y2) and the distortion coefficients of the particular lens.

While otherwise straightforward, the nonlinear nature of the lens distortion makes the problem
challenging.

Define Distortion Model

We begin by defining our distortion model:

% Parameters
syms k_1 k_2 p_1 p_2 real
syms r x y
distortionX = subs(x * (1 + k_1 * r^2 + k_2 * r^4) + 2 * p_1 * x * y + p_2 * (r^2 + 2 * x^2), r,

2
distortionX = p2 3 x2 + y2 + x k2 x2 + y2 + k1 x2 + y2 + 1 + 2 p1 x y

distortionY = subs(y * (1 + k_1 * r^2 + k_2 * r^4) + 2 * p_2 * x * y + p_1 * (r^2 + 2 * y^2), r,

2
distortionY = p1 x2 + 3 y2 + y k2 x2 + y2 + k1 x2 + y2 + 1 + 2 p2 x y

Radial Distortion k1 = 0

2-94
Developing an Algorithm for Undistorting an Image

We plot a grid of pixel locations assuming our lens has a radial distortion coefficient k1 = 0. Note that
distortion is smallest near the center of the image and largest near the edges.
% Set Parameters
parameters = [k_1 k_2 p_1 p_2];
parameterValues = [0 0 0 0];
plotLensDistortion(distortionX,distortionY,parameters,parameterValues)

spacing = 0.2000

distortionX = x

distortionY = y

Radial Distortion k1 = 0 . 15

Explore the sensitivity to changes in k1.

% Set Parameters
parameters = [k_1 k_2 p_1 p_2];
parameterValues = [0.15 0 0 0];
plotLensDistortion(distortionX,distortionY,parameters,parameterValues)

spacing = 0.2000

distortionX =
3 x2 3 y2
x + +1
20 20

2-95
2 Symbolic Computations in MATLAB

distortionY =
3 x2 3 y2
y + +1
20 20

Calculate Inverse Distortion Model

Given a camera's lens distortion coefficients and a set of distorted pixel locations (x2, y2), we want to
be able to calculate the undistorted pixel locations (x1, y1). We will look at the specific case where all
distortion coefficients are zero except for k1 which equals 0.2.

We begin by defining the distortion coefficients.

syms X Y positive
eq1 = X == distortionX

2
eq1 = X = p2 3 x2 + y2 + x k2 x2 + y2 + k1 x2 + y2 + 1 + 2 p1 x y

eq2 = Y == distortionY

2
eq2 = Y = p1 x2 + 3 y2 + y k2 x2 + y2 + k1 x2 + y2 + 1 + 2 p2 x y

We define the distortion equations for given distortion coefficients, and solve for the undistorted pixel
locations (x1, y1).

2-96
Developing an Algorithm for Undistorting an Image

parameters = [k_1 k_2 p_1 p_2];


parameterValues = [0.2 0 0 0];
eq1 = expand(subs(eq1, parameters, parameterValues))

eq1 =
x3 x y2
X= + +x
5 5

eq2 = expand(subs(eq2, parameters, parameterValues))

eq2 =
x2 y y3
Y= + +y
5 5

Result = solve([eq1, eq2], [x,y], 'MaxDegree', 3,'Real',true)

Result = struct with fields:


x: (X*(((5*Y^3)/(2*(X^2 + Y^2)) + ((25*Y^6)/(4*(X^2 + Y^2)^2) + (125*Y^6)/(27*(X^2 + Y^2)^3))
y: ((5*Y^3)/(2*(X^2 + Y^2)) + ((25*Y^6)/(4*(X^2 + Y^2)^2) + (125*Y^6)/(27*(X^2 + Y^2)^3))^(1/

Since element 1 is the only real solution, we will extract that expression into its own variable.
[Result.x Result.y]

ans =
X σ1
σ1
Y

where

5 Y2
σ1 = σ2 −
3 X + Y 2 σ2
2

1/3
5 Y3 25 Y 6 125 Y 6
σ2 = + +
2 X2 + Y 2 4 X2 + Y 2
2
27 X 2 + Y 2
3

Now we have analytical expressions for the pixel locations X and Y which we can use to undistort our
images.

Function for Drawing the Lens Distortion


function plotLensDistortion(distortionX,distortionY,parameters,parameterValues)
% distortionX is the expression describing the distorted x coordinate
% distortionY is the expression describing the distorted y coordinate
% k1 and k2 are the radial distortion coefficients
% p1 and p2 are the tangential distortion coefficients

syms x y

% This is the grid spacing over the image


spacing = 0.2

% Inspect and parametrically substitute in the values for k_1 k_2 p_1 p_2
distortionX = subs(distortionX,parameters,parameterValues)
distortionY = subs(distortionY,parameters,parameterValues)

2-97
2 Symbolic Computations in MATLAB

% Loop over the grid


for x_i = -1:spacing:1
for y_j = -1:spacing:1

% Compute the distorted location


xout = subs(distortionX, {x,y}, {x_i,y_j});
yout = subs(distortionY, {x,y}, {x_i,y_j});

% Plot the original point


plot(x_i,y_j, 'o', 'Color', [1.0, 0.0, 0.0])
hold on

% Draw the distortion direction with Quiver


p1 = [x_i,y_j]; % First Point
p2 = [xout,yout]; % Second Point
dp = p2-p1; % Difference
quiver(p1(1),p1(2),dp(1),dp(2),'AutoScale','off','MaxHeadSize',1,'Color',[0 0 1])

end
end
hold off
grid on

end

2-98
Electric Dipole Moment and Radiation Power

Electric Dipole Moment and Radiation Power

This example finds the average radiation power of two attracting charges moving in an elliptical orbit
(an electric dipole).

Common Center of Mass

The two opposite charges, e1 and e2, form an electric dipole. The masses of the charged particles are
m1 and m2, respectively. For the common center of mass m1*r1 + m2*r2 = 0, where r1 and r2 are
distance vectors to the charged particles. The distance between charged particles is r = r1 - r2.

syms m1 m2 e1 e2 r1 r2 r
[r1,r2] = solve(m1*r1 + m2*r2 == 0, r == r1 - r2, r1, r2)

r1 =
m2 r
m1 + m2

r2 =
m1 r

m1 + m2

Dipole Moment

Find the dipole moment of this system:

d = e1*r1 + e2*r2;
simplify(d)

ans =
r e1 m2 − e2 m1
m1 + m2

2-99
2 Symbolic Computations in MATLAB

Radiation Power per Unit of Time

2 2
According to the Larmor formula, the total power radiated in a unit of time is J = d̈ , or, in terms
3c3
2 m1m2 e1 e2 2 2
of the distance between the charged particles, J = − r̈ . Here dot means a
3c m1 + m2 m1 m2
3
α
time derivative. Coulomb's law mr̈ = − lets you find the values of acceleration r̈ in terms of the
r2
m1m2
reduced mass of the system, m = , and the product of the charges of the particles,
m1 + m2
α = e1e2 .

alpha = sym('alpha');
syms m c
m = m1*m2/(m1 + m2);
r2 = -alpha/(m*r^2);

J = simplify(subs(2/(3*c^3)*d^2, r, r2))

J =
2
2 α2 e1 m2 − e2 m1
3 c3 m12 m22 r 4

Parameters of the Elliptical Orbit

The major semiaxis a and eccentricity ϵ of an elliptical orbit are given by the following expressions,
where E is the total orbital energy, and L = mr 2ϕ̇ is the angular momentum.

syms E L phi
a = alpha/(2*E)

a =
α
2E

eccentricity = sqrt(1-2*E*L^2/(m*alpha^2))

eccentricity =
2 E L2 m1 + m2
1−
α2 m1 m2

The equation of an elliptical orbit, 1 + ϵcosϕ = a 1 − ϵ2 /r, lets you express the distance r in terms of
the angle phi.

r = a*(1 - eccentricity^2)/(1 + eccentricity*cos(phi));

Averaged Radiation Power

The average radiation power of two charged particles moving in an elliptical orbit is an integral of the


T
radiation power over one full cycle of motion, normalized by the period of motion, Javg = 1/T J dt.
0
The period of motions T is

T = 2*pi*sqrt(m*a^3/alpha);

2-100
Electric Dipole Moment and Radiation Power

Changing the integration variable t to phi, you get the following result. Use the simplify function
to get a shorter integration result. Here, use subs to evaluate J.

J = subs(J);
Javg = simplify(1/T*int(J*m*r^2/L, phi, 0, 2*pi))

Javg =
2
2 2 α2 e1 m2 − e2 m1 2 E L2 m1 + 2 E L2 m2 − 3 α2 m1 m2

3 α2 m1 m2
3 L5 c3 m1 + m2
E3 m1 + m2

If One Particle is Much Heavier Than the Other

Estimate the average radiation power of the electric dipole with one particle much heavier than the
over, m1>>m2. For this, compute the limit of the expression for radiation power, assuming that m1
tends to infinity.

limJ = limit(Javg, m1, Inf);


simplify(limJ)

ans =
2 2 α2 e22 2 E L2 − 3 α2 m2

α2 m2
3 L5 c3
E3

2-101
2 Symbolic Computations in MATLAB

Validate Simulink Model Using Symbolic Math Toolbox

This example shows how to model a bouncing ball, which is a classical hybrid dynamic system. This
model includes both continuous dynamics and discrete transitions. It uses the Symbolic Math
Toolbox™ to help explain some of the theory behind ODE solving in the “Simulation of Bouncing Ball”
(Simulink).

Assumptions

• The ball rebounds with no angle


• There is no drag
• Height at time t=0 is 10 m
• Thrown with upwards velocity of 15 m/s

Derivation

The coefficient of restitution is defined as

Cr = vb − va /ua − ub

where v is the speed of object before impact and u is the speed after.

We split the second order differential equation

2
d h
= −g
dt2

into

dh h(t + Δt) − h(t)


= v discretized as = v(t)
dt Δt

and

2-102
Validate Simulink Model Using Symbolic Math Toolbox

dv v(t + Δt) − v(t)


= − g discretized as = −g
dt Δt

We will use basic 1st order numerical integration using forward Euler.

h(t + Δt) = h(t) + v(t)Δt

v(t + Δt) = v(t) − gΔt

Solve the Problem Analytically

Using the Symbolic Math Toolbox, we can approach the problem analytically. This allows us to solve
certain problems more easily, such as determining precisely when the ball first hits the ground
(below).

Declare our symbolic variables.

syms g t H(t) h_0 v_0

2
d h dh dv
Split the second order differential equation = − ginto = v and = − g.
dt 2 dt dt

Dh = diff(H);
D2h = diff(H, 2) == g

D2h(t) =
∂2
H t =g
∂t2

Solve the ODE using dsolve:

eqn = dsolve(D2h, H(0) == h_0, Dh(0) == v_0)

eqn =
g t2
+ v0 t + h0
2

Parametrically explore the parabolic profile of motion using subs:

eqn = subs(eqn, [h_0, v_0, g], [10, 15, -9.81])

eqn =
981 t2
− + 15 t + 10
200

Find the time at which the ball hits the ground by solving for zero:

assume(t > 0)
tHit = solve(eqn == 0)

tHit =
20 5 26 500
+
109 327

Visualize the solution:

2-103
2 Symbolic Computations in MATLAB

fplot(eqn,[0 10])
ylim([0 25])

Format your exact results using variable precision arithmetic with vpa:
disp(['The ball with an initial height of 10m and velocity of 15m/s will hit the ground at ' char

The ball with an initial height of 10m and velocity of 15m/s will hit the ground at 3.621 seconds

Solve the Problem Numerically

Setup Simulation Parameters

Properties of the ball


c_bounce = .9; % Bouncing's coefficient of restitution; perfect restitution would be 1

Properties of the simulation


gravity = 9.8; % Gravity's acceleration (m/s)
height_0 = 10; % Initial height at time t=0 (m)
velocity_0=15; % Initial velocity at time t=0 (m/s)

Declaring the simulation time step


dt = 0.05; % Animation timestep (s)
t_final = 25; % Simulate period (s)
t = 0:dt:t_final; % Timespan
N = length(t); % Number of iterations

2-104
Validate Simulink Model Using Symbolic Math Toolbox

Initialize simulation quantities

h=[]; % Height of the ball as a function of time (m)


v=[]; % Velocity of the ball (m/sec) as a function of time (m/s)
h(1)=height_0;
v(1)=velocity_0;

Simulate the bouncing ball (we will use basic 1st order numerical integration using forward Euler):

for i=1:N-1

v(i+1)=v(i)-gravity*dt;
h(i+1)=h(i)+v(i)*dt;

% When the ball bounces (the height is less than 0),


% reverse the velocity and recalculate the position.
% Using the coefficient of restitution
if h(i+1) < 0

v(i)=-v(i)*c_bounce;
v(i+1)=v(i)-gravity*dt;
h(i+1)=0+v(i)*dt;

end

end

Visualize and validate the simulation

plot(t,h,'o')
hold on
fplot(eqn,[0 10])
title('Height over time')
ylim([0 25])
hold off

2-105
2 Symbolic Computations in MATLAB

plot(t,v)
title('Velocity over time')

2-106
Validate Simulink Model Using Symbolic Math Toolbox

Validate Numerics with Analytics

Compare your analytical results with your numeric results.

As a reminder the time of impact was:

disp(['The ball with an initial height of 10m and velocity of 15m/s will hit the ground at ' char

The ball with an initial height of 10m and velocity of 15m/s will hit the ground at 3.621 seconds

From the numerical simulation we can find the closest value in the simulation when h ti ≈ 0

i = ceil(double(tHit/dt));
t([i-1 i i+1])

ans = 1×3

3.5500 3.6000 3.6500

plot(t,h,'o')
hold on
fplot(eqn,[0 10])
plot(t([i-1 i i+1 ]),h([i-1 i i+1 ]),'*R')
title('Height over time')
xlim([0 5])
ylim([0 25])
hold off

2-107
2 Symbolic Computations in MATLAB

2-108
3

Mathematics

• “Solve Algebraic Equations” on page 3-3


• “Solve System of Algebraic Equations” on page 3-7
• “Troubleshoot Equation Solutions from solve Function” on page 3-17
• “Solve Equations Numerically” on page 3-21
• “Solve System of Linear Equations” on page 3-30
• “Select Numeric or Symbolic Solver” on page 3-33
• “Solve Parametric Equations in ReturnConditions Mode” on page 3-34
• “Solve Algebraic Equation Using Live Editor Task” on page 3-36
• “Solve Differential Equation” on page 3-43
• “Solve a System of Differential Equations” on page 3-47
• “Solve a Second-Order Differential Equation Numerically” on page 3-52
• “Solve Partial Differential Equation of Tsunami Model” on page 3-54
• “Solve Differential Algebraic Equations (DAEs)” on page 3-61
• “Solve Semilinear DAE System” on page 3-70
• “Solve DAEs Using Mass Matrix Solvers” on page 3-77
• “Analyze and Manipulate Differential Algebraic Equations” on page 3-82
• “Derive and Apply Inverse Kinematics to Two-Link Robot Arm” on page 3-89
• “Gauss-Laguerre Quadrature Evaluation Points and Weights” on page 3-96
• “Simulate a Stochastic Process Using the Feynman–Kac Formula” on page 3-106
• “The Black–Scholes Formula for Call Option Price” on page 3-114
• “Choose Function to Rearrange Expression” on page 3-119
• “Extract Numerators and Denominators of Rational Expressions” on page 3-127
• “Simplify Symbolic Expressions” on page 3-129
• “Simplify Symbolic Expressions Using Live Editor Task” on page 3-134
• “Substitute Variables in Symbolic Expressions” on page 3-140
• “Substitute Elements in Symbolic Matrices” on page 3-142
• “Substitute Scalars with Matrices” on page 3-144
• “Evaluate Symbolic Expressions Using subs” on page 3-146
• “Abbreviate Common Terms in Long Expressions” on page 3-147
• “Harmonic Analysis of Transfer Function Output” on page 3-150
• “Explore Single-Period Asset Arbitrage” on page 3-156
• “Analytical Solutions of the Inverse Kinematics of a Humanoid Robot” on page 3-160
• “Differentiation” on page 3-171
• “Integration” on page 3-176
• “Taylor Series” on page 3-182
3 Mathematics

• “Fourier and Inverse Fourier Transforms” on page 3-184


• “Solve Differential Equations of RLC Circuit Using Laplace Transform” on page 3-188
• “Solve Difference Equations Using Z-Transform” on page 3-195
• “Symbolic Summation” on page 3-200
• “Padé Approximant” on page 3-202
• “Limits” on page 3-209
• “Find Asymptotes, Critical, and Inflection Points” on page 3-212
• “Functional Derivatives Tutorial” on page 3-217
• “Learn Calculus in the Live Editor” on page 3-222
• “Differentiation” on page 3-227
• “Integration” on page 3-235
• “Interactive Calculus in Live Editor” on page 3-239
• “Maxima, Minima, and Inflection Points” on page 3-241
• “Find Extremum of Multivariate Function and Its Approximation” on page 3-250
• “Padé Approximant of Time-Delay Input” on page 3-254
• “Solve Partial Differential Equation of Nonlinear Heat Transfer” on page 3-260
• “Symbolic Matrix Computation” on page 3-267
• “Linear Algebraic Operations” on page 3-274
• “Basic Algebraic Operations” on page 3-278
• “Singular Value Decomposition” on page 3-280
• “Eigenvalues” on page 3-282
• “Jordan Canonical Form” on page 3-286
• “Eigenvalues of the Laplace Operator” on page 3-288
• “Hilbert Matrices and Their Inverses” on page 3-298
• “Markov Chain Analysis and Stationary Distribution” on page 3-302
• “Matrix Rotations and Transformations” on page 3-307
• “Clear Assumptions and Reset the Symbolic Engine” on page 3-314
• “Recognize and Avoid Round-Off Errors” on page 3-317
• “Increase Speed by Reducing Precision” on page 3-321
• “Prime Factorizations” on page 3-323
• “Handling Large Integers to Solve the 196 Problem” on page 3-326

3-2
Solve Algebraic Equations

Solve Algebraic Equations


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

In this section...
“Solve an Equation” on page 3-3
“Return the Full Solution to an Equation” on page 3-3
“Work with the Full Solution, Parameters, and Conditions Returned by solve” on page 3-4
“Visualize and Plot Solutions Returned by solve” on page 3-5
“Simplify Complicated Results and Improve Performance” on page 3-6

Solve an Equation
If eqn is an equation, solve(eqn, x) solves eqn for the symbolic variable x.

Use the == operator to specify the familiar quadratic equation and solve it using solve.
syms a b c x
eqn = a*x^2 + b*x + c == 0;
solx = solve(eqn, x)

solx =
-(b + (b^2 - 4*a*c)^(1/2))/(2*a)
-(b - (b^2 - 4*a*c)^(1/2))/(2*a)

solx is a symbolic vector containing the two solutions of the quadratic equation. If the input eqn is
an expression and not an equation, solve solves the equation eqn == 0.

To solve for a variable other than x, specify that variable instead. For example, solve eqn for b.
solb = solve(eqn, b)

solb =
-(a*x^2 + c)/x

If you do not specify a variable, solve uses symvar to select the variable to solve for. For example,
solve(eqn) solves eqn for x.

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

3-3
3 Mathematics

three output variables: for the solution to x, for the parameters in the solution, and for the conditions
on the solution.

syms x
[solx, param, cond] = solve(cos(x) == -sin(x), x, 'ReturnConditions', true)

solx =
pi*k - pi/4
param =
k
cond =
in(k, 'integer')

solx contains the solution for x, which is pi*k - pi/4. The param variable specifies the parameter
in the solution, which is k. The cond variable specifies the condition in(k, 'integer') on the
solution, which means k must be an integer. Thus, solve returns a periodic solution starting at pi/4
which repeats at intervals of pi*k, where k is an integer.

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.

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

3-4
Solve Algebraic Equations

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
grid on
fplot(-sin(x))
title('Both sides of equation cos(x) = -sin(x)')
legend('cos(x)','-sin(x)','Location','best','AutoUpdate','off')

Calculate the values of the functions at the values of x, and superimpose the solutions as points using
scatter.

yvalues = cos(xvalues)

yvalues =
−0.70710678118654752440084436210485
0.70710678118654752440084436210485
−0.70710678118654752440084436210485
0.70710678118654752440084436210485

scatter(xvalues, yvalues)

3-5
3 Mathematics

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

See Also

Related Examples
• “Solve System of Linear Equations” on page 3-30
• “Solve Differential Equation” on page 3-43
• “Solve Differential Algebraic Equations (DAEs)” on page 3-61

3-6
Solve System of Algebraic Equations

Solve System of Algebraic Equations

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

Handle the Output of solve

Suppose you have the system

x2 y2 = 0
y
x− = α,
2

and you want to solve for x and y. First, create the necessary symbolic objects.

syms x y a

There are several ways to address the output of solve. One way is to use a two-output call. The call
returns the following.

[solx,soly] = solve(x^2*y^2 == 0, x-y/2 == a)

solx =
a
0

soly =
0
−2 a

Modify the first equation to x2 y2 = 1. The new system has more solutions. Four distinct solutions are
produced.

[solx,soly] = solve(x^2*y^2 == 1, x-y/2 == a)

solx =
a a2 − 2

2 2
a a2 + 2

2 2
a a2 − 2
+
2 2
a a2 + 2
+
2 2

soly =
−a − a2 − 2
−a − a2 + 2
a2 − 2 − a
a2 + 2 − a

3-7
3 Mathematics

Since you did not specify the dependent variables, solve uses symvar to determine the variables.

This way of assigning output from solve is quite successful for “small” systems. For instance, if you
have a 10-by-10 system of equations, typing the following is both awkward and time consuming.

[x1,x2,x3,x4,x5,x6,x7,x8,x9,x10] = solve(...)

To circumvent this difficulty, solve can return a structure whose fields are the solutions. For
example, solve the system of equations u^2 - v^2 = a^2, u + v = 1, a^2 - 2*a = 3. The
solver returns its results enclosed in a structure.

syms u v a
S = solve(u^2 - v^2 == a^2, u + v == 1, a^2 - 2*a == 3)

S = struct with fields:


a: [2x1 sym]
u: [2x1 sym]
v: [2x1 sym]

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

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]

3-8
Solve System of Algebraic Equations

sol =
2v 5u

3 3
4u v

3 3

[A,b] = equationsToMatrix(eqns,x,y);
z = A\b

z =
2v 5u

3 3
4u v

3 3

Thus, sol and z produce the same solution, although the results are assigned to different variables.

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;
a.YTickLabel = M;
title('Plot of System of Equations')
legend('sin(x)+cos(y) == 4/5','sin(x)*cos(y) == 1/10',...
'Location','best','AutoUpdate','off')

3-9
3 Mathematics

The solutions lie at the intersection of the two plots. This shows the system has repeated, periodic
solutions. To solve this system of equations for the full solution set, use solve and set the
ReturnConditions option to true.

S = solve(eqn1,eqn2,'ReturnConditions',true)

S = struct with fields:


x: [2x1 sym]
y: [2x1 sym]
parameters: [z z1]
conditions: [2x1 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

ans =
z1
z1

3-10
Solve System of Algebraic Equations

S.y

ans =
z
z

S.parameters

ans = z z1

S.conditions

ans =
z + acos σ3 z − acos σ3 π − z1 + σ1 z1 + σ1
∈ℤ∨ ∈ℤ ∧ − ∈ℤ∨ ∈ℤ
2π 2π 2π 2π
z1 − π + asin σ3 z1 − asin σ3 z + σ2 z − σ2
∈ℤ∨ ∈ℤ ∧ ∈ℤ∨ ∈ℤ
2π 2π 2π 2π

where

6 2
σ1 = asin −
10 5

2 6
σ2 = acos −
5 10

6 2
σ3 = +
10 5

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);
scatter(Srange.x,Srange.y,'k')

3-11
3 Mathematics

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.

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)

paramx = z1

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

paramy = z

Solve the first solution of x for the parameter paramx.

3-12
Solve System of Algebraic Equations

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

solparamx =
6 2 6 2 6 2 6 2
π + asin − asin − − π −asin − −2 π − asin −
10 5 10 5 10 5 10 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 =
6 2 6 2 6 2 6 2
acos + acos + − 2 π −acos + 2 π − acos +
10 5 10 5 10 5 10 5

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

assume(S.parameters,'clear')
assumptions

ans =

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.

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

solparamx =
π + σ1 σ1 − π −σ1 −2 π − σ1
σ2 π − σ2 σ2 − 2 π −π − σ2

where

6 2
σ1 = asin −
10 5

6 2
σ2 = asin +
10 5

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

solparamy =
σ2 σ2 − 2 π −σ2 2 π − σ2
σ1 σ1 − 2 π −σ1 2 π − σ1

where

2 6
σ1 = acos −
5 10

6 2
σ2 = acos +
10 5

3-13
3 Mathematics

The first rows of paramx and paramy form the first solution to the system of equations, and the
second rows form the second solution.

To find the values of x and y for these values of paramx and paramy, use subs to substitute for
paramx and paramy in S.x and S.y.

solx(1,:) = subs(S.x(1), paramx, solparamx(1,:));


solx(2,:) = subs(S.x(2), paramx, solparamx(2,:))

solx =
π + σ1 σ1 − π −σ1 −2 π − σ1
σ2 π − σ2 σ2 − 2 π −π − σ2

where

6 2
σ1 = asin −
10 5

6 2
σ2 = asin +
10 5

soly(1,:) = subs(S.y(1), paramy, solparamy(1,:));


soly(2,:) = subs(S.y(2), paramy, solparamy(2,:))

soly =
σ2 σ2 − 2 π −σ2 2 π − σ2
σ1 σ1 − 2 π −σ1 2 π − σ1

where

2 6
σ1 = acos −
5 10

6 2
σ2 = acos +
10 5

Note that solx and soly are the two sets of solutions to x and to y. The full sets of solutions to the
system of equations are the two sets of points formed by all possible combinations of the values in
solx and soly.

Plot these two sets of points using scatter. Overlay them on the plot of the equations. As expected,
the solutions appear at the intersection of the plots of the two equations.

for i = 1:length(solx(1,:))
for j = 1:length(soly(1,:))
scatter(solx(1,i), soly(1,j), 'k')
scatter(solx(2,i), soly(2,j), 'k')
end
end

3-14
Solve System of Algebraic Equations

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.

Use vpa to convert the symbolic solutions solx and soly to numeric form.

vpa(solx)

ans =
2.9859135500977407388300518406219 −3.2972717570818457380952349259371 0.155679103492052499632591542
0.70095651347102524787213653614929 2.4406361401187679905905068471302 −5.5822287937085612290531502

vpa(soly)

ans =
0.86983981332387137135918515549046 −5.4133454938557151055661016110685 −0.8698398133238713713591851
1.4151172233028441195987301489821 −4.8680680838767423573265566175769 −1.4151172233028441195987301

3-15
3 Mathematics

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

3-16
Troubleshoot Equation Solutions from solve Function

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 3-17
“Apply Simplification Rules” on page 3-17
“Use Assumptions to Narrow Results” on page 3-18
“Simplify Solutions” on page 3-19
“Tips” on page 3-19

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.

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.

3-17
3 Mathematics

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)
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 by recreating it using syms.

syms x

Alternatively, to make several assumptions, use the & operator. Make the following assumptions, and
solve the following equations.

syms a b c f g h y
assume(f == c & a == h & a~= 0)
S = solve([a*x + b*y == c, h*x - g*y == f], [x, y], 'ReturnConditions', true);

3-18
Troubleshoot Equation Solutions from solve Function

S.x
S.y
S.conditions

ans =
f/h
ans =
0
ans =
b + g ~= 0

Under the specified assumptions, the solution is x = f/h and y = 0 under the condition b + g ~=
0.

Clear the assumptions on the variables for further computations by recreating them using syms.

syms a c f h

Simplify Solutions
The solve function does not call simplification functions for the final results. To simplify the
solutions, call simplify.

Solve the following equation. Convert the numbers to symbolic numbers using sym to return a
symbolic result.
syms x
S = solve((sin(x) - 2*cos(x))/(sin(x) + 2*cos(x)) == 1/2, x)

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

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.

3-19
3 Mathematics

sym(13)/5
sym(133333333333333333333)/5
sym('133333333333333333333')/5

ans =
13/5
ans =
133333333333333327872/5
ans =
133333333333333333333/5

Placing the number in quotes and using sym provides the highest accuracy.
• If possible, simplify the system of equations manually before using solve. Try to reduce the
number of equations, parameters, and variables.

3-20
Solve Equations Numerically

Solve Equations Numerically

Symbolic Math Toolbox™ offers both numeric and symbolic equation solvers. For a comparison of
numeric and symbolic solvers, see “Select Numeric or Symbolic Solver” on page 3-33. An equation
or a system of equations can have multiple solutions. To find these solutions numerically, use the
function vpasolve. For polynomial equations, vpasolve returns all solutions. For nonpolynomial
equations, vpasolve returns the first solution it finds. These examples show you how to use
vpasolve to find solutions to both polynomial and nonpolynomial equations, and how to obtain these
solutions to arbitrary precision.

Find All Roots of a Polynomial Function

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

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

sol =
1.0240240759053702941448316563337
−0.88080620051762149639205672298326 + 0.50434058840127584376331806592405 i
−0.88080620051762149639205672298326 − 0.50434058840127584376331806592405 i
−0.22974795226118163963098570610724 + 0.96774615576744031073999010695171 i
−0.22974795226118163963098570610724 − 0.96774615576744031073999010695171 i
0.7652087814927846556172932675903 + 0.83187331431049713218367239317121 i
0.7652087814927846556172932675903 − 0.83187331431049713218367239317121 i

vpasolve returns seven roots of the function, as expected, because the function is a polynomial of
degree seven.

Find Zeros of a Nonpolynomial Function Using Search Ranges and Starting Points

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

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

3-21
3 Mathematics

Use vpasolve to find a zero of the function f. Note that vpasolve returns only one solution of a
nonpolynomial equation, even if multiple solutions exist. On repeated calls, vpasolve returns the
same result.

f = exp(x/7)*cos(2*x);
for k = 1:3
vpasolve(f,x)
end

ans = −7.0685834705770347865409476123789

ans = −7.0685834705770347865409476123789

ans = −7.0685834705770347865409476123789

To find multiple solutions, set the option 'Random' to true. This makes vpasolve choose starting
points randomly. For information on the algorithm that chooses random starting points, see
“Algorithms” on page 7-1626 on the vpasolve page.

for k = 1:3
vpasolve(f,x,'Random',true)
end

ans = −226.98006922186256147892598444194

ans = 98.174770424681038701957605727484

ans = 52.621676947629036744249276669932

3-22
Solve Equations Numerically

To find a zero close to x = 10, set the starting point to 10.

vpasolve(f,x,10)

ans = 10.210176124166828025003590995658

To find a zero close to x = 1000, set the starting point to 1000.

vpasolve(f,x,1000)

ans = 999.8118620049516981407362567287

To find a zero in the range 15 ≤ x ≤ 25, set the search range to [15 25].

vpasolve(f,x,[15 25])

ans = 21.205750411731104359622842837137

To find multiple zeros in the range [15 25], you cannot call vpasolve repeatedly because it returns
the same result on each call, as previously shown. Instead, set the search range and set 'Random' to
true.

for k = 1:3
vpasolve(f,x,[15 25],'Random',true)
end

ans = 21.205750411731104359622842837137

ans = 21.205750411731104359622842837137

ans = 16.493361431346414501928877762217

Because 'Random' selects starting points randomly, the same solution might be found on successive
calls.

Find All Zeros in a Specified Search Range

Create a function findzeros to systematically find all zeros for f in a given search range, within a
specified error tolerance. The function starts with the input search range and calls vpasolve to find
a zero. Then, it splits the search range into two around the zero value and recursively calls itself with
the new search ranges as inputs to find more zeros.

The function is explained section by section here.

Declare the function with the three inputs and one output. The first input is the function, the second
input is the range, and the optional third input allows you to specify the error between a zero and the
higher and lower bounds generated from it.

function sol = findzeros(f,range,err)

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

3-23
3 Mathematics

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. Save this function as findzeros.m in the current
folder.

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 [15 25] to find all zeros in that range for f(x) = exp(x/
7)*cos(2*x), within the default error tolerance.

3-24
Solve Equations Numerically

syms f(x)
f(x) = exp(x/7)*cos(2*x);
sol = findzeros(f,[15 25])'

sol =
16.493361431346414501928877762217
18.064157758141311121160199453857
19.634954084936207740391521145497
21.205750411731104359622842837137
22.776546738526000978854164528776
24.347343065320897598085486220416

Obtain Solutions to Arbitrary Precision

Use digits to set the precision of the solutions returned by vpasolve. By default, vpasolve
returns solutions to a precision of 32 significant figures.

f = exp(x/7)*cos(2*x);
vpasolve(f)

ans = −7.0685834705770347865409476123789

Use digits to increase the precision to 64 significant figures. When modifying digits, ensure that
you save its current value so that you can restore it.

digitsOld = digits;
digits(64)
vpasolve(f)

ans = −7.068583470577034786540947612378881489443631148593988097193625333

Next, change the precision of the solutions to 16 significant figures.

digits(16)

Solve Multivariate Equations Using Search Ranges

Consider the following system of equations.

z = 10 cos x + cos y
z = x + y2 − 0 . 1x2 y
x + y − 2.7 = 0

A plot of the equations for 0 ≤ x ≤ 2 . 5 and 0 ≤ x ≤ 2 . 5 shows that the three surfaces intersect in two
points. To better visualize the plot, change the line of sight using view.

syms x y z
eqn1 = z == 10*(cos(x) + cos(y));
eqn2 = z == x+y^2-0.1*x^2*y;
eqn3 = x+y-2.7 == 0;
equations = [eqn1 eqn2 eqn3];
fimplicit3(equations)
axis([0 2.5 0 2.5 -20 10])
title('System of Multivariate Equations')
view(69,28)

3-25
3 Mathematics

Use vpasolve to find a point where the surfaces intersect. The function vpasolve returns a
structure. To access the x-, y-, and z-values of the solution, index into the structure.

sol = vpasolve(equations);
[sol.x sol.y sol.z]

ans = 2.369747722454798 0.3302522775452021 2.293354376823228

To search a region of the solution space, specify search ranges for the variables. If you specify the
ranges 0 ≤ x ≤ 1 . 5 and 1 . 5 ≤ y ≤ 2 . 5, then vpasolve function searches the bounded area shown.

3-26
Solve Equations Numerically

Use vpasolve to find a solution for this search range. To omit a search range for z, set the third
search range to [NaN NaN].

vars = [x y z];
range = [0 1.5; 1.5 2.5; NaN NaN];
sol = vpasolve(equations,vars,range);
[sol.x sol.y sol.z]

ans = 0.9106266172563336 1.789373382743666 3.964101572135625

To find multiple solutions, set the 'Random' option to true. This makes vpasolve use random
starting points on successive runs. The 'Random' option can be used in conjunction with search
ranges to make vpasolve use random starting points within a search range. Because 'Random'
selects starting points randomly, the same solution might be found on successive calls. Call
vpasolve repeatedly to ensure you find both solutions.

clear sol
range = [0 3; 0 3; NaN NaN];
for k = 1:5
temp = vpasolve(equations,vars,range,'Random',true);
sol(k,1) = temp.x;
sol(k,2) = temp.y;
sol(k,3) = temp.z;
end
sol

sol =

3-27
3 Mathematics

2.369747722454798 0.3302522775452021 2.293354376823228


2.369747722454798 0.3302522775452021 2.293354376823228
2.369747722454798 0.330252277545202 2.293354376823228
0.9106266172563336 1.789373382743666 3.964101572135625
0.9106266172563336 1.789373382743666 3.964101572135625

Plot the equations. Superimpose the solutions as a scatter plot of points with yellow X markers using
scatter3. To better visualize the plot, make two of the surfaces transparent using alpha and
change the line of sight using view.

vpasolve finds solutions at the intersection of the surfaces formed by the equations as shown.

clf
ax = axes;
h = fimplicit3(equations);
h(2).FaceAlpha = 0;
h(3).FaceAlpha = 0;
axis([0 2.5 0 2.5 -20 10])
hold on
scatter3(sol(:,1),sol(:,2),sol(:,3),600,'red','X','LineWidth',2)
title('Randomly Found Solutions in Specified Search Range')
cz = ax.Children;
view(69,28)
hold off

Lastly, restore the old value of digits for further calculations.

3-28
Solve Equations Numerically

digits(digitsOld)

3-29
3 Mathematics

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 3-30
“Solve System of Linear Equations Using solve” on page 3-31

Solve System of Linear Equations Using linsolve


A system of linear equations

a11x1 + a12x2 + … + a1nxn = b1


a21x1 + a22x2 + … + a2nxn = b2

am1x1 + am2x2 + … + amnxn = bm

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

a11 … a1n
A= ⋮ ⋱ ⋮
am1 ⋯ amn

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

b1
b = ⋮
bm

If you do not have the system of linear equations in the form AX = B, use equationsToMatrix to
convert the equations into this form. Consider the following system.

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

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]

3-30
Solve System of Linear Equations

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

2x + y + z = 2
−x + y − z = 3
x + 2y + 3z = − 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.

3-31
3 Mathematics

See Also

More About
• “Solve Algebraic Equations” on page 3-3
• “Solve System of Algebraic Equations” on page 3-7

3-32
Select Numeric or Symbolic Solver

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 be Returns approximate solutions. Precision can be
approximated using vpa. controlled arbitrarily using digits.
Returns a general form of the solution. For polynomial equations, returns all numeric
solutions that exist. For nonpolynomial equations,
returns the first numeric solution found.
General form allows insight into the solution. Numeric solutions provide less insight.
Runs slower. Runs faster.
Search ranges can be specified using inequalities. Search ranges and starting points can be
specified.
solve solves equations and inequalities that vpasolve does not solve inequalities, nor does it
contain parameters. solve equations that contain parameters.
solve can return parameterized solutions. vpasolve does not return parameterized
solutions.

vpasolve uses variable-precision arithmetic. You can control precision arbitrarily using digits. For
examples, see “Increase Precision of Numeric Calculations” on page 2-36.

See Also
solve | vpasolve

Related Examples
• “Solve Algebraic Equations” on page 3-3
• “Solve Equations Numerically” on page 3-21
• “Solve System of Linear Equations” on page 3-30

3-33
3 Mathematics

Solve Parametric Equations in ReturnConditions Mode

This example shows you how to solve parameterized algebraic equations using the Symbolic Math
Toolbox™.

To solve algebraic equations symbolically, use the solve function. The solve function can provide
complete information about all solutions of an equation, even if there are infinitely many, by
introducing a parameterization. It can also provide information under which conditions these
solutions are valid. To obtain this information, set the option ReturnConditions to true.

Solve the equation sin(C*x) = 1. Specify x as the variable to solve for. The solve function handles
C as a constant. Provide three output variables for the solution, the newly generated parameters in
the solution, and the conditions on the solution.

syms C x
eq = sin(C*x) == 1;
[solx, params, conds] = solve(eq, x, 'ReturnConditions', true)

solx =
π
2
+2πk
C

params = k

conds = k ∈ ℤ ∧ C ≠ 0

To verify the solution, substitute the solution into the equation using subs. To work on under the
assumptions in conds for the rest of this example, use assume. Test the solution using isAlways.
The isAlways function returns logical 1 (true) indicating that the solution always holds under the
given assumptions.

SolutionCorrect = subs(eq, x, solx)

SolutionCorrect =
π
sin + 2 π k = 1
2

assume(conds)
isAlways(SolutionCorrect)

ans = logical
1

To obtain one solution out of the infinitely many solutions, find a value of the parameters params by
solving the conditions conds for the parameters; do not specify the ReturnConditions option.
Substitute this value of k into the solution using subs to obtain a solution out of the solution set.

k0 = solve(conds, params)

k0 = 0

subs(solx, params, k0)

ans =

3-34
Solve Parametric Equations in ReturnConditions Mode

π
2C

To obtain a parameter value that satisfies a certain condition, add the condition to the input to solve.
Find a value of the parameter greater than 99/4 and substitute in to find the solution.

k1 = solve([conds, params > 99/4], params)

k1 = 26

subs(solx, params, k1)

ans =
105 π
2C

To find a solution in a specified interval, you can solve the original equation with the inequalities that
specify the interval.

[solx1, params1, conds1] = solve([eq, x > 2, x < 7], x, 'ReturnConditions', true)

solx1 =
π+4πk
2C

params1 = k

conds1 = 0 < C ∧ 4 C < π + 4 π k ∧ π + 4 π k < 14 C ∨ C < 0 ∧ π + 4 π k < 4 C ∧ 14 C < π + 4 π k

Alternatively, you can also use the existing solution, and restrict it with additional conditions. Note
that while the condition changes, the solution remains the same. The solve function expresses solx
and solx1 with different parameterizations, although they are equivalent.

[~, ~, conds2] = solve(x == solx, x < 7, x > 2, x, 'ReturnConditions', true)

conds2 =
4 4k+1 4k+1 14
< ∧ <
π C C π

Obtain those parameter values that satisfy the new condition, for a particular value of the constant C:

conds3 = subs(conds2, C, 5)

conds3 =
4 4k 1 4k 1 14
< + ∧ + <
π 5 5 5 5 π

solve(conds3, params)

ans =
2
3
4
5

3-35
3 Mathematics

Solve Algebraic Equation Using Live Editor Task

Starting in R2020a, you can interactively solve algebraic equations to obtain symbolic solutions using
the Solve Symbolic Equation task in the Live Editor. For more information on Live Editor tasks, see
“Add Interactive Tasks to a Live Script”.

These examples show you how to find the solutions of

• a trigonometric equation
• a cubic equation
• a system of cubic and linear equations

Solve a Trigonometric Equation

Find the solution of the trigonometric equation sin(x) + cos(x) = 0 with the assumption that x > π/2.

First, go to the Home tab, and create a live script by clicking New Live Script. Define the
symbolic variable x, and use the == operator to declare the equality sign of the trigonometric
equation. Use assume to set the assumption on x.

syms x
eqn = sin(x) + cos(x) == 0;
assume(x > pi/2);

In the Live Editor tab, run the code by clicking Run to store x with its assumption and eqn into
the current workspace.

Next, open the Solve Symbolic Equation task by selecting Task > Solve Symbolic Equation in the
Live Editor tab. To find the solution of the trigonometric equation, select the symbolic equation eqn
from the workspace. Specify x as the variable to solve for. Select the Return conditions option to
return the general solution and the analytic constraints under which it holds.

3-36
Solve Algebraic Equation Using Live Editor Task

You can ignore the assumption on x by selecting the Ignore properties option. Return the solution
without using the assumption that x > π/2.

3-37
3 Mathematics

To experiment with solving symbolic equations, you can repeat the previous steps for other system
equations and solver options. You can run the following examples by adding the code to the existing
live script or a new live script.

Solve a Cubic Equation

Find the solutions of the cubic equation x3 − 2x2 + y = 0.

Define the symbolic variables x and y using syms, and use the == operator to declare the equality
sign of the cubic equation.

syms x y
cubicEquation = x^3 - 2*x^2 + y == 0;

To find the solutions of the cubic equation, select the symbolic equation cubicEquation from the
workspace. Specify x as the variable to solve for.

The solver returns the symbolic solutions in terms of the root function. To express the root function
in terms of square roots, select the Expand all roots option.

3-38
Solve Algebraic Equation Using Live Editor Task

Solve a System of Equations

Solve the system of cubic and linear equations:

x3 − 2x2 + y = 0
y = 4x − 8

Define the symbolic variables x and y using syms. Use the == operator to declare the equality sign of
the equations. To declare the system of equations, combine the two symbolic equations into an array.

syms x y
cubicEquation = x^3 - 2*x^2 + y == 0;
linearEquation = y == 4*x - 8;
systemEquations = [cubicEquation linearEquation];

To find the solution of the system of equations, select the symbolic equation systemEquations from
the workspace. Specify x and y as the variables to solve for.

3-39
3 Mathematics

The solver returns real and complex solutions. To show real solutions only, select the Return real
solutions option.

3-40
Solve Algebraic Equation Using Live Editor Task

Generate Code

To view the code that a task used, click at the bottom of the task window. The task displays the
code block, which you can cut and paste to use or modify later in the existing script or a different
program. For example:

Because the underlying code is now part of your live script, you can continue to use the solutions
generated by the task for further processing. For example, you can plot the system of equations and
their real-valued solution.

3-41
3 Mathematics

See Also
Live Editor Tasks
Simplify Symbolic Expression | Solve Symbolic Equation

Functions
solve

Related Examples
• “Add Interactive Tasks to a Live Script”
• “Solve Algebraic Equations” on page 3-3

3-42
Solve Differential Equation

Solve Differential Equation

Solve a differential equation analytically by using the dsolve function, with or without initial
conditions. To solve a system of differential equations, see “Solve a System of Differential Equations”
on page 3-47.

In this section...
“First-Order Linear ODE” on page 3-43
“Solve Differential Equation with Condition” on page 3-43
“Nonlinear Differential Equation with Initial Condition” on page 3-44
“Second-Order ODE with Initial Conditions” on page 3-44
“Third-Order ODE with Initial Conditions” on page 3-44
“More ODE Examples” on page 3-45

First-Order Linear ODE


Solve this differential equation.

dy
= ty .
dt

First, represent y by using syms to create the symbolic function y(t).

syms y(t)

Define the equation using == and represent differentiation using the diff function.

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

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

Solve the equation using dsolve.

ySol(t) = dsolve(ode)

ySol(t) =
C1*exp(t^2/2)

Solve Differential Equation with Condition


In the previous solution, the constant C1 appears because no condition was specified. Solve the
equation with the initial condition y(0) == 2. The dsolve function finds a value of C1 that satisfies
the condition.

cond = y(0) == 2;
ySol(t) = dsolve(ode,cond)

ySol(t) =
2*exp(t^2/2)

3-43
3 Mathematics

If dsolve cannot solve your equation, then try solving the equation numerically. See “Solve a Second-
Order Differential Equation Numerically” on page 3-52.

Nonlinear Differential Equation with Initial Condition


Solve this nonlinear differential equation with an initial condition. The equation has multiple
solutions.

dy 2
+ y = 1,
dt
y 0 = 0.

syms y(t)
ode = (diff(y,t)+y)^2 == 1;
cond = y(0) == 0;
ySol(t) = dsolve(ode,cond)

ySol(t) =
exp(-t) - 1
1 - exp(-t)

Second-Order ODE with Initial Conditions


Solve this second-order differential equation with two initial conditions.
2
d y
= cos 2x − y,
dx2
y 0 = 1,
y′ 0 = 0.

Define the equation and conditions. The second initial condition involves the first derivative of y.
Represent the derivative by creating the symbolic function Dy = diff(y) and then define the
condition using Dy(0)==0.

syms y(x)
Dy = diff(y);

ode = diff(y,x,2) == cos(2*x)-y;


cond1 = y(0) == 1;
cond2 = Dy(0) == 0;

Solve ode for y. Simplify the solution using the simplify function.

conds = [cond1 cond2];


ySol(x) = dsolve(ode,conds);
ySol = simplify(ySol)

ySol(x) =
1 - (8*sin(x/2)^4)/3

Third-Order ODE with Initial Conditions


Solve this third-order differential equation with three initial conditions.

3-44
Solve Differential Equation

3
d u
= u,
dx3
u(0) = 1,
u′(0) = − 1,
u′′(0) = π .

Because the initial conditions contain the first- and second-order derivatives, create two symbolic
functions, Du = diff(u,x) and D2u = diff(u,x,2), to specify the initial conditions.

syms u(x)
Du = diff(u,x);
D2u = diff(u,x,2);

Create the equation and initial conditions, and solve it.

ode = diff(u,x,3) == u;
cond1 = u(0) == 1;
cond2 = Du(0) == -1;
cond3 = D2u(0) == pi;
conds = [cond1 cond2 cond3];

uSol(x) = dsolve(ode,conds)

uSol(x) =

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

Differential Equation MATLAB Commands


dy syms y(t)
+ 4y(t) = e−t, ode = diff(y)+4*y == exp(-t);
dt
cond = y(0) == 1;
y 0 = 1. ySol(t) = dsolve(ode,cond)

ySol(t) =
exp(-t)/3 + (2*exp(-4*t))/3
2
d y dy syms y(x)
2x2 + 3x − y = 0. ode = 2*x^2*diff(y,x,2)+3*x*diff(y,x)-y == 0;
dx2 dx
ySol(x) = dsolve(ode)

ySol(x) =
C1/(3*x) + C2*x^(1/2)
The Airy equation. syms y(x)
ode = diff(y,x,2) == x*y;
2 ySol(x) = dsolve(ode)
d y
= xy(x) .
dx2 ySol(x) =
C1*airy(0,x) + C2*airy(2,x)

3-45
3 Mathematics

Differential Equation MATLAB Commands


Puiseux series solution. syms y(x) a
ode = (x^2+1)*diff(y,x,2)-2*x*diff(y,x)+y == 0;
2 Dy = diff(y,x);
d y dy
x2 + 1 − 2x + y = 0. cond = [Dy(0) == a; y(0) == 5];
dx2 dx
ySol(x) = dsolve(ode,cond,'ExpansionPoint',0)

ySol(x) =
- (a*x^5)/120 - (5*x^4)/24 + (a*x^3)/6 - (5*x^2)/2 + a*x + 5

See Also
dsolve | odeFunction | odeToVectorField | reduceDifferentialOrder | daeFunction

Related Examples
• “Solve a System of Differential Equations” on page 3-47
• “Solve a Second-Order Differential Equation Numerically” on page 3-52
• “Solve Differential Algebraic Equations (DAEs)” on page 3-61

3-46
Solve a System of Differential Equations

Solve a System of Differential Equations

Solve a system of several ordinary differential equations in several variables by using the dsolve
function, with or without initial conditions. To solve a single differential equation, see “Solve
Differential Equation” on page 3-43.

Solve System of Differential Equations

Solve this system of linear first-order differential equations.

du
= 3u + 4v,
dt
dv
= − 4u + 3v .
dt

First, represent u and v by using syms to create the symbolic functions u(t) and v(t).
syms u(t) v(t)

Define the equations using == and represent differentiation using the diff function.
ode1 = diff(u) == 3*u + 4*v;
ode2 = diff(v) == -4*u + 3*v;
odes = [ode1; ode2]

odes(t) =

u t = 3u t +4v t
∂t

v t = 3v t −4u t
∂t

Solve the system using the dsolve function which returns the solutions as elements of a structure.
S = dsolve(odes)

S = struct with fields:


v: C1*cos(4*t)*exp(3*t) - C2*sin(4*t)*exp(3*t)
u: C2*cos(4*t)*exp(3*t) + C1*sin(4*t)*exp(3*t)

If dsolve cannot solve your equation, then try solving the equation numerically. See “Solve a Second-
Order Differential Equation Numerically” on page 3-52.

To access u(t) and v(t), index into the structure S.


uSol(t) = S.u

uSol(t) = C2 cos 4 t e3 t + C1 sin 4 t e3 t

vSol(t) = S.v

vSol(t) = C1 cos 4 t e3 t − C2 sin 4 t e3 t

Alternatively, store u(t) and v(t) directly by providing multiple output arguments.
[uSol(t),vSol(t)] = dsolve(odes)

3-47
3 Mathematics

uSol(t) = C2 cos 4 t e3 t + C1 sin 4 t e3 t

vSol(t) = C1 cos 4 t e3 t − C2 sin 4 t e3 t

The constants C1 and C2 appear because no conditions are specified. Solve the system with the initial
conditions u(0) == 0 and v(0) == 0. The dsolve function finds values for the constants that
satisfy these conditions.

cond1 = u(0) == 0;
cond2 = v(0) == 1;
conds = [cond1; cond2];
[uSol(t),vSol(t)] = dsolve(odes,conds)

uSol(t) = sin 4 t e3 t

vSol(t) = cos 4 t e3 t

Visualize the solution using fplot.

fplot(uSol)
hold on
fplot(vSol)
grid on
legend('uSol','vSol','Location','best')

3-48
Solve a System of Differential Equations

Solve Differential Equations in Matrix Form

Solve differential equations in matrix form by using dsolve.

Consider this system of differential equations.

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

The matrix form of the system is

x′ 1 2 x 1
= + .
y′ −1 1 y t

Let

x 1 2 1
Y= ,A= ,B = .
y −1 1 t

The system is now Y′ = A Y + B ..

Define these matrices and the matrix equation.


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

odes(t) =

x t =x t +2y t +1
∂t

y t =t−x t +y t
∂t

Solve the matrix equation using dsolve. Simplify the solution by using the simplify function.
[xSol(t),ySol(t)] = dsolve(odes);
xSol(t) = simplify(xSol(t))

xSol(t) =
2t 1
+ 2 C2 et cos 2 t + 2 C1 et sin 2 t +
3 9

ySol(t) = simplify(ySol(t))

ySol(t) =
t 2
C1 et cos 2 t − − C2 et sin 2 t −
3 9

The constants C1 and C2 appear because no conditions are specified.

Solve the system with the initial conditions u(0) = 2 and v(0) = − 1. When specifying equations in
matrix form, you must specify initial conditions in matrix form too. dsolve finds values for the
constants that satisfy these conditions.

3-49
3 Mathematics

C = Y(0) == [2;-1];
[xSol(t),ySol(t)] = dsolve(odes,C)

xSol(t) =
−t 4 σ + 2 σ + 6 t σ + 6 2 t σ e−t 4 σ2 − 2 σ1 + 6 t σ2 − 6 2 t σ1
17 2 e 1 2 1 2 7
2 et σ2 + − 2 et σ1 +
18 18 18 9

where

σ1 = sin 2 t

σ2 = cos 2 t

ySol(t) =
−t 4 σ + 2 σ + 6 t σ + 6 2 t σ e−t 4 σ2 − 2 σ1 + 6 t σ2 − 6 2 t σ1
17 2 e 1 2 1 2 7
− et σ1 + − et σ2 +
18 18 18 9

where

σ1 = sin 2 t

σ2 = cos 2 t

Visualize the solution using fplot.

clf
fplot(ySol)
hold on
fplot(xSol)
grid on
legend('ySol','xSol','Location','best')

3-50
Solve a System of Differential Equations

See Also
“Solve Differential Equation” on page 3-43

3-51
3 Mathematics

Solve a Second-Order Differential Equation Numerically

This example shows you how to convert a second-order differential equation into a system of
differential equations that can be solved using the numerical solver ode45 of MATLAB®.

A typical approach to solving higher-order ordinary differential equations is to convert them to


systems of first-order differential equations, and then solve those systems. The example uses
Symbolic Math Toolbox™ to convert a second-order ODE to a system of first-order ODEs. Then it uses
the MATLAB solver ode45 to solve the system.

Rewrite the Second-Order ODE as a System of First-Order ODEs

Use odeToVectorField to rewrite this second-order differential equation

2
d y dy
= (1 − y2) −y
dt 2 dt

dy
using a change of variables. Let y(t) = Y 1and = Y 2 such that differentiating both equations we
dt
obtain a system of first-order differential equations.

dY 1
= Y2
dt
dY 2
= − (Y 12 − 1)Y 2 − Y 1
dt

syms y(t)
[V] = odeToVectorField(diff(y, 2) == (1 - y^2)*diff(y) - y)

V =
Y2

− Y 12 − 1 Y 2 − Y 1

Generate MATLAB Function

The MATLAB ODE solvers do not accept symbolic expressions as an input. Therefore, before you can
use a MATLAB ODE solver to solve the system, you must convert that system to a MATLAB function.
Generate a MATLAB function from this system of first-order differential equations using
matlabFunction with V as an input.

M = matlabFunction(V,'vars', {'t','Y'})

M = function_handle with value:


@(t,Y)[Y(2);-(Y(1).^2-1.0).*Y(2)-Y(1)]

Solve the System of First-Order ODEs

To solve this system, call the MATLAB ode45 numerical solver using the generated MATLAB function
as an input.

sol = ode45(M,[0 20],[2 0]);

3-52
Solve a Second-Order Differential Equation Numerically

Plot the Solution

Plot the solution using linspace to generate 100 points in the interval [0,20] and deval to evaluate
the solution for each point.

fplot(@(x)deval(sol,x,1), [0, 20])

See Also
dsolve | matlabFunction | ode45 | odeToVectorField

3-53
3 Mathematics

Solve Partial Differential Equation of Tsunami Model

This example simulates a tsunami wave phenomenon by solving the partial differential equations that
model the tsunami.

This simulation is a simplified visualization of the phenomenon, and is based on a paper by Goring
and Raichlen [1].

Mathematics of the Tsunami Model

A solitary wave (a soliton solution of the Korteweg-de Vries equation) travels at a constant speed from
the right to the left along a canal of constant depth. This corresponds to a tsunami traveling over
deep sea. At the left end of the canal, there is a slope simulating the continental shelf. After reaching
the slope, the solitary wave begins to increase its height. When the water becomes very shallow, most
of the wave is reflected back into the canal. However, a narrow but high peak of water arises at the
end of the slope and proceeds with reduced speed in the original direction of the incident wave. This
is the tsunami that finally hits the shore, causing disastrous destruction along the coastline. The
speed of the wave nearing the shore is comparatively small. The wave eventually starts to break.

3-54
Solve Partial Differential Equation of Tsunami Model

Using linear dispersionless water theory, the height u(x, t) of a free surface wave above the
undisturbed water level in a one-dimensional canal of varying depth h(x) is the solution of the
following partial differential equation. (See [2].)

utt = g (h ux)x

In this formula, subscripts denote partial derivatives, and g = 9 . 81m/s2 is the gravitational
acceleration.

Consider a wave crossing a linear slope h(x) from a region with the constant depth h2 to a region with
the constant depth h1 ≪ h2. The Fourier transformation with respect to t turns the water wave partial
differential equation to the following ordinary differential equation for the Fourier mode
u(x, t) = U(x, ω) ei ω t.

−ω2 U = g (h Ux)x

For the regions with constant depth h, the Fourier modes are traveling waves propagating in opposite
directions with constant speed c = g h.

u(x, t) = C1(ω) ei ω (t + x/c) + C2(ω) ei ω(t − x/c)

i ω (t + x/c2) i ω (t − x/c2)
The solution u2(x, t) = e + R(ω) e for the deep water region is the superposition of
two waves:

3-55
3 Mathematics

• a wave traveling to the left with constant speed c2 = g h2


• a wave traveling to the right with an amplitude given by the frequency dependent reflection
coefficient R(ω)

This choice of u2 satisfies the wave equation in the deep water region for any R(ω).

i ω(t + x/c1)
The solution u1(x, t) = T(ω) e for the shallow water region is a transmitted wave traveling to
the left with the constant speed c1 = g h1. This choice of u1 satisfies the wave equation in the
shallow water region for any transmission coefficient T(ω).

For the transition region (the slope), use u(x, t) = U(x, w) ei ω t.

Parameters and Solutions of the Tsunami Model in Symbolic Math Toolbox

Define the parameters of the tsunami model as follows. Disregard the dependency on the frequency ω
in the following notations: R = R(ω), T = T(ω), U(x) = U(x, ω).

syms L H depthratio g positive


syms x t w T R U(x)

L1 = depthratio*L;
L2 = L;

h1 = depthratio*H;
h2 = H;
h(x) = x*H/L;

c1 = sqrt(g*h1);
c2 = sqrt(g*h2);

u(x,t) = U(x)*exp(1i*w*t);
u1(x,t) = T*exp(1i*w*(t + x/c1));
u2(x,t) = exp(1i*w*(t + x/c2)) + R*exp(1i*w*(t - x/c2));

In the transition region over the linear slope, use dsolve to solve the ODE for the Fourier transform
U of u.

wavePDE(x,t) = diff(u,t,t) - g*diff(h(x)*diff(u,x),x);


slopeODE(x) = wavePDE(x,0);
U(x) = dsolve(slopeODE);

The solution U is a complicated expression involving Bessel functions. It contains two arbitrary
"constants" that depend on ω.

Const = setdiff(symvar(U), sym([depthratio,g,H,L,x,w]))

Const = C1 C2

For any Fourier mode, the overall solution must be a continuously differentiable function of x. Hence,
the function values and the derivatives must match at the seam points L1 and L2. This provides four
linear equations for T , R, and the two constants in U.

du1(x) = diff(u1(x,0),x);
du2(x) = diff(u2(x,0),x);
dU(x) = diff(U(x),x);

3-56
Solve Partial Differential Equation of Tsunami Model

eqs = [ U(L1) == u1(L1,0), U(L2) == u2(L2,0),...


dU(L1) == du1(L1), dU(L2) == du2(L2)];
unknowns = [Const(1),Const(2),R,T];

Solve these equations.

[Cvalue1, Cvalue2, R, T] = solve(eqs, unknowns);

Substitute the results back into R, T , and U.

U(x) = subs(U(x), {Const(1),Const(2)}, {Cvalue1,Cvalue2});

You cannot directly evaluate the solution for ω = 0 because both numerator and denominator of the
corresponding expressions vanish. Instead, find the low frequency limits of these expressions.

simplify(limit(U(x), w, 0))

ans =
2
depthratio + 1

simplify(limit(R, w, 0))

ans =
depthratio − 1

depthratio + 1

simplify(limit(T, w, 0))

ans =
2
depthratio + 1

These limits are remarkably simple. They only depend on the ratio of the depth values defining the
slope.

Substitute Symbolic Parameters with Numeric Values

For the following computations, use these numerical values for the symbolic parameters.

• Gravitational acceleration: g = 9 . 81 m/sec2


• Depth of the canal: H = 1 m
• Depth ratio between the shallow and the deep regions: depthratio = 0 . 04
• Length of the slope region: L = 2 m

g = 9.81;
L = 2;
H = 1;
depthratio = 0.04;

h1 = depthratio*H;
h2 = H;

L1 = depthratio*L;
L2 = L;

3-57
3 Mathematics

c1 = sqrt(g*h1);
c2 = sqrt(g*h2);

Define the incoming soliton of amplitude A traveling to the left with constant speed c2 in the deep
water region.

A = 0.3;
soliton = @(x,t) A.*sech(sqrt(3/4*g*A/H)*(x/c2+t)).^2;

Choose Nt sample points for t. The time scale is chosen as a multiple of the (temporal) width of the
incoming soliton. Store the corresponding discretized frequencies of the Fourier transform in W .

Nt = 64;
TimeScale = 40*sqrt(4/3*H/A/g);
W = [0, 1:Nt/2 - 1, -(Nt/2 - 1):-1]'*2*pi/TimeScale;

Choose Nx sample points in x direction for each region. Create sample points X1 for the shallow
water region, X2 for the deep water region, and X12 for the slope region.

Nx = 100;
x_min = L1 - 4;
x_max = L2 + 12;
X12 = linspace(L1, L2, Nx);
X1 = linspace(x_min, L1, Nx);
X2 = linspace(L2, x_max, Nx);

Compute the Fourier transform of the incoming soliton on a time grid of Nt equidistant sample
points.

S = fft(soliton(-0.8*TimeScale*c2, linspace(0,TimeScale,2*(Nt/2)-1)))';
S = repmat(S,1,Nx);

Construct a traveling wave solution in the deep water region based on the Fourier data in S.

soliton = real(ifft(S .* exp(1i*W*X2/c2)));

Convert the Fourier modes of the reflected wave in the deep water region to numerical values over a
grid in (x, ω) space. Multiply these values with the Fourier coefficients in S and use the function ifft
to compute the reflected wave in (x, t) space. Note that the first row of the numeric data R consists of
NaN values because proper numerical evaluation of the symbolic data R for ω = 0 is not possible.
Define the values in the first row of R as the low frequency limits.

R = double(subs(subs(vpa(subs(R)), w, W), x ,X2));


R(1,:) = double((1-sqrt(depthratio)) / (1+sqrt(depthratio)));
reflectedWave = real(ifft(S .* R .* exp(-1i*W*X2/c2)));

Use the same approach for the transmitted wave in the shallow water region.

T = double(subs(subs(vpa(subs(T)),w,W),x,X1));
T(1,:) = double(2/(1+sqrt(depthratio)));
transmittedWave = real(ifft(S .* T .* exp(1i*W*X1/c1)));

Also, use this approach for the slope region.

U12 = double(subs(subs(vpa(subs(U(x))),w,W),x,X12));
U12(1,:) = double(2/(1+sqrt(depthratio)));
U12 = real(ifft(S .* U12));

3-58
Solve Partial Differential Equation of Tsunami Model

Plot the Solution

For a smoother animation, generate additional sample points using trigonometric interpolation along
the columns of the plot data.

soliton = interpft(soliton, 10*Nt);


reflectedWave = interpft(reflectedWave, 10*Nt);
U12 = interpft(U12, 10*Nt);
transmittedWave = interpft(transmittedWave, 10*Nt);

Create an animated plot of the solution that shows-up in a separate figure window.

figure('Visible', 'on');
plot([x_min, L1, L2, x_max], [-h1, -h1, -h2, -h2], 'Color', 'black')
axis([x_min, x_max, -H-0.1, 0.6])
hold on

line1 = plot(X1,transmittedWave(1,:), 'Color', 'blue');


line12 = plot(X12,U12(1,:), 'Color', 'blue');
line2 = plot(X2,soliton(1,:) + reflectedWave(1,:), 'Color', 'blue');

for t = 2 : size(soliton, 1)*0.35


line1.YData = transmittedWave(t,:);
line12.YData = U12(t,:);
line2.YData = soliton(t,:) + reflectedWave(t,:);
pause(0.1)
end

3-59
3 Mathematics

More About Tsunamis

In real life, tsunamis have a wavelength of hundreds of kilometers, often traveling at speeds of more
than 500 km/hour. (Note that the average depth of the ocean is about 4 km, corresponding to a speed
of g h ≈ 700 km/hour.) Over deep sea, the amplitude is rather small, often about 0.5 m or less.
When propagating onto the shelf, however, tsunamis increase their height dramatically: amplitudes of
up to 30 m and more were reported.

One interesting phenomenon is that although tsunamis typically approach the coastline as a wave
front extending for hundreds of kilometers perpendicular to the direction in which they travel, they
do not cause uniform damage along the coast. At some points they cause disasters, whereas only
moderate wave phenomena are observed at other places. This is caused by different slopes from the
sea bed to the continental shelf. In fact, very steep slopes cause most of the tsunami to be reflected
back into the region of deep water, whereas small slopes reflect less of the wave, transmitting a
narrow but high wave carrying much energy.

Run the simulation for different values of L, which correspond to different slopes. The steeper the
slope, the lower and less powerful the wave that is transmitted.

Note that this model ignores the dispersion and friction effects. On the shelf, the simulation loses its
physical meaning. Here, friction effects are important, causing breaking of the waves.

References

[1] Derek G. Goring and F. Raichlen, Tsunamis - The Propagation of Long Waves onto a Shelf, Journal
of Waterway, Port, Coastal and Ocean Engineering 118(1), 1992, pp. 41 - 63.

[2] H. Lamb, Hydrodynamics, Dover, 1932.

See Also
Functions
diff | dsolve | solve | subs

3-60
Solve Differential Algebraic Equations (DAEs)

Solve Differential Algebraic Equations (DAEs)

This example show how to solve differential algebraic equations (DAEs) by using MATLAB® and
Symbolic Math Toolbox™.

Differential algebraic equations involving functions, or state variables, x t = x1 t , . . . , xn t have


the form

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

where t is the independent variable. The number of equations F = F1, . . . , Fn must match the
number of state variables x t = x1 t , . . . , xn t .

Because most DAE systems are not suitable for direct input to MATLAB solvers, such as ode15i, first
convert them to a suitable form by using Symbolic Math Toolbox functionality. This functionality
reduces the differential index (number of differentiations needed to reduce the system to ODEs) of
the DAEs to 1 or 0, and then converts the DAE system to numeric function handles suitable for
MATLAB solvers. Then, use MATLAB solvers, such as ode15i, ode15s, or ode23t, to solve the DAEs.

Solve your DAE system by completing these steps.

Step 1: Specify Equations and Variables

The following figure shows the DAE workflow by solving the DAEs for a pendulum.

The state variables are:

3-61
3 Mathematics

• Horizontal position of pendulum x t


• Vertical position of pendulum y t
• Force preventing pendulum from flying away T t

The variables are:

• Pendulum mass m
• Pendulum length r
• Gravitational constant g

The DAE system of equations is:

2
d x xt
m =T t
dt 2 r
2
d y yt
m =T t − mg
dt 2 r
2 2
xt +y t = r2

Specify independent variables and state variables by using syms.

syms x(t) y(t) T(t) m r g

Specify equations by using the == operator.

eqn1 = m*diff(x(t), 2) == T(t)/r*x(t);


eqn2 = m*diff(y(t), 2) == T(t)/r*y(t) - m*g;
eqn3 = x(t)^2 + y(t)^2 == r^2;
eqns = [eqn1 eqn2 eqn3];

Place the state variables in a column vector. Store the number of original variables for reference.

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


origVars = length(vars);

Step 2: Reduce Differential Order

2.1 (Optional) Check Incidence of Variables

This step is optional. You can check where variables occur in the DAE system by viewing the
incidence matrix. This step finds any variables that do not occur in your input and can be removed
from the vars vector.

Display the incidence matrix by using incidenceMatrix. The output of incidenceMatrix has a
row for each equation and a column for each variable. Because the system has three equations and
three state variables, incidenceMatrix returns a 3-by-3 matrix. The matrix has 1s and 0s, where 1s
represent the occurrence of a state variable. For example, the 1 in position (2,3) means the second
equation contains the third state variable T(t).

M = incidenceMatrix(eqns,vars)

M = 3×3

1 0 1

3-62
Solve Differential Algebraic Equations (DAEs)

0 1 1
1 1 0

If a column of the incidence matrix is all 0s, then that state variable does not occur in the DAE system
and should be removed.

2.2 Reduce Differential Order

The differential order of a DAE system is the highest differential order of its equations. To solve DAEs
using MATLAB, the differential order must be reduced to 1. Here, the first and second equations have
second-order derivatives of x(t) and y(t). Thus, the differential order is 2.

Reduce the system to a first-order system by using reduceDifferentialOrder. The


reduceDifferentialOrder function substitutes derivatives with new variables, such as Dxt(t)
and Dyt(t). The right side of the expressions in eqns is 0.
[eqns,vars] = reduceDifferentialOrder(eqns,vars)

eqns =
∂ T t xt
mDxt t −
∂t r
∂ T t yt
gm+m Dyt t −
∂t r
2 2
−r 2 + x t+y t

Dxt t − xt
∂t

Dyt t − yt
∂t

vars =
xt
yt
T t
Dxt t
Dyt t

Step 3: Check and Reduce Differential Index

3.1 Check Differential Index of System

Check the differential index of the DAE system by using isLowIndexDAE. If the index is 0 or 1, then
isLowIndexDAE returns logical 1 (true) and you can skip step 3.2 and go to Step 4. Convert DAE
Systems to MATLAB Function Handles. Here, isLowIndexDAE returns logical 0 (false), which
means the differential index is greater than 1 and must be reduced.
isLowIndexDAE(eqns,vars)

ans = logical
0

3.2 Reduce Differential Index with reduceDAEIndex

To reduce the differential index, the reduceDAEIndex function adds new equations that are derived
from the input equations, and then replaces higher-order derivatives with new variables. If

3-63
3 Mathematics

reduceDAEIndex fails and issues a warning, then use the alternative function reduceDAEToODE as
described in the workflow “Solve Semilinear DAE System” on page 3-70.

Reduce the differential index of the DAEs described by eqns and vars.

[DAEs,DAEvars] = reduceDAEIndex(eqns,vars)

DAEs =
T t xt
m Dxtt t −
r
T t yt
g m + m Dytt t −
r
2 2
−r 2 + x t + y t
Dxt t − Dxt1 t
Dyt t − Dyt1 t
2 Dxt1 t x t + 2 Dyt1 t y t
∂ 2 2
2y t Dyt1 t + 2 Dxt1 t + 2 Dyt1 t + 2 Dxt1t t x t
∂t
Dxtt t − Dxt1t t

Dytt t − Dyt1 t
∂t

Dyt1 t − yt
∂t

DAEvars =
xt
yt
T t
Dxt t
Dyt t
Dytt t
Dxtt t
Dxt1 t
Dyt1 t
Dxt1t t

If reduceDAEIndex issues an error or a warning, use the alternative workflow described in “Solve
Semilinear DAE System” on page 3-70.

Often, reduceDAEIndex introduces redundant equations and variables that can be eliminated.
Eliminate redundant equations and variables using reduceRedundancies.

[DAEs,DAEvars] = reduceRedundancies(DAEs,DAEvars)

DAEs =

3-64
Solve Differential Algebraic Equations (DAEs)

T t x t − m r Dxtt t

r
g m r − T t y t + m r Dytt t
r
2 2
−r 2 + x t + y t
2 Dxt t x t + 2 Dyt t y t
2 2
2 Dxt t + 2 Dyt t + 2 Dxtt t x t + 2 Dytt t y t

Dytt t − Dyt t
∂t

Dyt t − yt
∂t

DAEvars =
xt
yt
T t
Dxt t
Dyt t
Dytt t
Dxtt t

Check the differential index of the new system. Now, isLowIndexDAE returns logical 1 (true), which
means that the differential index of the system is 0 or 1.
isLowIndexDAE(DAEs,DAEvars)

ans = logical
1

Step 4: Convert DAE Systems to MATLAB Function Handles

This step creates function handles for the MATLAB ODE solver ode15i, which is a general purpose
solver. To use specialized mass matrix solvers such as ode15s and ode23t, see “Solve DAEs Using
Mass Matrix Solvers” on page 3-77 and “Choose an ODE Solver”.

reduceDAEIndex outputs a vector of equations in DAEs and a vector of variables in DAEvars. To use
ode15i, you need a function handle that describes the DAE system.

First, the equations in DAEs can contain symbolic parameters that are not specified in the vector of
variables DAEvars. Find these parameters by using setdiff on the output of symvar from DAEs
and DAEvars.
pDAEs = symvar(DAEs);
pDAEvars = symvar(DAEvars);
extraParams = setdiff(pDAEs,pDAEvars)

extraParams = g m r

The extra parameters that you need to specify are the mass m, radius r, and gravitational constant g.

Create the function handle by using daeFunction. Specify the extra symbolic parameters as
additional input arguments of daeFunction.
f = daeFunction(DAEs,DAEvars,g,m,r);

3-65
3 Mathematics

The rest of the workflow is purely numerical. Set the parameter values and create the function handle
for ode15i.

g = 9.81;
m = 1;
r = 1;
F = @(t,Y,YP) f(t,Y,YP,g,m,r);

Step 5: Find Initial Conditions for Solvers

The ode15i solver requires initial values for all variables in the function handle. Find initial values
that satisfy the equations by using the MATLAB decic function. decic accepts guesses (which might
not satisfy the equations) for the initial conditions and tries to find satisfactory initial conditions using
those guesses. decic can fail, in which case you must manually supply consistent initial values for
your problem.

First, check the variables in DAEvars.

DAEvars

DAEvars =
xt
yt
T t
Dxt t
Dyt t
Dytt t
Dxtt t

Here, Dxt(t) is the first derivative of x(t), Dytt(t) is the second derivative of y(t), and so on.
There are 7 variables in a 7-by-1 vector. Therefore, guesses for initial values of variables and their
derivatives must also be 7-by-1 vectors.

Assume the initial angular displacement of the pendulum is 30° or pi/6, and the origin of the
coordinates is at the suspension point of the pendulum. Given that we used a radius r of 1, the initial
horizontal position x(t) is r*sin(pi/6). The initial vertical position y(t) is -r*cos(pi/6).
Specify these initial values of the variables in the vector y0est.

Arbitrarily set the initial values of the remaining variables and their derivatives to 0. These are not
good guesses. However, they suffice for this problem. In your problem, if decic errors, then provide
better guesses and refer to decic.

y0est = [r*sin(pi/6); -r*cos(pi/6); 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 decic.

[y0,yp0] = decic(F,0,y0est,[],yp0est,[],opt)

y0 = 7×1

3-66
Solve Differential Algebraic Equations (DAEs)

0.4771
-0.8788
-8.6214
0
0.0000
-2.2333
-4.1135

yp0 = 7×1

0
0.0000
0
0
-2.2333
0
0

Step 6: Solve DAEs Using ode15i

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

[tSol,ySol] = ode15i(F,[0 0.5],y0,yp0,opt);


plot(tSol,ySol(:,1:origVars),'LineWidth',2)

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

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

3-67
3 Mathematics

Solve the system for different parameter values by setting the new value and regenerating the
function handle and initial conditions.

Set r to 2 and regenerate the function handle and initial conditions.

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

y0est = [r*sin(pi/6); -r*cos(pi/6); 0; 0; 0; 0; 0];


[y0,yp0] = decic(F,0,y0est,[],yp0est,[],opt);

Solve the system for the new parameter value.

[tSol,y] = ode15i(F,[0 0.5],y0,yp0,opt);


plot(tSol,y(:,1:origVars),'LineWidth',2)

for k = 1:origVars
S{k} = char(DAEvars(k));
end
legend(S,'Location','Best')
grid on

3-68
Solve Differential Algebraic Equations (DAEs)

See Also

Related Examples
• “Solve Semilinear DAE System” on page 3-70
• “Solve DAEs Using Mass Matrix Solvers” on page 3-77

3-69
3 Mathematics

Solve Semilinear DAE System

This workflow is an alternative workflow to solving semilinear differential algebraic equations (DAEs),
used only if reduceDAEIndex failed in the standard workflow with the warning message: The
index of the reduced DAEs is larger than 1. [daetools::reduceDAEIndex]. For the
standard workflow, see “Solve Differential Algebraic Equations (DAEs)” on page 3-61.

Complete steps 1 and 2 in “Solve Differential Algebraic Equations (DAEs)” on page 3-61 before
beginning other steps. Then, in step 3, if reduceDAEIndex fails, reduce the differential index using
reduceDAEToODE. The advantage of reduceDAEToODE is that it reliably reduces semilinear DAEs to
ODEs (DAEs of index 0). However, this function is slower and works only on semilinear DAE systems.
reduceDAEToODE can fail if the system is not semilinear.

To solve your DAE system, complete these steps.

Step 1. Specify Equations and Variables

The DAE system of equations is:

2
d x xt
m =T t
dt 2 r
2
d y yt
m =T t − mg
dt2 r
2 2
xt +y t = r2

Specify independent variables and state variables by using syms.

syms x(t) y(t) T(t) m r g

Specify equations by using the == operator.

eqn1 = m*diff(x(t), 2) == T(t)/r*x(t);


eqn2 = m*diff(y(t), 2) == T(t)/r*y(t) - m*g;
eqn3 = x(t)^2 + y(t)^2 == r^2;
eqns = [eqn1 eqn2 eqn3];

Place the state variables in a column vector. Store the number of original variables for reference.

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


origVars = length(vars);

Step 2. Reduce Differential Order

The differential order of a DAE system is the highest differential order of its equations. To solve DAEs
using MATLAB®, the differential order must be reduced to 1. Here, the first and second equations
have second-order derivatives of x(t) and y(t). Thus, the differential order is 2.

Reduce the system to a first-order system by using reduceDifferentialOrder. The


reduceDifferentialOrder function substitutes derivatives with new variables, such as Dxt(t)
and Dyt(t). The right side of the expressions in eqns is 0.

[eqns,vars] = reduceDifferentialOrder(eqns,vars)

3-70
Solve Semilinear DAE System

eqns =
∂ T t xt
m Dxt t −
∂t r
∂ T t yt
gm+m Dyt t −
∂t r
2 2
−r 2 + x t+y t

Dxt t − xt
∂t

Dyt t − yt
∂t

vars =
xt
yt
T t
Dxt t
Dyt t

Step 3. Reduce Differential Index with reduceDAEToODE

To reduce the differential index of the DAEs described by eqns and vars, use reduceDAEToODE. To
reduce the index, reduceDAEToODE adds new variables and equations to the system.
reduceDAEToODE also returns constraints, which are conditions that help find initial values to ensure
that the resulting ODEs are equal to the initial DAEs.

[ODEs,constraints] = reduceDAEToODE(eqns,vars)

ODEs =

xt Dxt t −
∂t

Dyt t − yt
∂t
∂ T t xt
m Dxt t −
∂t r
∂ T t y t −gmr
m Dyt t −
∂t r
∂ 2 2 ∂ ∂ ∂ ∂
− 4T t y t −2gmr y t − 2x t +2y t T t −4T t x t x t − 4 m r Dxt t Dxt t − 4 m r Dyt t Dyt
∂t ∂t ∂t ∂t ∂t

constraints =
2 2 2 2
−2 m r Dxt t − 2 m r Dyt t −2T t x t −2T t y t +2gmr y t
2 2
r2 − x t − y t
2 Dxt t x t + 2 Dyt t y t

3-71
3 Mathematics

Step 4. ODEs to Function Handles for ode15s and ode23t

From the output of reduceDAEToODE, you have a vector of equations in ODEs and a vector of
variables in vars. To use ode15s or ode23t, you need two function handles: one representing the
mass matrix of the ODE system, and the other representing the vector containing the right sides of
the mass matrix equations. These function handles are the equivalent mass matrix representation of
the ODE system where M(t,y(t))y’(t) = f(t,y(t)).

Find these function handles by using massMatrixForm to get the mass matrix massM (M in the
equation) and right sides f.

[massM,f] = massMatrixForm(ODEs,vars)

massM =
−1 0 0 0 0
0 −1 0 0 0
0 0 0 m 0
0 0 0 0 m
2 2
−4 T t x t 2 g m r − 4 T t y t −2 x t −2y t −4 m r Dxt t −4 m r Dyt t

f =
−Dxt t
−Dyt t
T t xt
r
T t y t −gmr
r
0

The equations in ODEs can contain symbolic parameters that are not specified in the vector of
variables vars. Find these parameters by using setdiff on the output of symvar from ODEs and
vars.

pODEs = symvar(ODEs);
pvars = symvar(vars);
extraParams = setdiff(pODEs, pvars)

extraParams = g m r

The extra parameters that you need to specify are the mass m, radius r, and gravitational constant g.

Convert massM and f to function handles using odeFunction. Specify the extra symbolic parameters
as additional inputs to odeFunction.

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


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

The rest of the workflow is purely numerical. Set the parameter values and substitute the parameter
values in DAEs and constraints.

m = 1;
r = 1;
g = 9.81;
ODEsNumeric = subs(ODEs);
constraintsNumeric = subs(constraints);

3-72
Solve Semilinear DAE System

Create the function handle suitable for input to ode15s or ode23s.

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

Step 5. Initial Conditions for ode15s and ode23t

The solvers require initial values for all variables in the function handle. Find initial values that
satisfy the equations by using the MATLAB decic function. The decic accepts guesses (which might
not satisfy the equations) for the initial conditions and tries to find satisfactory initial conditions using
those guesses. decic can fail, in which case you must manually supply consistent initial values for
your problem.

First, check the variables in vars.

vars

vars =
xt
yt
T t
Dxt t
Dyt t

Here, Dxt(t) is the first derivative of x(t), and so on. There are 5 variables in a 5-by-1 vector.
Therefore, guesses for initial values of variables and their derivatives must also be 5-by-1 vectors.

Assume the initial angular displacement of the pendulum is 30° or pi/6, and the origin of the
coordinates is at the suspension point of the pendulum. Given that we used a radius r of 1, the initial
horizontal position x(t) is r*sin(pi/6). The initial vertical position y(t) is -r*cos(pi/6).
Specify these initial values of the variables in the vector y0est.

Arbitrarily set the initial values of the remaining variables and their derivatives to 0. These are not
good guesses. However, they suffice for this problem. In your problem, if decic errors, then provide
better guesses and refer to the decic page.

y0est = [r*sin(pi/6); -r*cos(pi/6); 0; 0; 0];


yp0est = zeros(5,1);

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
decic. The parameter [1,0,0,0,1] in this function call fixes the first and the last element in
y0est, so that decic does not change them during the numerical search. Here, this fixing is
necessary to ensure decic finds satisfactory initial conditions.

[y0, yp0] = decic(ODEsNumeric, vars, constraintsNumeric, 0,...


y0est, [1,0,0,0,1], yp0est, opt)

y0 = 5×1

0.5000
-0.8660

3-73
3 Mathematics

-8.4957
0
0

yp0 = 5×1

0
0
0
-4.2479
-2.4525

Now create an option set that contains the mass matrix M of the system and the vector yp0 of
consistent initial values for the derivatives. You will use this option set when solving the system.

opt = odeset(opt, 'InitialSlope', yp0);

Step 6. Solve an ODE System with ode15s or ode23t

Solve the system integrating over the time span 0 ≤ t ≤ 0.5. Add the grid lines and the legend to the
plot. Use ode23s by replacing ode15s with ode23s.

[tSol,ySol] = ode15s(F, [0, 0.5], y0, opt);


plot(tSol,ySol(:,1:origVars),'-o')

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

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


grid on

3-74
Solve Semilinear DAE System

Solve the system for different parameter values by setting the new value and regenerating the
function handle and initial conditions.

Set r to 2 and repeat the steps.


r = 2;

ODEsNumeric = subs(ODEs);
constraintsNumeric = subs(constraints);
M = @(t,Y) massM(t,Y,m,r,g);
F = @(t,Y) f(t,Y,m,r,g);

y0est = [r*sin(pi/6); -r*cos(pi/6); 0; 0; 0];


opt = odeset('Mass', M, 'RelTol', 10.0^(-7), 'AbsTol' , 10.0^(-7));
[y0, yp0] = decic(ODEsNumeric, vars, constraintsNumeric, 0,...
y0est, [1,0,0,0,1], yp0est, opt);

opt = odeset(opt, 'InitialSlope', yp0);

Solve the system for the new parameter value.


[tSol,ySol] = ode15s(F, [0, 0.5], y0, opt);
plot(tSol,ySol(:,1:origVars),'-o')

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

3-75
3 Mathematics

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


grid on

See Also
daeFunction | decic | findDecoupledBlocks | incidenceMatrix | isLowIndexDAE |
massMatrixForm | odeFunction | reduceDAEIndex | reduceDAEToODE |
reduceDifferentialOrder | reduceRedundancies

Related Examples
• “Solve Differential Algebraic Equations (DAEs)” on page 3-61
• “Solve DAEs Using Mass Matrix Solvers” on page 3-77

3-76
Solve DAEs Using Mass Matrix Solvers

Solve DAEs Using Mass Matrix Solvers


Solve differential algebraic equations by using one of the mass matrix solvers available in MATLAB.
To use this workflow, first complete steps 1, 2, and 3 from “Solve Differential Algebraic Equations
(DAEs)” on page 3-61. Then, use a mass matrix solver instead of ode15i.

This example demonstrates the use of ode15s or ode23t. For details on the other solvers, see
“Choose an ODE Solver” and adapt the workflow on this page.

In this section...
“Step 1. Convert DAEs to Function Handles” on page 3-77
“Step 2. Find Initial Conditions” on page 3-78
“Step 3. Solve DAE System” on page 3-79

Step 1. Convert DAEs to Function Handles


From the output of reduceDAEIndex, you have a vector of equations DAEs and a vector of variables
DAEvars. To use ode15s or ode23t, you need two function handles: one representing the mass
matrix of a DAE system, and the other representing the right sides of the mass matrix equations.
These function handles form the equivalent mass matrix representation of the ODE system where
M(t,y(t))y’(t) = f(t,y(t)).

Find these function handles by using massMatrixForm to get the mass matrix M and the right sides
F.

[M,f] = massMatrixForm(DAEs,DAEvars)

M =
[ 0, 0, 0, 0, 0, 0, 0]
[ 0, 0, 0, 0, 0, 0, 0]
[ 0, 0, 0, 0, 0, 0, 0]
[ 0, 0, 0, 0, 0, 0, 0]
[ 0, 0, 0, 0, 0, 0, 0]
[ 0, 0, 0, 0, -1, 0, 0]
[ 0, -1, 0, 0, 0, 0, 0]

f =
(T(t)*x(t) - m*r*Dxtt(t))/r
-(g*m*r - T(t)*y(t) + m*r*Dytt(t))/r
r^2 - y(t)^2 - x(t)^2
- 2*Dxt(t)*x(t) - 2*Dyt(t)*y(t)
- 2*Dxtt(t)*x(t) - 2*Dytt(t)*y(t) - 2*Dxt(t)^2 - 2*Dyt(t)^2
-Dytt(t)
-Dyt(t)

The equations in DAEs can contain symbolic parameters that are not specified in the vector of
variables DAEvars. Find these parameters by using setdiff on the output of symvar from DAEs
and DAEvars.

pDAEs = symvar(DAEs);
pDAEvars = symvar(DAEvars);
extraParams = setdiff(pDAEs, pDAEvars)

3-77
3 Mathematics

extraParams =
[ g, m, r]

The mass matrix M does not have these extra parameters. Therefore, convert M directly to a function
handle by using odeFunction.

M = odeFunction(M, DAEvars);

Convert f to a function handle. Specify the extra parameters as additional inputs to odeFunction.

f = odeFunction(f, DAEvars, g, m, r);

The rest of the workflow is purely numerical. Set parameter values and create the function handle.

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

Step 2. Find Initial Conditions


The solvers require initial values for all variables in the function handle. Find initial values that
satisfy the equations by using the MATLAB decic function. The decic accepts guesses (which might
not satisfy the equations) for the initial conditions, and tries to find satisfactory initial conditions
using those guesses. decic can fail, in which case you must manually supply consistent initial values
for your problem.

First, check the variables in DAEvars.

DAEvars

DAEvars =
x(t)
y(t)
T(t)
Dxt(t)
Dyt(t)
Dytt(t)
Dxtt(t)

Here, Dxt(t) is the first derivative of x(t), Dytt(t) is the second derivative of y(t), and so on.
There are 7 variables in a 7-by-1 vector. Thus, guesses for initial values of variables and their
derivatives must also be 7-by-1 vectors.

Assume the initial angular displacement of the pendulum is 30° or pi/6, and the origin of the
coordinates is at the suspension point of the pendulum. Given that we used a radius r of 1, the initial
horizontal position x(t) is r*sin(pi/6). The initial vertical position y(t) is -r*cos(pi/6).
Specify these initial values of the variables in the vector y0est.

Arbitrarily set the initial values of the remaining variables and their derivatives to 0. These are not
good guesses. However, they suffice for our problem. In your problem, if decic errors, then provide
better guesses and refer to the decic page.

y0est = [r*sin(pi/6); -r*cos(pi/6); 0; 0; 0; 0; 0];


yp0est = zeros(7,1);

3-78
Solve DAEs Using Mass Matrix Solvers

Create an option set that contains the mass matrix M and initial guesses yp0est, and specifies
numerical tolerances for the numerical search.

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 describing the DAE as f(t,y,yp)
= f(t,y,y') = 0. In terms of M and F, this means f(t,y,yp) = M(t,y)*yp - F(t,y).

implicitDAE = @(t,y,yp) M(t,y)*yp - F(t,y);


[y0, yp0] = decic(implicitDAE, 0, y0est, [], yp0est, [], opt)

y0 =
0.4771
-0.8788
-8.6214
0
0.0000
-2.2333
-4.1135

yp0 =
0
0.0000
0
0
-2.2333
0
0

Now create an option set that contains the mass matrix M of the system and the vector yp0 of
consistent initial values for the derivatives. You will use this option set when solving the system.

opt = odeset(opt, 'InitialSlope', yp0);

Step 3. Solve DAE System


Solve the system integrating over the time span 0 ≤ t ≤ 0.5. Add the grid lines and the legend to the
plot. The code uses ode15s. Instead, you can use ode23s by replacing ode15s with ode23s.

[tSol,ySol] = ode15s(F, [0, 0.5], y0, opt);


plot(tSol,ySol(:,1:origVars),'-o')

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

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


grid on

3-79
3 Mathematics

Solve the system for different parameter values by setting the new value and regenerating the
function handle and initial conditions.

Set r to 2 and regenerate the function handle and initial conditions.

r = 2;

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


y0est = [r*sin(pi/6); -r*cos(pi/6); 0; 0; 0; 0; 0];
implicitDAE = @(t,y,yp) M(t,y)*yp - F(t,y);
[y0, yp0] = decic(implicitDAE, 0, y0est, [], yp0est, [], opt);

opt = odeset(opt, 'InitialSlope', yp0);

Solve the system for the new parameter value.

[tSol,ySol] = ode15s(F, [0, 0.5], y0, opt);


plot(tSol,ySol(:,1:origVars),'-o')

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

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


grid on

3-80
Solve DAEs Using Mass Matrix Solvers

See Also

Related Examples
• “Solve Differential Algebraic Equations (DAEs)” on page 3-61
• “Solve Semilinear DAE System” on page 3-70

3-81
3 Mathematics

Analyze and Manipulate Differential Algebraic Equations

This example shows how to solve differential algebraic equations (DAEs) of high differential index
using Symbolic Math Toolbox™.

Engineers often specify the behavior of their physical objects (mechanical systems, electrical devices,
and so on) by a mixture of differential equations and algebraic equations. MATLAB® provides special
numerical solvers, such as ode15i and ode15s, capable of integrating such DAEs -- provided that
their 'differential index' does not exceed 1.

This example shows the workflow from setting up the model as a system of differential equations with
algebraic constraints to the numerical simulation. The following Symbolic Math Toolbox functions are
used.

• daeFunction
• findDecoupledBlocks
• incidenceMatrix
• isOfLowDAEIndex
• reduceDifferentialOrder
• massMatrixForm
• reduceDAEIndex
• reduceDAEToODE
• reduceRedundancies
• sym/decic

Define Parameters of the Model

Consider a 2-D physical pendulum, consisting of a mass m attached to the origin by a string of
constant length r. Only the gravitational acceleration g = 9.81 m/s^2 acts on the mass. The model
consists of second-order differential equation for the position (x(t), y(t)) of the mass with an
unknown force F(t) inside the string which serves for keeping the mass on the circle. The force is
directed along the string.
syms x(t) y(t) F(t) m g r
eqs = [m*diff(x(t), t, t) == F(t)/r*x(t);
m*diff(y(t), t, t) == F(t)/r*y(t) - m*g;
x(t)^2 + y(t)^2 == r^2]

eqs =
∂2 Ft xt
m xt =
∂t 2 r
2
∂ Ft yt
m yt = −gm
∂t2 r
2 2
xt +y t = r2

vars = [x(t), y(t), F(t)]

vars = x t y t F t

Rewrite this DAE system to a system of first-order differential algebraic equations.

3-82
Analyze and Manipulate Differential Algebraic Equations

[eqs, vars, newVars] = reduceDifferentialOrder(eqs, vars)

eqs =
∂ Ft xt
m Dxt t −
∂t r
∂ Ft yt
gm+m Dyt t −
∂t r
2 2
−r 2 + x t+y t

Dxt t − xt
∂t

Dyt t − yt
∂t

vars =
xt
yt
Ft
Dxt t
Dyt t

newVars =

Dxt t xt
∂t

Dyt t yt
∂t

Try Solving the High-Index DAE System

Before you can use a numerical MATLAB solver, such as ode15i, you must follow these steps.

1 Convert the system of DAEs to a MATLAB function handle.


2 Choose numerical values for symbolic parameters of the system.
3 Set consistent initial conditions.

To convert a DAE system to a MATLAB function handle, use daeFunction.

F = daeFunction(eqs, vars, [m, g, r])

F = function_handle with value:


@(t,in2,in3,in4)[in3(4,:).*in4(:,1)-(in2(3,:).*in2(1,:))./in4(:,3);in3(5,:).*in4(:,1)+in4(:,1

Assign numerical values to the symbolic parameters of the system: m = 1kg, g = 9.18m/s^2, and r
= 1m.

f = @(t, y, yp) F(t, y, yp, [1, 9.81, 1])

f = function_handle with value:


@(t,y,yp)F(t,y,yp,[1,9.81,1])

The function handle f is a suitable input for the numerical solver ode15i. The next step is to
compute consistent initial conditions. Use odeset to set numerical tolerances. Then use the MATLAB
decic function to compute consistent initial conditions y0, yp0 for the positions and the derivatives
at time t0 = 0.

3-83
3 Mathematics

opt = odeset('RelTol', 10.0^(-4), 'AbsTol' , 10.0^(-4));


t0 = 0;
[y0,yp0] = decic(f, t0, [0.98;-0.21; zeros(3,1)], [], zeros(5,1), [], opt)

y0 = 5×1

0.9777
-0.2100
0
0
0

yp0 = 5×1

0
0
0
0
-9.8100

Test the initial conditions:

f(t0, y0, yp0)

ans = 5×1
10-16 ×

0
0
-0.3469
0
0

Now you can use ode15i to try solving the system. When you call ode15i, the integration stops
immediately and issues the following warnings.

Warning: Matrix is singular, close to singular or badly scaled.

Results may be inaccurate. RCOND = NaN.

Warning: Failure at t=0.000000e+00.

Unable to meet integration tolerances without reducing the step

size below the smallest value allowed (0.000000e+00) at time t.

For this example, ode15i issues these warnings multiple times. For readability, disable warnings by
using warning('off','all') before calling ode15i and then enable them again.

tfinal = 0.5;
s = warning('off','all');
ode15i(f, [t0, tfinal], y0, yp0, opt);

3-84
Analyze and Manipulate Differential Algebraic Equations

warning(s)

Analyze and Adjust the DAE System

Check the differential index of the DAE system.

isLowIndexDAE(eqs, vars)

ans = logical
0

This result explains why ode15i cannot solve this system. This function requires the input DAE
system to be of differential index 0 or 1. Reduce the differential index by extending the model to an
equivalent larger DAE system that includes some hidden algebraic constraints.

[eqs, vars, newVars, index] = reduceDAEIndex(eqs, vars)

eqs =

3-85
3 Mathematics

Ft xt
m Dxtt t −
r
Ft yt
g m + m Dytt t −
r
2 2
−r 2 + x t + y t
Dxt t − Dxt1 t
Dyt t − Dyt1 t
2 Dxt1 t x t + 2 Dyt1 t y t
∂ 2 2
2y t Dyt1 t + 2 Dxt1 t + 2 Dyt1 t + 2 Dxt1t t x t
∂t
Dxtt t − Dxt1t t

Dytt t − Dyt1 t
∂t

Dyt1 t − yt
∂t

vars =
xt
yt
Ft
Dxt t
Dyt t
Dytt t
Dxtt t
Dxt1 t
Dyt1 t
Dxt1t t

newVars =

Dytt t Dyt t
∂t

Dxtt t Dxt t
∂t

Dxt1 t xt
∂t

Dyt1 t yt
∂t
∂2
Dxt1t t xt
∂t2

index = 3

The fourth output shows that the differential index of the original model is three. Simplify the new
system.

[eqs, vars, S] = reduceRedundancies(eqs, vars)

eqs =

3-86
Analyze and Manipulate Differential Algebraic Equations

F t x t − m r Dxtt t

r
g m r − F t y t + m r Dytt t
r
2 2
−r 2 + x t + y t
2 Dxt t x t + 2 Dyt t y t
2 2
2 Dxt t + 2 Dyt t + 2 Dxtt t x t + 2 Dytt t y t

Dytt t − Dyt t
∂t

Dyt t − yt
∂t

vars =
xt
yt
Ft
Dxt t
Dyt t
Dytt t
Dxtt t

S = struct with fields:


solvedEquations: [3x1 sym]
constantVariables: [0x2 sym]
replacedVariables: [3x2 sym]
otherEquations: [0x1 sym]

Check if the new system has a low differential index (0 or 1).


isLowIndexDAE(eqs, vars)

ans = logical
1

Solve the Low-Index DAE System

Generate a MATLAB function handle that replaces the symbolic parameters by numerical values.
F = daeFunction(eqs, vars, [m, g, r])

F = function_handle with value:


@(t,in2,in3,in4)[-(in2(3,:).*in2(1,:)-in2(7,:).*in4(:,1).*in4(:,3))./in4(:,3);(-in2(3,:).*in2

f = @(t, y, yp) F(t, y, yp, [1, 9.81, 1])

f = function_handle with value:


@(t,y,yp)F(t,y,yp,[1,9.81,1])

Compute consistent initial conditions for the index reduced by the MATLAB decic function. Here,
opt is the options structure that sets numerical tolerances. You already computed it using odeset.
[y0,yp0] = decic(f, t0, [0.98;-0.21; zeros(5,1)], [], zeros(7,1), [], opt)

3-87
3 Mathematics

y0 = 7×1

0.9779
-0.2093
-2.0528
-0.0000
0
-9.3804
-2.0074

yp0 = 7×1

0
0
0
0
-9.3804
0
0

Solve the system and plot the solution.

ode15i(f, [t0, tfinal], y0, yp0, opt)

3-88
Derive and Apply Inverse Kinematics to Two-Link Robot Arm

Derive and Apply Inverse Kinematics to Two-Link Robot Arm

This example shows how to derive and apply inverse kinematics to a two-link robot arm by using
MATLAB® and Symbolic Math Toolbox™.

The example defines the joint parameters and end-effector locations symbolically, calculates and
visualizes the forward and inverse kinematics solutions, and finds the system Jacobian, which is
useful for simulating the motion of the robot arm.

Step 1: Define Geometric Parameters

Define the link lengths, joint angles and end-effector locations of the robots as symbolic variables.
syms L_1 L_2 theta_1 theta_2 XE YE

Specify values for the link lengths of the robot.


L1 = 1;
L2 = 0.5;

Step 2: Define X and Y Coordinates of End Effector

3-89
3 Mathematics

Define the X and Y coordinates of the end-effector as a function of the joint angles θ1 , θ2 .

XE_RHS = L_1*cos(theta_1) + L_2*cos(theta_1+theta_2)

XE_RHS = L2 cos θ1 + θ2 + L1 cos θ1

YE_RHS = L_1*sin(theta_1) + L_2*sin(theta_1+theta_2)

YE_RHS = L2 sin θ1 + θ2 + L1 sin θ1

Convert the symbolic expressions into MATLAB functions.

XE_MLF = matlabFunction(XE_RHS,'Vars',[L_1 L_2 theta_1 theta_2]);


YE_MLF = matlabFunction(YE_RHS,'Vars',[L_1 L_2 theta_1 theta_2]);

Step 3: Calculate and Visualize Forward Kinematics

Forward kinematics transforms the joint angles into end-effector locations:


(θ1, θ2) f (θ1, θ2) (XE, Y E). Given specific joint-angle values, use forward kinematics to calculate
the end-effector locations.

∘ ∘ ∘ ∘
Specify the input values of the joint angles as 0 < θ1 < 90 and −180 < θ2 < 180 .

t1_degs_row = linspace(0,90,100);
t2_degs_row = linspace(-180,180,100);
[tt1_degs,tt2_degs] = meshgrid(t1_degs_row,t2_degs_row);

Convert the angle units from degrees to radians.

tt1_rads = deg2rad(tt1_degs);
tt2_rads = deg2rad(tt2_degs);

Calculate the X and Y coordinates using the MATLAB functions XE_MLF and YE_MLF, respectively.

X_mat = XE_MLF(L1,L2,tt1_rads,tt2_rads);
Y_mat = YE_MLF(L1,L2,tt1_rads,tt2_rads);

Visualize the X and Y coordinates using the helper function plot_XY_given_theta_2dof.

plot_XY_given_theta_2dof(tt1_degs,tt2_degs,X_mat,Y_mat,(L1+L2))

3-90
Derive and Apply Inverse Kinematics to Two-Link Robot Arm

Step 4: Find Inverse Kinematics

Inverse kinematics transforms the end-effector locations into joint angles:


(XE, Y E) g(XE, Y E) (θ1, θ2). Find the inverse kinematics from the forward kinematics equations.

Define the forward kinematics equations.

XE_EQ = XE == XE_RHS;
YE_EQ = YE == YE_RHS;

Solve for θ1 and θ2.

S = solve([XE_EQ YE_EQ], [theta_1 theta_2])

S = struct with fields:


theta_1: [2x1 sym]
theta_2: [2x1 sym]

The structure S represents the multiple solutions for θ1 and θ2. Show the pair of solutions for θ1.

simplify(S.theta_1)

ans =

3-91
3 Mathematics

2 L1 YE + σ1
2 atan
L1 + 2 L1 XE − L22 + XE2 + YE2
2

2 L1 YE − σ1
2 atan
L1 + 2 L1 XE − L22 + XE2 + YE2
2

where

σ1 = −L14 + 2 L12 L22 + 2 L12 XE2 + 2 L12 YE2 − L24 + 2 L22 XE2 + 2 L22 YE2 − XE4 − 2 XE2 YE2 − YE4

Show the pair of solutions for θ2.

simplify(S.theta_2)

ans =
−σ1
σ1

where

−L12 + 2 L1 L2 − L22 + XE2 + YE2 L12 + 2 L1 L2 + L22 − XE2 − YE2


σ1 = 2 atan
−L12 + 2 L1 L2 − L22 + XE2 + YE2

Convert the solutions into MATLAB functions that you can use later. The functions TH1_MLF and
TH2_MLF represent the inverse kinematics.

TH1_MLF{1} = matlabFunction(S.theta_1(1),'Vars',[L_1 L_2 XE YE]);


TH1_MLF{2} = matlabFunction(S.theta_1(2),'Vars',[L_1 L_2 XE YE]);
TH2_MLF{1} = matlabFunction(S.theta_2(1),'Vars',[L_1 L_2 XE YE]);
TH2_MLF{2} = matlabFunction(S.theta_2(2),'Vars',[L_1 L_2 XE YE]);

Step 5: Calculate and Visualize Inverse Kinematics

Use the inverse kinematics to compute θ1 and θ2 from the X and Y coordinates.

Define the grid points of the X and Y coordinates.

[xmat,ymat] = meshgrid(0:0.01:1.5,0:0.01:1.5);

Calculate the angles θ1 and θ2 using the MATLAB functions TH1_MLF{1} and TH2_MLF{1},
respectively.

tmp_th1_mat = TH1_MLF{1}(L1,L2,xmat,ymat);
tmp_th2_mat = TH2_MLF{1}(L1,L2,xmat,ymat);

Convert the angle units from radians to degrees.

tmp_th1_mat = rad2deg(tmp_th1_mat);
tmp_th2_mat = rad2deg(tmp_th2_mat);

Some of the input coordinates, such as (X,Y) = (1.5,1.5), are beyond the reachable workspace of the
end effector. The inverse kinematics solutions can generate some imaginary theta values that require
correction. Correct the imaginary theta values.

th1_mat = NaN(size(tmp_th1_mat));
th2_mat = NaN(size(tmp_th2_mat));

3-92
Derive and Apply Inverse Kinematics to Two-Link Robot Arm

tf_mat = imag(tmp_th1_mat) == 0;
th1_mat(tf_mat) = real(tmp_th1_mat(tf_mat));

tf_mat = imag(tmp_th2_mat) == 0;
th2_mat(tf_mat) = real(tmp_th2_mat(tf_mat));

Visualize the angles θ1 and θ2 using the helper function plot_theta_given_XY_2dof.

plot_theta_given_XY_2dof(xmat,ymat,th1_mat,th2_mat)

Step 6: Compute System Jacobian

The definition of the system Jacobian is:

dX dX
d(X, Y) dθ1 dθ2
J= =
d(θ1, θ2) dY dY
dθ1 dθ2

the_J = jacobian([XE_RHS YE_RHS],[theta_1 theta_2])

the_J =
−L2 sin θ1 + θ2 − L1 sin θ1 −L2 sin θ1 + θ2
L2 cos θ1 + θ2 + L1 cos θ1 L2 cos θ1 + θ2

3-93
3 Mathematics

You can relate the joint velocity to the end-effector velocity and the other way around, by using the
system Jacobian J and its Moore-Penrose pseudoinverse J +:

dX dX dX dθ1
dt dθ1 dθ2 dt
= .
dY dY dY dθ2
dt dθ1 dθ2 dt

dX dθ1
dt dt
= J.
dY dθ2
dt dt

dθ1 dX
dt + dt
= J .
dθ2 dY
dt dt

You can also convert the symbolic expression of the Jacobian to a MATLAB function block. Simulate
the end-effector locations of the robot on a trajectory by defining the multiple waypoints as inputs to
a Simulink® model. The Simulink model can calculate a motion-profile based on the joint angle
values to reach each waypoint in the trajectory. For more details, see Inverse Kinematics of a 2-link
Robot Arm and Teaching Rigid Body Dynamics.

Helper Functions

function plot_theta_given_XY_2dof(X_mat,Y_mat,theta_1_mat_degs,...
theta_2_mat_degs)

xlab_str = 'X (m)';


ylab_str = 'Y (m)';

figure;
hax(1) = subplot(1,2,1);
contourf(X_mat, Y_mat, theta_1_mat_degs);
clim(hax(1), [-180 180]);
colormap(gca,'jet'); colorbar
xlabel(xlab_str, 'Interpreter', 'tex');
ylabel(ylab_str, 'Interpreter', 'tex');
title(hax(1), '\theta_1', 'Interpreter', 'tex')
axis('equal')
hax(2) = subplot(1,2,2);
contourf(X_mat, Y_mat, theta_2_mat_degs);
clim(hax(2), [-180 180]);
colormap(gca,'jet'); colorbar
xlabel(xlab_str, 'Interpreter', 'tex');
ylabel(ylab_str, 'Interpreter', 'tex');
title(hax(2), '\theta_2', 'Interpreter', 'tex')
axis('equal')

end

function plot_XY_given_theta_2dof(theta_1_mat_degs,theta_2_mat_degs,...

3-94
Derive and Apply Inverse Kinematics to Two-Link Robot Arm

X_mat,Y_mat,a_cmax)

xlab_str = '\theta_1 (degs)';


ylab_str = '\theta_2 (degs)';

figure;
hax(1) = subplot(1,2,1);
contourf(theta_1_mat_degs, theta_2_mat_degs, X_mat);
clim(hax(1), [0 a_cmax]);
colormap(gca,'jet'); colorbar
xlabel(xlab_str, 'Interpreter', 'tex');
ylabel(ylab_str, 'Interpreter', 'tex');
title(hax(1), 'X_E', 'Interpreter', 'tex')
hax(2) = subplot(1,2,2);
contourf(theta_1_mat_degs, theta_2_mat_degs, Y_mat);
clim(hax(1), [0 a_cmax]);
colormap(gca,'jet'); colorbar
xlabel(xlab_str, 'Interpreter', 'tex');
ylabel(ylab_str, 'Interpreter', 'tex');
title(hax(2), 'Y_E', 'Interpreter', 'tex')

end

See Also
Functions
matlabFunction | solve | simplify | jacobian

3-95
3 Mathematics

Gauss-Laguerre Quadrature Evaluation Points and Weights

This example shows how to solve polynomial equations and systems of equations, and work with the
results using Symbolic Math Toolbox™.

n

b
Gaussian quadrature rules approximate an integral by sums
a
f (t)w(t)dt ≈ ∑ f (xi)αi. Here, the xi
i=1
and αi are parameters of the method, depending on n but not on f . They follow from the choice of the
weight function w(t), as follows. Associated to the weight function is a family of orthogonal
polynomials. The polynomials' roots are the evaluation points xi. Finally, the weights αi are
determined by the condition that the method be correct for polynomials of small degree. Consider the
weight function w(t) = exp( − t) on the interval [0, ∞ ]. This case is known as Gauss-Laguerre
quadrature.

syms t
n = 4;
w(t) = exp(-t);

Assume you know the first n members of the family of orthogonal polynomials. In case of the
quadrature rule considered here, they turn out to be the Laguerre polynomials.

F = laguerreL(0:n-1, t)

F =
t2 t3 3 t2
1 1−t −2t+1 − + −3t+1
2 6 2

Let L be the n + 1 st polynomial, the coefficients of which are still to be determined.

X = sym('X', [1, n+1])

X = X1 X2 X3 X4 X5

L = poly2sym(X, t)

L = X1 t4 + X2 t3 + X3 t2 + X4 t + X5

Represent the orthogonality relations between the Laguerre polynomials F and L in a system of
equations sys.

sys = [int(F.*L.*w(t), t, 0, inf) == 0]

sys = 24 X1 + 6 X2 + 2 X3 + X4 + X5 = 0 −96 X1 − 18 X2 − 4 X3 − X4 = 0 144 X1 + 18 X2 + 2 X3 = 0 −96 X1 − 6 X2 = 0

Add the condition that the polynomial have norm 1.

sys = [sys, int(L^2.*w(t), 0, inf) == 1]

sys = 24 X1 + 6 X2 + 2 X3 + X4 + X5 = 0 −96 X1 − 18 X2 − 4 X3 − X4 = 0 144 X1 + 18 X2 + 2 X3 = 0 −96 X1 − 6 X2 = 0 4032

Solve for the coefficients of L.

3-96
Gauss-Laguerre Quadrature Evaluation Points and Weights

S = solve(sys, X)

S = struct with fields:


X1: [2x1 sym]
X2: [2x1 sym]
X3: [2x1 sym]
X4: [2x1 sym]
X5: [2x1 sym]

solve returns the two solutions in a structure array. Display the solutions.

structfun(@display, S)

ans =
1

24
1
24

ans =
2
3
2

3

ans =
−3
3

ans =
4
−4

ans =
−1
1

Make the solution unique by imposing an extra condition that the first coefficient be positive:

sys = [sys, X(1)>0];


S = solve(sys, X)

S = struct with fields:


X1: 1/24
X2: -2/3
X3: 3
X4: -4
X5: 1

Substitute the solution into L.

L = subs(L, S)

L =
t4 2 t3
− + 3 t2 − 4 t + 1
24 3

3-97
3 Mathematics

As expected, this polynomial is the |n|th Laguerre polynomial:

laguerreL(n, t)

ans =
t4 2 t3
− + 3 t2 − 4 t + 1
24 3

The evaluation points xi are the roots of the polynomial L. Solve L for the evaluation points. The roots
are expressed in terms of the root function.

x = solve(L)

x =
root σ1, z, 1
root σ1, z, 2
root σ1, z, 3
root σ1, z, 4

where

σ1 = z4 − 16 z3 + 72 z2 − 96 z + 24

The form of the solutions might suggest that nothing has been achieved, but various operations are
available on them. Compute floating-point approximations using vpa:

vpa(x)

ans =
0.32254768961939231180036145910437
1.7457611011583465756868167125179
4.5366202969211279832792853849571
9.3950709123011331292335364434205

Some spurious imaginary parts might occur. Prove symbolically that the roots are real numbers:

isAlways(in(x, 'real'))

ans = 4x1 logical array

1
1
1
1

For polynomials of degree less than or equal to 4, you can use MaxDegree to obtain the solutions in
terms of nested radicals instead in terms of root. However, subsequent operations on results of this
form would be slow.

xradical = solve(L, 'MaxDegree', 4)

xradical =

3-98
Gauss-Laguerre Quadrature Evaluation Points and Weights

4 − σ1 − σ3
4 + σ1 − σ3
σ3 − σ2 + 4
σ3 + σ2 + 4

where

96 σ6 σ4 − 3 σ5 σ4 − 288 σ4 − 512 3 6 6 + 3 6 i
σ1 = 1/4
1/6
2 768 + 128 3 6 i 144 σ6 + 9 σ5 + 864

96 σ6 σ4 − 3 σ5 σ4 − 288 σ4 + 512 3 6 6 + 3 6 i
σ2 = 1/4
1/6
2 768 + 128 3 6 i 144 σ6 + 9 σ5 + 864

σ4
σ3 = 1/6
2 768 + 128 3 6 i

σ4 = 16 σ6 + σ5 + 96

2/3
σ5 = 768 + 128 3 6 i

1/3
σ6 = 768 + 128 3 6 i

The weights αi are given by the condition that for polynomials of degree less than n, the quadrature
rule must produce exact results. It is sufficient if this holds for a basis of the vector space of these
polynomials. This condition results in a system of four equations in four variables.
y = sym('y', [n, 1]);
sys = sym(zeros(n));
for k=0:n-1
sys(k+1) = sum(y.*(x.^k)) == int(t^k * w(t), t, 0, inf);
end
sys

sys =
y1 + y2 + y3 + y4 = 1 0 0 0
y1 root σ1, z, 1 + y2 root σ1, z, 2 + y3 root σ1, z, 3 + y4 root σ1, z, 4 = 1 0 0 0
2 2 2 2
y1 root σ1, z, 1 + y2 root σ1, z, 2 + y3 root σ1, z, 3 + y4 root σ1, z, 4 =2 0 0 0
3 3 3 3
y1 root σ1, z, 1 + y2 root σ1, z, 2 + y3 root σ1, z, 3 + y4 root σ1, z, 4 =6 0 0 0

where

σ1 = z4 − 16 z3 + 72 z2 − 96 z + 24

Solve the system both numerically and symbolically. The solution is the desired vector of weights αi.

[a1, a2, a3, a4] = vpasolve(sys, y)

a1 = 0.60315410434163360163596602381808

a2 = 0.35741869243779968664149201745809

a3 = 0.03888790851500538427243816815621

a4 = 0.00053929470556132745010379056762059

3-99
3 Mathematics

[alpha1, alpha2, alpha3, alpha4] = solve(sys, y)

alpha1 =
σ3 σ2 + σ3 σ1 + σ2 σ1 − σ3 σ2 σ1 − 2 σ3 − 2 σ2 − 2 σ1 + 6

σ4 − σ3 σ4 σ2 + σ4 σ1 − σ2 σ1 − σ42

where

σ1 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 4

σ2 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 3

σ3 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 2

σ4 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 1

alpha2 =
root σ1, z, 1 root σ1, z, 3 + root σ1, z, 1 root σ1, z, 4 + root σ1, z, 3 root σ1, z, 4 − root σ1, z, 1 root σ1, z, 3 root σ1, z, 4
root σ1, z, 2 − root σ1, z, 1 root σ1, z, 2 − root σ1, z, 3 root σ1, z, 2 − root

where

σ1 = z4 − 16 z3 + 72 z2 − 96 z + 24

alpha3 =
σ3 σ2 + σ3 σ1 + σ2 σ1 − σ3 σ2 σ1 − 2 σ3 − 2 σ2 − 2 σ1 + 6
σ4 − σ1 σ3 σ2 − σ3 σ4 − σ2 σ4 + σ42

where

σ1 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 4

σ2 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 2

σ3 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 1

σ4 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 3

alpha4 =
σ3 σ2 + σ3 σ1 + σ2 σ1 − σ3 σ2 σ1 − 2 σ3 − 2 σ2 − 2 σ1 + 6

σ4 σ3 + σ42 σ2 + σ42 σ1 − σ43 + σ3 σ2 σ1 − σ3 σ2 σ4 − σ3 σ1 σ4 − σ2 σ1 σ4
2

where

σ1 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 3

σ2 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 2

σ3 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 1

σ4 = root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 4

Alternatively, you can also obtain the solution as a structure by giving only one output argument.

S = solve(sys, y)

3-100
Gauss-Laguerre Quadrature Evaluation Points and Weights

S = struct with fields:


y1: -(root(z^4 - 16*z^3 + 72*z^2 - 96*z + 24, z, 2)*root(z^4 - 16*z^3 + 72*z^2 - 96*z + 24, z
y2: (root(z^4 - 16*z^3 + 72*z^2 - 96*z + 24, z, 1)*root(z^4 - 16*z^3 + 72*z^2 - 96*z + 24, z,
y3: (root(z^4 - 16*z^3 + 72*z^2 - 96*z + 24, z, 1)*root(z^4 - 16*z^3 + 72*z^2 - 96*z + 24, z,
y4: -(root(z^4 - 16*z^3 + 72*z^2 - 96*z + 24, z, 1)*root(z^4 - 16*z^3 + 72*z^2 - 96*z + 24, z

structfun(@double, S)

ans = 4×1

0.6032
0.3574
0.0389
0.0005

Convert the structure S to a symbolic array:

Scell = struct2cell(S);
alpha = transpose([Scell{:}])

alpha =

3-101
3 Mathematics

σ3 + σ15 + σ2 − σ6 − σ12 − σ11 − σ10 + 6


− 2
root σ16, z, 1 − root σ16, z, 2 σ1 + σ4 − σ2 − root σ16, z, 1
σ1 + σ4 + σ2 − σ7 − σ13 − σ11 − σ10 + 6
root σ16, z, 2 − root σ16, z, 1 root σ16, z, 2 − root σ16, z, 3 root σ16, z, 2 − root σ16, z, 4
σ5 + σ4 + σ15 − σ8 − σ13 − σ12 − σ10 + 6
2
root σ16, z, 3 − root σ16, z, 4 σ5 − σ1 − σ3 + root σ16, z, 3
σ5 + σ1 + σ3 − σ9 − σ13 − σ12 − σ11 + 6
− 3
σ14 root σ16, z, 1 + σ14 root σ16, z, 2 + σ14 root σ16, z, 3 − root σ16, z, 4 + σ9 − σ8 − σ7 − σ6

where

σ1 = root σ16, z, 1 root σ16, z, 3

σ2 = root σ16, z, 3 root σ16, z, 4

σ3 = root σ16, z, 2 root σ16, z, 3

σ4 = root σ16, z, 1 root σ16, z, 4

σ5 = root σ16, z, 1 root σ16, z, 2

σ6 = root σ16, z, 2 root σ16, z, 3 root σ16, z, 4

σ7 = root σ16, z, 1 root σ16, z, 3 root σ16, z, 4

σ8 = root σ16, z, 1 root σ16, z, 2 root σ16, z, 4

σ9 = root σ16, z, 1 root σ16, z, 2 root σ16, z, 3

σ10 = 2 root σ16, z, 4

σ11 = 2 root σ16, z, 3

σ12 = 2 root σ16, z, 2

σ13 = 2 root σ16, z, 1

2
σ14 = root σ16, z, 4

σ15 = root σ16, z, 2 root σ16, z, 4

σ16 = z4 − 16 z3 + 72 z2 − 96 z + 24

The symbolic solution looks complicated. Simplify it, and convert it into a floating point vector:

alpha = simplify(alpha)

alpha =

3-102
Gauss-Laguerre Quadrature Evaluation Points and Weights

2
root σ1, z, 1 29 root σ1, z, 1 2
− +
72 144 3
2
root σ1, z, 2 29 root σ1, z, 2 2
− +
72 144 3
2
root σ1, z, 3 29 root σ1, z, 3 2
− +
72 144 3
2
root σ1, z, 4 29 root σ1, z, 4 2
− +
72 144 3

where

σ1 = z4 − 16 z3 + 72 z2 − 96 z + 24

vpa(alpha)

ans =
0.60315410434163360163596602381808
0.35741869243779968664149201745809
0.03888790851500538427243816815621
0.00053929470556132745010379056762059

Increase the readability by replacing the occurrences of the roots x in alpha by abbreviations:

subs(alpha, x, sym('R', [4, 1]))

ans =
R12 29 R1 2
− +
72 144 3
2
root σ1, z1, 2 29 root σ1, z1, 2 2
− +
72 144 3
2
root σ1, z1, 3 29 root σ1, z1, 3 2
− +
72 144 3
2
root σ1, z1, 4 29 root σ1, z1, 4 2
− +
72 144 3

where

σ1 = z14 − 16 z13 + 72 z12 − 96 z1 + 24

Sum the weights to show that their sum equals 1:

simplify(sum(alpha))

ans = 1

A different method to obtain the weights of a quadrature rule is to compute them using the formula
t − xj

b
αi = w(t) ∏ dt. Do this for i = 1. It leads to the same result as the other method:
a x
j≠i i
− xj

int(w(t) * prod((t - x(2:4)) ./ (x(1) - x(2:4))), t, 0, inf)

ans =

3-103
3 Mathematics

2
root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 1 29 root z4 − 16 z3 + 72 z2 − 96 z + 24, z, 1 2
− +
72 144 3

The quadrature rule produces exact results even for all polynomials of degree less than or equal to
2n − 1, but not for t2n.

simplify(sum(alpha.*(x.^(2*n-1))) -int(t^(2*n-1)*w(t), t, 0, inf))

ans = 0

simplify(sum(alpha.*(x.^(2*n))) -int(t^(2*n)*w(t), t, 0, inf))

ans = −576

Apply the quadrature rule to the cosine, and compare with the exact result:

vpa(sum(alpha.*(cos(x))))

ans = 0.50249370546067059229918484198931

int(cos(t)*w(t), t, 0, inf)

ans =
1
2

For powers of the cosine, the error oscillates between odd and even powers:

errors = zeros(1, 20);


for k=1:20
errors(k) = double(sum(alpha.*(cos(x).^k)) -int(cos(t)^k*w(t), t, 0, inf));
end
plot(real(errors))

3-104
Gauss-Laguerre Quadrature Evaluation Points and Weights

3-105
3 Mathematics

Simulate a Stochastic Process Using the Feynman–Kac Formula

This example obtains the partial differential equation that describes the expected final price of an
asset whose price is a stochastic process given by a stochastic differential equation.

The steps involved are:

1 Define Parameters of the Model Using Stochastic Differential Equations


2 Apply Ito's Rule
3 Solve Feynman–Kac Equation
4 Compute Expected Time to Sell Asset

1. Define Parameters of the Model Using Stochastic Differential Equations

A model for the price of an asset X(t) defined in the time interval [0,T] is a stochastic process
defined by a stochastic differential equation of the form dX = μ(t, X)dt + σ(t, X)dB(t), where B(t) is
the Wiener process with unit variance parameter.

Create the symbolic variable T and the following symbolic functions:

• r(t) is a continuous function representing a spot interest rate. This rate determines the discount
factor for the final payoff at the time T.
• u(t,x) is the expected value of the discounted future price calculated as X T exp −∫T r t dt
t
under the condition X(t) = x.
• μ(t, X) and σ(t, X) are drift and diffusion of the stochastic process X(t).

syms mu(t, X) sigma(t, X) r(t, X) u(t, X) T

According to the Feynman–Kac theorem, u satisfies the partial differential equation


∂u σ2 ∂2 u ∂u
∂t
+ 2 ∂x2
+ μ ∂x − ur = 0 with a final condition at time T.

eq = diff(u, t) + sigma^2*diff(u, X, X)/2 + mu*diff(u, X) - u*r;

The numerical solver pdepe works with initial conditions. To transform the final condition into an
initial condition, apply a time reversal by setting u(t, X) = v(T - t, X).

syms v(t, X)
eq2 = subs(eq, {u, t}, {v(T - t, X), T - t});
eq2 = feval(symengine, 'rewrite', eq2, 'diff')

eq2 =
2
2 ∂
σ T − t, X v t, X
∂ X2 ∂ ∂
+ μ T − t, X v t, X − v t, X − v t, X r T − t, X
2 ∂X ∂t

The solver pdepe requires the partial differential equation in the following form. Here the
coefficients c, f, and s are functions of x, t, v, and ∂v/ ∂x.

∂v ∂f
c = +s
∂t ∂x

3-106
Simulate a Stochastic Process Using the Feynman–Kac Formula

To be able to solve the equation eq2 with the pdepe solver, map eq2 to this form. First, extract the
coefficients and terms of eq2.
syms dvt dvXX
eq3 = subs(eq2, {diff(v, t), diff(v, X, X)}, {dvt, dvXX});
[k,terms] = coeffs(eq3, [dvt, dvXX])

k =
2
σ T − t, X ∂
−1 μ T − t, X v t, X − v t, X r T − t, X
2 ∂X

terms = dvt dvXX 1

Now, you can rewrite eq2 as k(1)*terms(1) + k(2)*terms(2) + k(3)*terms(3) = 0.


Moving the term with the time derivative to the left side of the equation, you get

∂v ∂2 v
= k(2) 2 + k(3)
∂t ∂X

Manually integrate the right side by parts. The result is

∂ ∂v ∂v ∂k(2)
k(2) + k(3) −
∂X ∂X ∂X ∂X

Therefore, to write eq2 in the form suitable for pdepe, use the following parameters:
c = 1;
f = k(2) * diff(v, X);
s = k(3) - diff(v, X) * diff(k(2), X);

2. Apply Ito's Rule

Asset prices follow a multiplicative process. That is, the logarithm of the price can be described in
terms of an SDE, but the expected value of the price itself is of interest because it describes the
profit, and thus we need an SDE for the latter.

In general, if a stochastic process X is given in terms of an SDE, then Ito's rule says that the
transformed process G(t, X) satisfies

2
dG σ2 d G dG dG
dG = μ + + dt + σdB(t)
dX 2 dX 2 dt dX

We assume that the logarithm of the price is given by a one-dimensional additive Brownian motion,
that is, mu and sigma are constants. Define a function that applies Ito's rule, and use it to transform
the additive Brownian motion into a geometric Brownian motion.
ito = @(mu, sigma, G, t, X) ...
deal( mu * diff(G, X) + sigma^2/2 * diff(G, X, X) + diff(G, t), ...
diff(G, X) * sigma );

syms mu0 sigma0


[mu1, sigma1] = ito(mu0, sigma0, exp(X), t, X)

mu1 =
e X σ02
+ μ0 e X
2

3-107
3 Mathematics

sigma1 = σ0 e X

Replace exp(X) by Y.

syms Y
mu1 = subs(mu1, X, log(Y));
sigma1 = subs(sigma1, X, log(Y));
f = f(t, log(Y));
s = s(t, log(Y));

For simplicity, assume that the interest rate is zero. This is a special case also known as Kolmogorov
backward equation.

r0 = 0;

c = subs(c, {mu, sigma}, {mu1, sigma1});


s = subs(s, {mu, sigma, r}, {mu1, sigma1, r0});
f = subs(f, {mu, sigma}, {mu1, sigma1});

3. Solve Feynman–Kac Equation

Before you can convert symbolic expressions to MATLAB function handles, you must replace function
calls, such as diff(v(t, X), X) and v(t, X), with variables. You can use any valid MATLAB
variable names.

syms dvdx V;
dvX = diff(v, X);
c = subs(c, {dvX, v}, {dvdx, V});
f = subs(f, {dvX, v}, {dvdx, V});
s = subs(s, {dvX, v}, {dvdx, V});

For a flat geometry (translation symmetry), set the following value:

m = 0;

Also, assign numeric values to symbolic parameters.

muvalue = 0;
sigmavalue = 1;

c0 = subs(c, {mu0, sigma0}, {muvalue, sigmavalue});


f0 = subs(f, {mu0, sigma0}, {muvalue, sigmavalue});
s0 = subs(s, {mu0, sigma0}, {muvalue, sigmavalue});

Use matlabFunction to create a function handle. Pass the coefficients c0, f0, and s0 in the form
required by pdepe, namely, a function handle with three output arguments.

FeynmanKacPde = matlabFunction(c0, f0, s0, 'Vars', [t, Y, V, dvdx])

FeynmanKacPde = function_handle with value:


@(t,Y,V,dvdx)deal(1.0,(Y.^2.*dvdx)./2.0,(Y.*dvdx)./2.0)

As the final condition, take the identity mapping. That is, the payoff at time T is given by the asset
price itself. You can modify this line in order to investigate derivative instruments.

FeynmanKacIC = @(x) x;

3-108
Simulate a Stochastic Process Using the Feynman–Kac Formula

Numerical solving of PDEs can only be applied to a finite domain. Therefore, you must specify a
boundary condition. Assume that the asset is sold at the moment when its price rises above or falls
below a certain limit, and thus the solution v has to satisfy x - v = 0 at the boundary points x. You
can choose another boundary condition, for example, you can use v = 0 to model knockout options.
The zeroes in the second and fourth output indicate that the boundary condition does not depend on
dv
dx
.

FeynmanKacBC = @(xl, vl, xr, vr, t) ...


deal(xl - vl, 0, xr - vr, 0);

Choose the space grid, which is the range of values of the price x. Set the left boundary to zero: it is
not reachable by a geometric random walk. Set the right boundary to one: when the asset price
reaches this limit, the asset is sold.

xgrid = linspace(0, 1, 101);

Choose the time grid. Because of the time reversal applied in the beginning, it denotes the time left
until the final time T.

tgrid = linspace(0, 1, 21);

Solve the equation.

sol = pdepe(m,FeynmanKacPde,FeynmanKacIC,FeynmanKacBC,xgrid,tgrid);

Plot the solution. The expected selling price depends nearly linearly on the price at time t, and also
weakly on t.

surf(xgrid, tgrid, sol)


title('Expected selling price of asset');
xlabel('price');
ylabel('time');
zlabel('expected final price');

3-109
3 Mathematics

The state of a geometric Brownian motion with drift μ1 at time t is a lognormally distributed random
variable with expected value exp(μ1t) times its initial value. This describes the expected selling price
of an asset that is never sold because of reaching a limit.

Expected = transpose(exp(tgrid./2)) * xgrid;

Dividing the solution obtained above by that expected value shows how much profit is lost by selling
prematurely at the limit.

sol2 = sol./Expected;
surf(xgrid, tgrid, sol2)
title('Ratio of expected final prices: with / without sales order at x=1')
xlabel('price');
ylabel('time');
zlabel('ratio of final prices');

3-110
Simulate a Stochastic Process Using the Feynman–Kac Formula

For example, plot the ratio of the expected payoff of an asset for which a limit sales order has been
placed and the same asset without sales order over a timespan T, as a function of t. Consider the
case of an order limit of two and four times the current price, respectively.

plot(tgrid, sol2(:, xgrid == 1/2));


hold on
plot(tgrid, sol2(:, xgrid == 1/4));
legend('Limit at two times current price', 'Limit at four times current price');
xlabel('timespan the order is valid');
ylabel('ratio of final prices: with / without sales order');
hold off

3-111
3 Mathematics

4. Compute Expected Time to Sell Asset

It is a textbook result that the expected exit time when the limit is reached and the asset is sold is
given by the following equation:
syms y(X)
exitTimeEquation(X) = subs(eq, {r, u}, {0, y(X)}) == -1

exitTimeEquation(X) =
2
2 ∂
σ t, X y X
∂ X2 ∂
+ μ t, X y X = −1
2 ∂X

In addition, y must be zero at the boundaries. For mu and sigma, insert the actual stochastic process
under consideration:
exitTimeGBM = subs(subs(exitTimeEquation, {mu, sigma}, {mu1, sigma1}), Y, X)

exitTimeGBM(X) =
∂2
X 2 σ02 y X
X σ02 ∂ ∂ X2
+ X μ0 y X + = −1
2 ∂X 2

Solve this problem for arbitrary interval borders a and b.


syms a b
exitTime = dsolve(exitTimeGBM, y(a) == 0, y(b) == 0)

3-112
Simulate a Stochastic Process Using the Feynman–Kac Formula

exitTime =
σ σ σ σ σ
2 μ0 σ4 log b − 2 μ0 σ5 log a + a 1 σ02 σ4 σ5 − b 1 σ02 σ4 σ5 log X σ2 σ6 − σ7 − a 1 σ02 σ4 + b 1 σ02 σ5 X 1 σ02
− + +
σ3 μ0 σ3 2 μ02

where

2 μ0
σ1 =
σ02

2 μ0 log X

σ2 = e σ02

σ3 = 2 μ02 σ4 − σ5

σ6

σ4 = e σ02

σ7

σ5 = e σ02

σ6 = 2 μ0 log a

σ7 = 2 μ0 log b

Because you cannot substitute mu0 = 0 directly, compute the limit at mu0 -> 0 instead.

L = limit(subs(exitTime, sigma0, sigmavalue), mu0, muvalue)

L = − log X − log a log X − log b

L is undefined at a = 0. Set the assumption that 0 < X < 1.

assume(0 < X & X < 1)

Using the value b = 1 for the right border, compute the limit.

limit(subs(L, b, 1), a, 0, 'Right')

ans = ∞

The expected exit time is infinite.

See Also
Functions
diff | subs | coeffs | matlabFunction | dsolve

3-113
3 Mathematics

The Black–Scholes Formula for Call Option Price

This example shows how to calculate the call option price using the Black–Scholes formula. This
example uses vpasolve to numerically solve the problems of finding the spot price and implied
volatility from the Black–Scholes formula.

Find Call Option Price

The Black–Scholes formula models the price of European call options [1 on page 3-118]. For a non-
dividend-paying underlying stock, the parameters of the formula are defined as:

• S is the current stock price or spot price.


• K is the exercise or strike price.
• σ is the standard deviation of continuously compounded annual returns of the stock, which is
called volatility.
• T is the time for the option to expire in years.
• r is the annualized risk-free interest rate.

The price of a call option C in terms of the Black–Scholes parameters is

C = N(d1) × S − N(d2) × PV(K),

where:

• 1 S σ2
d1 = log + r+ T
σ T K 2
• d2 = d1 − σ T
• PV(K) = Kexp( − rT)


1 d
N(d) is the standard normal cumulative distribution function, N(d) = exp( − t2 /2) dt.
2π −∞

Find the price of a European stock option that expires in three months with an exercise price of $95.
Assume that the underlying stock pays no dividend, trades at $100, and has a volatility of 50% per
annum. The risk-free rate is 1% per annum.

Use sym to create symbolic numbers that represent the values of the Black–Scholes parameters.

syms t d
S = sym(100); % current stock price (spot price)
K = sym(95); % exercise price (strike price)
sigma = sym(0.50); % volatility of stock
T = sym(3/12); % expiry time in years
r = sym(0.01); % annualized risk-free interest rate

Calculate the option price without approximation. Create a symbolic function N(d) that represents
the standard normal cumulative distribution function.

PV_K = K*exp(-r*T);
d1 = (log(S/K) + (r + sigma^2/2)*T)/(sigma*sqrt(T));
d2 = d1 - sigma*sqrt(T);
N(d) = int(exp(-((t)^2)/2),t,-Inf,d)*1/sqrt(2*sym(pi))

3-114
The Black–Scholes Formula for Call Option Price

N(d) =
2d
erf 2 1
+
2 2

Csym = N(d1)*S - N(d2)*PV_K

Csym =
20 23
2 4 log −
19 200
20 27
erf 2
2 4 log 19 + 200 1 1
50 erf − 95 e− 400 + + 50
2 2 2

To obtain the numeric result with variable precision, use vpa. By default, vpa returns a number with
32 significant digits.

Cvpa = vpa(Csym)

Cvpa = 12.52792339252145394554497137187

To change the precision, use digits. The price of the option to 6 significant digits is $12.5279.

digits(6)
Cvpa = vpa(Csym)

Cvpa = 12.5279

Plot Call Option Price

Next, suppose that for the same stock option the time to expiry changes and the day-to-day stock
price is unknown. Find the price of this call option for expiry time T that varies from 0 to 0.25 years,
and spot price S that varies from $50 to $140. Use the values for exercise rate (K), volatility (sigma),
and interest rate (r) from the previous example. In this case, use the time to expiry T and day-to-day
stock price S as the variable quantities.

Define the symbolic expression C to represent the call option price with T and S as the unknown
variables.

syms T S

PV_K = K*exp(-r*T);
d1 = (log(S/K) + (r + sigma^2/2)*T)/(sigma*sqrt(T));
d2 = d1 - sigma*sqrt(T);
Nd1 = int(exp(-((t)^2)/2),-Inf,d1)*1/sqrt(2*pi);
Nd2 = int(exp(-((t)^2)/2),-Inf,d2)*1/sqrt(2*pi);
C = Nd1*S - Nd2*PV_K;

Plot the call option price as a function of spot price and expiry time.

fsurf(C,[50 140 0 0.25])


xlabel('Spot price')
ylabel('Expiry time')
zlabel('Call option price')

3-115
3 Mathematics

Calculate the call option price with expiry time 0.1 years and spot price $105. Use subs to substitute
the values of T and S to the expression C. Return the price as a numeric result using vpa.

Csym = subs(C,[T S],[0.1 105]);


Cvpa = vpa(Csym)

Cvpa = 12.5868

Find Spot Price

Consider the case where the option price is changing, and you want to know how this affects the
underlying stock price. This is a problem of finding S from the Black–Scholes formula given the
known parameters K , σ, T , r , and C.

For example, after one month, the price of the same call option now trades at $15.04 with expiry time
of two months. Find the spot price of the underlying stock. Create a symbolic function C(S) that
represents the Black–Scholes formula with the unknown parameter S.

syms C(S) d1(S) d2(S) Nd1(S) Nd2(S)

K = 95; % exercise price (strike price)


sigma = 0.50; % volatility of stock
T = 2/12; % expiry time in years
r = 0.01; % annualized risk-free interest rate

PV_K = K*exp(-r*T);
d1(S) = (log(S/K) + (r + sigma^2/2)*T)/(sigma*sqrt(T));

3-116
The Black–Scholes Formula for Call Option Price

d2(S) = d1 - sigma*sqrt(T);
Nd1(S) = int(exp(-((t)^2)/2),-Inf,d1)*1/sqrt(2*pi);
Nd2(S) = int(exp(-((t)^2)/2),-Inf,d2)*1/sqrt(2*pi);
C(S) = Nd1*S - Nd2*PV_K;

Use vpasolve to numerically solve for the spot price of the underlying stock. Search for solutions
only in the positive numbers. The spot price of the underlying stock is $106.162.

S_Sol = vpasolve(C(S) == 15.04,S,[0 Inf])

S_Sol = 106.162

Find Implied Volatility

Consider the case where the option price is changing and you want to know what is the implied
volatility. This is a problem of finding the value of σ from the Black–Scholes formula given the known
parameters S, K , T , r , and C.

Consider the same stock option that expires in three months with an exercise price of $95. Assume
that the underlying stock trades at $100, and the risk-free rate is 1% per annum. Find the implied
volatility as a function of option price that ranges from $6 to $25. Create a vector for the range of the
option price. Create a symbolic function C(sigma) that represents the Black–Scholes formula with
the unknown parameter sigma. Use vpasolve to numerically solve for the implied volatility.

syms C(sigma) d1(sigma) d2(sigma) Nd1(sigma) Nd2(sigma)

S = 100; % current stock price (spot price)


K = 95; % exercise price (strike price)
T = 3/12; % expiry time in years
r = 0.01; % annualized risk-free interest rate
C_Range = 6:25; % range of option price
sigma_Sol = zeros(size(C_Range));

PV_K = K*exp(-r*T);
d1(sigma) = (log(S/K) + (r + sigma^2/2)*T)/(sigma*sqrt(T));
d2(sigma) = d1 - sigma*sqrt(T);
Nd1(sigma) = int(exp(-((t)^2)/2),-Inf,d1)*1/sqrt(2*pi);
Nd2(sigma) = int(exp(-((t)^2)/2),-Inf,d2)*1/sqrt(2*pi);
C(sigma) = Nd1*S - Nd2*PV_K;
for i = 1:length(C_Range)
sigma_Sol(i) = vpasolve(C(sigma) == C_Range(i),sigma,[0 Inf]);
end

Plot the implied volatility as a function of the option price.

plot(C_Range,sigma_Sol)
xlabel('Option price')
ylabel('Implied volatility')

3-117
3 Mathematics

Reference

[1] https://en.wikipedia.org/wiki/Black–Scholes_model

See Also
Functions
vpa | vpasolve | subs

3-118
Choose Function to Rearrange Expression

Choose Function to Rearrange Expression


Type of Transformation Function
“Combine Terms of Same Algebraic Structures” combine
on page 3-119
“Expand Expressions” on page 3-120 expand
“Factor Expressions” on page 3-121 factor
“Extract Subexpressions from Expression” on children
page 3-123
“Collect Terms with Same Powers” on page 3-123 collect
“Rewrite Expressions in Terms of Other rewrite
Functions” on page 3-124
“Compute Partial Fraction Decompositions of partfrac
Expressions” on page 3-125
“Compute Normal Forms of Rational simplifyFraction
Expressions” on page 3-125
“Represent Polynomials Using Horner Nested horner
Forms” on page 3-126

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:

• ab ac = ab + c
• ac bc = (a b)c
• (ab)c = abc

For example, by default the function combines the following square roots.

combine(sqrt(2)*sqrt(x))

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

The function does not combine the square roots sqrt(x)*sqrt(y) because the identity is not valid
for negative values of variables.

combine(sqrt(x)*sqrt(y))

3-119
3 Mathematics

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

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 by recreating them using syms.
syms x y

As target functions, combine accepts atan, exp, gamma, int, log, sincos, and sinhcosh.

Expand Expressions
For elementary expressions, use the expand function to transform the original expression by
multiplying sums of products. This function provides an easy way to expand polynomials.
expand((x - 1)*(x - 2)*(x - 3))

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

expand(x*(x*(x - 6) + 11) - 6)

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

The function also expands exponential and logarithmic expressions. For example, expand the
following expression containing exponentials.
expand(exp(x + y)*(x + exp(x - y)))

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

Expand an expression containing logarithm. Expanding logarithms is not valid for generic complex
values, but it is valid for positive values.
syms a b c positive
expand(log(a*b*c))

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

For further computations, clear the assumptions.

3-120
Choose Function to Rearrange Expression

syms a b c

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.

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)

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

3-121
3 Mathematics

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 the expression x^6 + 1. By default, factor uses factorization
over rational numbers keeping rational numbers in their exact symbolic form. The resulting factors
for this expression do not show polynomial roots.

factor(x^6 + 1)

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

Using other factorization modes lets you factor this expression further. For example, factor the same
expression over complex numbers.

factor(x^6 + 1,'FactorMode','complex')

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

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

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))
factor(1/sym(210))

ans =
[ 2, 2, 47, 379, 12671]

ans =
[ 1/2, 1/3, 1/5, 1/7]

factor also can factor numbers larger than flintmax that the MATLAB factor cannot. To
represent a large number accurately, place the number in quotation marks.

factor(sym('41758540882408627201'))

ans =
[ 479001599, 87178291199]

3-122
Choose Function to Rearrange Expression

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

expr = children(f)

expr =
1×3 cell array
{[y^2*exp(2*x)]} {[y^3*exp(3*x)]} {[y*exp(x)]}

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

Extract the subexpressions of expr{1} by calling children on this expression.

expr1 = children(expr{1})

expr1 =
1×2 cell array
{[y^2]} {[exp(2*x)]}

Access the contents of the cell array expr1 using braces.

expr1{1}
expr1{2}

ans =
y^2
ans =
exp(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 grouping 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
expr = x*y^4 + x*z + 2*x^3 + x^2*y*z +...
3*x^3*y^4*z^2 + y*z^2 + 5*x*y*z;
collect(expr, x)

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

Group the terms of the same expression with the equal powers of y.

collect(expr, y)

3-123
3 Mathematics

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

Group the terms of the same expression with the equal powers of z.
collect(expr, z)

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

If you do not specify variables that collect must consider as unknowns, the function uses symvar to
determine the default variable.
collect(expr)

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

Collect terms of an expression with respect to several unknowns by specifying those unknowns as a
vector.
collect(expr, [y,z])

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

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)

Use rewrite to express these trigonometric functions in terms of the exponential function.
rewrite(sin(x),'exp')

ans =
(exp(-x*1i)*1i)/2 - (exp(x*1i)*1i)/2

rewrite(cos(x),'exp')

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

3-124
Choose Function to Rearrange Expression

Use rewrite to express these hyperbolic functions in terms of the exponential function.
rewrite(sinh(x),'exp')

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

rewrite(cosh(x),'exp')

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

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


The partfrac 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, partfrac returns 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

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


The simplifyFraction function 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)

3-125
3 Mathematics

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 compared to other mathematically equivalent forms of
the same polynomial. Typically, this form of an 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

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

3-127
3 Mathematics

numden works on vectors and matrices. If an input is a vector or matrix, numden returns two vectors
or two matrices of the same size as the input. The first vector or matrix contains numerators of each
element. The second vector or matrix contains denominators of each element. For example, find
numerators and denominators of each element of the 3-by-3 Hilbert matrix.

H = sym(hilb(3))

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

[n,d] = numden(H)

n =
[ 1, 1, 1]
[ 1, 1, 1]
[ 1, 1, 1]

d =
[ 1, 2, 3]
[ 2, 3, 4]
[ 3, 4, 5]

3-128
Simplify Symbolic Expressions

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

x4 - 2x3 - 13x2 + 14x + 24.

The first form clearly shows the roots of this polynomial. This form is simpler for working with the
roots. The second form serves best when you want to see the coefficients of the polynomial. For
example, this form is convenient when you differentiate or integrate polynomials.

If the problem you want to solve requires a particular form of an expression, the best approach is to
choose the appropriate simplification function. See “Choose Function to Rearrange Expression” on
page 3-119.

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

If you do not need a particular form of expressions (expanded, factored, or expressed in particular
terms), use simplify to shorten mathematical expressions. For example, use this simplifier to find a
shorter form for a final result of your computations.

simplify works on various types of symbolic expressions, such as polynomials, expressions with
trigonometric, logarithmic, and special functions. For example, simplify these polynomials.

syms x y
simplify((1 - x^2)/(1 - x))
simplify((x - 1)*(x + 1)*(x^2 + x + 1)*(x^2 + 1)*(x^2 - x + 1)*(x^4 - x^2 + 1))

ans =
x + 1

ans =
x^12 - 1

Simplify expressions involving trigonometric functions.

simplify(cos(x)^(-2) - tan(x)^2)
simplify(cos(x)^2 - sin(x)^2)

ans =
1

ans =
cos(2*x)

Simplify expressions involving exponents and logarithms. In the third expression, use log(sym(3))
instead of log(3). If you use log(3), then MATLAB calculates log(3) with the double precision,
and then converts the result to a symbolic number.

simplify(exp(x)*exp(y))
simplify(exp(x) - exp(x/2)^2)
simplify(log(x) + log(sym(3)) - log(3*x) + (exp(x) - 1)/(exp(x/2) + 1))

3-129
3 Mathematics

ans =
exp(x + y)

ans =
0

ans =
exp(x/2) - 1

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

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
for complex values in general.

syms x
simplify(log(x^2) + log(x))

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

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

simplify(log(x^2) + log(x),'IgnoreAnalyticConstraints',true)

ans =
3*log(x)

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

3-130
Simplify Symbolic Expressions

in general. If you assume that x is a real value, simplify combines logarithms without
IgnoreAnalyticConstraints.

assume(x,'real')
simplify(log(x^2) + log(x))

ans =
log(x^3)

For further computations, clear the assumption on x by recreating it using syms.

syms x

Another approach that can improve simplification of an expression or function is the syntax
simplify(f,'Steps',n), where n is a positive integer that controls how many steps simplify
takes. Specifying more simplification steps can help you simplify the expression better, but it takes
more time. By default, n = 1. For example, create and simplify this expression. The result is shorter
than the original expression, but it can be simplified further.

syms x
y = (cos(x)^2 - sin(x)^2)*sin(2*x)*(exp(2*x) - 2*exp(x) + 1)/...
((cos(2*x)^2 - sin(2*x)^2)*(exp(2*x) - 1));
simplify(y)

ans =
(sin(4*x)*(exp(x) - 1))/(2*cos(4*x)*(exp(x) + 1))

Specify the number of simplification steps for the same expression. First, use 25 steps.

simplify(y,'Steps',25)

ans =
(tan(4*x)*(exp(x) - 1))/(2*(exp(x) + 1))

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 you want the other forms of the same
expression. To do this, you can set the 'All' option to true. The syntax
simplify(f,'Steps',n,'All',true) shows other equivalent results of the same expression in
the simplification steps.

syms x
y = cos(x) + sin(x)
simplify(y,'Steps',10,'All',true)

ans =
2^(1/2)*sin(x + pi/4)
2^(1/2)*cos(x - pi/4)
cos(x) + sin(x)
2^(1/2)*((exp(- x*1i - (pi*1i)/4)*1i)/2 - (exp(x*1i + (pi*1i)/4)*1i)/2)

To return even more equivalent results, increase the number of steps to 25.

simplify(y,'Steps',25,'All',true)

3-131
3 Mathematics

ans =
2^(1/2)*sin(x + pi/4)
2^(1/2)*cos(x - pi/4)
cos(x) + sin(x)
-2^(1/2)*(2*sin(x/2 - pi/8)^2 - 1)
2^(1/2)*(exp(- x*1i + (pi*1i)/4)/2 + exp(x*1i - (pi*1i)/4)/2)
2^(1/2)*((exp(- x*1i - (pi*1i)/4)*1i)/2 - (exp(x*1i + (pi*1i)/4)*1i)/2)

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

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

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

By default, simplifyFraction does not expand expressions in the numerator and denominator of
the returned result. To expand the numerator and denominator in the resulting expression, use the
Expand option. For comparison, first simplify this fraction without Expand.
simplifyFraction((1 - exp(x)^4)/(1 + exp(x))^4)

3-132
Simplify Symbolic Expressions

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

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)

3-133
3 Mathematics

Simplify Symbolic Expressions Using Live Editor Task

Starting in R2020a, you can interactively simplify or rearrange symbolic expressions using the
Simplify Symbolic Expression task in the Live Editor. For more information on Live Editor tasks, see
“Add Interactive Tasks to a Live Script”.

This example shows you how to simplify or rearrange various symbolic expressions into the particular
form you require by choosing the appropriate method.

Simplify a Symbolic Expression

e−ix − eix
Simplify the expression i .
e−ix + eix

First, go to the Home tab, and create a live script by clicking New Live Script. Define the
symbolic variable x and declare the expression as a symbolic expression.

syms x;
expr = 1i*(exp(-1i*x) - exp(1i*x))/(exp(-1i*x) + exp(1i*x));

In the Live Editor tab, run the code by clicking Run to store x and expr into the current
workspace.

Next, open the Simplify Symbolic Expression task by selecting Task > Simplify Symbolic
Expression in the Live Editor tab. Select the symbolic expression expr from the workspace and
specify the simplification method as Simplify. Select Minimum for the computational effort (fastest
computation time).

To get a simpler expression, change the computational effort to Medium.

3-134
Simplify Symbolic Expressions Using Live Editor Task

To experiment with simplifying symbolic expressions, you can repeat the previous steps for other
symbolic expressions and simplification methods. You can run the following examples by adding the
code to the existing live script or a new live script.

Simplify a Polynomial Fraction

(x2 − 1)(x + 1)
Simplify the polynomial fraction .
x2 − 2x + 1

Declare the polynomial fraction as a symbolic expression.


expr2 = ((x^2 - 1)*(x + 1))/(x^2 - 2*x + 1);

Select the symbolic expression expr2 from the workspace and specify the simplification method as
Simplify fraction.

Select the Expand option to return the numerator and denominator of the simplified fraction in
expanded form.

3-135
3 Mathematics

Rewrite an Expression in a Different Form

Rewrite the trigonometric function tan(x) in terms of the sine function.

Declare tan(x) as a symbolic expression.


expr3 = tan(x);

Select the symbolic expression expr3 from the workspace and specify the simplification method as
Rewrite. Choose sin to rewrite tan(x) in terms of the sine function.

Expand a Logarithmic Expression

x3 ex
Expand the expression log using the logarithmic identities.
2

3-136
Simplify Symbolic Expressions Using Live Editor Task

Declare the logarithmic expression as a symbolic expression.

expr4 = log(x^3*exp(x)/2);

Select the symbolic expression expr4 from the workspace and specify the simplification method as
Expand. By default, the symbolic variable x in expr4 is complex when it is initially created. The
Expand method does not simplify the input expression because the logarithmic identities are not
valid for complex values of variables. To apply identities that are convenient but do not always hold
for all values of variables, select the Ignore analytic constraints option.

Simplify the Sum of Two Integral Expressions

∫ x f x dx + ∫ g y dy.
b b
Simplify the sum of two integral expressions:
a a

First, define a and b as symbolic variables, and f (x) and g(y) as symbolic functions. Use the int
function to represent the integrals.

syms a b f(x) g(y)


expr5 = int(x*f(x),x,a,b) + int(g(y),y,a,b);

Select the symbolic expression expr5 from the workspace and specify the simplification method as
Combine. Choose int as the function to combine.

3-137
3 Mathematics

Generate Code

To view the code that a task used, click at the bottom of the task window. The task displays the
code block, which you can cut and paste to use or modify later in the existing script or a different
program. For example:

Because the underlying code is now part of your live script, you can continue to use the variables
created by the task for further processing. For example, define the functions f (x) and g(x) as f (x) = x
and g(x) = cos(x). Evaluate the integrals in simplifiedExpr3 by substituting these functions.

3-138
Simplify Symbolic Expressions Using Live Editor Task

See Also
Live Editor Tasks
Simplify Symbolic Expression | Solve Symbolic Equation

Functions
simplify | simplifyFraction | combine | expand | rewrite

Related Examples
• “Add Interactive Tasks to a Live Script”
• “Choose Function to Rearrange Expression” on page 3-119
• Simplify Symbolic Expression

3-139
3 Mathematics

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')
in(a, 'integer')

Suppose, you know that the value of the parameter a is 2. Substitute a with 2 in the solution vector
solx.

subs(solx, a, 2)

ans =
(5*pi)/2
(23*pi)/6
(31*pi)/6

Alternatively, substitute params with 2. This approach returns the same result.

3-140
Substitute Variables in Symbolic Expressions

subs(solx, params, 2)

ans =
(5*pi)/2
(23*pi)/6
(31*pi)/6

Substitute parameter a with a floating-point number. The toolbox converts numbers to floating-point
values, but it keeps intact the symbolic expressions, such as sym(pi), exp(sym(1)), and so on.

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

3-141
3 Mathematics

Substitute Elements in Symbolic Matrices

Create a 2-by-2 matrix A with automatically generated elements using sym. The generated elements
A1, 1, A1, 2, A2, 1, and A2, 2 do not appear in the MATLAB® workspace.

A = sym('A',[2 2])

A =
A1, 1 A1, 2
A2, 1 A2, 2

Substitute the element A1, 2 with a value 5. Assign the value directly by indexing into the matrix
element.
A(1,2) = 5

A =
A1, 1 5
A2, 1 A2, 2

Alternatively, you can create a 2-by-2 matrix using syms. Create a matrix B using syms.
syms B [2 2]
B

B =
B1, 1 B1, 2
B2, 1 B2, 2

The generated elements B1, 1, B1, 2, B2, 1, and B2, 2 appear as symbolic variables B1_1, B1_2, B2_1,
and B2_2 in the MATLAB workspace. Use subs to substitute the element of B by specifying the
variable name. For example, substitute B2_2 with 4.
B = subs(B,B2_2,4)

B =
B1, 1 B1, 2
B2, 1 4

You can also create a matrix by specifying the elements individually. Create a 3-by-3 circulant matrix
M.
syms a b c
M = [a b c; b c a; c a b]

M =
a b c
b c a
c a b

Replace variable b in the matrix M by the expression a + 1. The subs function replaces all b elements
in matrix M with the expression a + 1.
M = subs(M,b,a+1)

3-142
Substitute Elements in Symbolic Matrices

M =
a a+1 c
a+1 c a
c a a+1

Next, replace all elements whose value is c with a + 2. You can specify the value to replace as c,
M(1,3) or M(3,1).

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

M =
a a+1 a+2
a+1 a+2 a
a+2 a a+1

To replace a particular element of a matrix with a new value while keeping all other elements
unchanged, use the assignment operation. For example, M(1,1) = 2 replaces only the first element
of the matrix M with the value 2.

Find eigenvalues and eigenvectors of the matrix M.

[V,E] = eig(M)

V =
3 1 3 1
1 − − −
2 2 2 2
3 1 3 1
1− − −
2 2 2 2
1 1 1

E =
3a+3 0 0
0 3 0
0 0 − 3

Replace the symbolic parameter a with the value 1.

subs(E,a,1)

ans =
6 0 0
0 3 0
0 0 − 3

3-143
3 Mathematics

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.

subs(S, t, sym(pi)./[1:6])

[ 0,...
0,...
5*3^(1/2), 4*2^(1/2) + 6,...
2^(1/2)*(5 - 5^(1/2))^(1/2) + (5*2^(1/2)*(5^(1/2) + 5)^(1/2))/2,...
3*3^(1/2) + 6]

You also can use subs to replace a scalar element of a matrix with another matrix. In this case, subs
expands the matrix to accommodate new elements. For example, replace zero elements of the matrix
F with a column vector [1;2]. The original 4-by-4 matrix F expands to an 8-by-4 matrix. The subs
function duplicates each row of the original matrix, not only the rows containing zero elements.

F = subs(F, 0, [1;2])

3-144
Substitute Scalars with Matrices

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

3-145
3 Mathematics

Evaluate Symbolic Expressions Using subs


When you assign a value to a symbolic variable, expressions containing the variable are not
automatically evaluated. Instead, evaluate expressions by using subs.

Define the expression y = x^2.

syms x
y = x^2;

Assign 2 to x. The value of y is still x^2 instead of 4.

x = 2;
y

y =
x^2

If you change the value of x again, the value of y stays x^2. Instead, evaluate y with the new value of
x by using subs.

subs(y)

ans =
4

The evaluated result is 4. However, y has not changed. Change the value of y by assigning the result
to y.

y = subs(y)

y =
4

Show that y is independent of x after this assignment.

x = 5;
subs(y)

ans =
4

3-146
Abbreviate Common Terms in Long Expressions

Abbreviate Common Terms in Long Expressions

Long expressions often contain several instances of the same subexpression. Such expressions look
shorter if the same subexpression is replaced with an abbreviation. You can use sympref to specify
whether or not to use abbreviated output format of symbolic expressions in live scripts.

1
For example, solve the equation x + = 1 using solve.
x

syms x
sols = solve(sqrt(x) + 1/x == 1, x)

sols =
σ2 1 2
1
+ + − σ1
18 σ2 2 3
σ2 1 2
1
+ + + σ1
18 σ2 2 3

where
1
3 9 σ − σ2 i
2
σ1 =
2

25 23 108 1/3
σ2 = −
54 108

The solve function returns exact solutions as symbolic expressions. By default, live scripts display
symbolic expressions in abbreviated output format. The symbolic preference setting uses an internal
algorithm to choose which subexpressions to abbreviate, which can also include nested abbreviations.
For example, the term σ1 contains the subexpression abbreviated as σ2. The symbolic preference
setting does not provide any options to choose which subexpressions to abbreviate.

You can turn off abbreviated output format by setting the 'AbbreviateOutput' preference to
false. The returned result is a long expression that is difficult to read.

sympref('AbbreviateOutput',false);
sols

sols =

3-147
3 Mathematics

2
1 25 23 108 1/3
3 − − i
25 23 108 1/3 25 23 108 1/3 54 108
1 54
− 108 1 9
54

108
+ + −
25 23 108 1/3 2 3 2
18 54 − 108

2
1 25 23 108 1/3
3 − − i
25 23 108 1/3 25 23 108 1/3 54 108
1 54
− 108 1 9
54

108
+ + +
25 23 108 1/3 2 3 2
18 54 − 108

The preferences you set using sympref persist through your current and future MATLAB® sessions.
Restore the default values of 'AbbreviateOutput' by specifying the 'default' option.
sympref('AbbreviateOutput','default');

subexpr is another function that you can use to shorten long expressions. This function abbreviates
only one common subexpression, and unlike sympref, it does not support nested abbreviations. Like
sympref, subexpr also does not let you choose which subexpressions to replace.

Use the second input argument of subexpr to specify the variable name that replaces the common
subexpression. For example, replace the common subexpression in sols with the variable t.
[sols1,t] = subexpr(sols,'t')

sols1 =
1 2
t 1 1 3 t− 9t i
+ + +
2 18 t 3 2

1 2
t 1 1 3 t− 9t i
+ + −
2 18 t 3 2

t =
25 23 108 1/3

54 108

Although sympref and subexpr do not provide a way to choose which subexpressions to replace in a
solution, you can define these subexpressions as symbolic variables and manually rewrite the
solution.

For example, define new symbolic variables a1 and a2.


syms a1 a2

Rewrite the solutions sols in terms of a1 and a2 before assigning the values of a1 and a2 to avoid
evaluating sols.
sols = [(1/2*a1 + 1/3 + sqrt(3)/2*a2*1i)^2;...
(1/2*a1 + 1/3 - sqrt(3)/2*a2*1i)^2]

3-148
Abbreviate Common Terms in Long Expressions

sols =
a1 1 3 a2 i 2
+ +
2 3 2

a1 1 3 a2 i 2
+ −
2 3 2

1 1
Assign the values t + and t − to a1 and a2, respectively.
9t 9t

a1 = t + 1/(9*t)

a1 =
1 25 23 108 1/3
+ −
25 23 108 1/3 54 108
9 54 − 108

a2 = t - 1/(9*t)

a2 =
25 23 108 1/3 1
− −
54 108 25 23 108 1/3
9 54 − 108

Evaluate sols using subs. The result is identical to the first output in this example.

sols_eval = subs(sols)

sols_eval =
σ2 1 2
1
+ + − σ1
18 σ2 2 3
σ2 1 2
1
+ + + σ1
18 σ2 2 3

where
1
3 9 σ − σ2 i
2
σ1 =
2

25 23 108 1/3
σ2 = −
54 108

3-149
3 Mathematics

Harmonic Analysis of Transfer Function Output

This example finds closed-form solutions for the coefficients of frequencies in an output signal. The
output signal results from passing an input through an analytical nonlinear transfer function.

This example uses the following Symbolic Math Toolbox™ capabilities:

• Taylor series expansion using taylor


• “Formula Manipulation and Simplification”

Motivation

To motivate the solution, we take a simple element from circuit theory: an ideal diode (in forward bias
operation). The current, I, is the output that depends exponentially on the input, V. Diodes have
found use in creating devices such as mixers and amplifiers where understanding the harmonic
structure of the output can be useful in characterizing the device and meeting design specifications.

syms Is V Vo real;
I = Is*(exp(V/Vo) - 1)

I = Is eV /Vo − 1

If V is a linear combination of 2 signals at frequencies LO and RF, the nonlinear transfer function will
mix LO and RF to create output with content at combinatorial harmonic frequency combinations:
freqs = {LO, 2LO, RF, 2RF, LO-RF, LO-2RF,...}.

The objective of this example is to determine the coefficients of freqs in the output.

3-150
Harmonic Analysis of Transfer Function Output

Define Input Signal

The input signal is a linear combination of two cosine signals.

syms c1 c2 t LO RF real;
input = c1*cos(LO*t) + c2*cos(RF*t)

input = c1 cos LO t + c2 cos RF t

Define Space of Harmonic Frequency Combinations

Below, harmCombinations is a combinatorial combination of the integer multiples of the input


frequencies LO and RF. We restrict the space of interest defined by 3 harmonics each in the LO and
RF directions.

n = 3;
harmCombinations = [kron((0:n)',ones(n*2+1,1)),repmat((-n:n)',n+1,1)];
freqs = harmCombinations*[LO;RF];

The first n frequencies are just the negative harmonic frequencies and are therefore redundant
considering that the input signal is real.

freqs = freqs(n+1:end)

freqs =
0
RF
2 RF
3 RF
LO − 3 RF
LO − 2 RF
LO − RF
LO
LO + RF
LO + 2 RF
LO + 3 RF
2 LO − 3 RF
2 LO − 2 RF
2 LO − RF
2 LO
2 LO + RF
2 LO + 2 RF
2 LO + 3 RF
3 LO − 3 RF
3 LO − 2 RF
3 LO − RF
3 LO
3 LO + RF
3 LO + 2 RF
3 LO + 3 RF

3-151
3 Mathematics

Taylor Expansion

To cover the frequency spectrum of interest, a Taylor series of order four for I(V) is sufficient.

s = taylor(I, V, 'Order', 4)

s =
Is V 2Is V 3 Is V
+ +
2 Vo2
6 Vo 3 Vo

Use an input signal combination of the LO and RF frequencies and express f in terms of cos(LO*t)
and cos(RF*t).

f0 = subs(s, V, input);
f = expand(f0)

f =
3 3
Is c12 σ2 Is c13 cos LO t Is c22 σ1 Is c23 cos RF t Is c1 cos LO t Is c2 cos RF t Is c1 c2 cos LO t cos RF t
+ + + + + + +
2 Vo2 3
6 Vo 2 Vo2 6 Vo 3 Vo Vo Vo2

where
2
σ1 = cos RF t

2
σ2 = cos LO t

Rewrite f in terms of single powers of cosines.

f = combine(f, 'sincos')

f =
Is c12 Is c22 Is c1 cos LO t Is c2 cos RF t Is c12 cos 2 LO t Is c13 cos LO t Is c13 cos 3 LO t
+ + + + + +
4 Vo 2
4 Vo 2 Vo Vo 4 Vo 2
8 Vo 3
24 Vo3
Is c22 cos 2 RF t Is c23 cos RF t Is c23 cos 3 RF t Is c1 c22 cos LO t Is c12 c2 cos RF t
+ 2
+ 3
+ 3
+ 3
+
4 Vo 8 Vo 24 Vo 4 Vo 4 Vo3
Is c1 c2 cos LO t + RF t Is c1 c2 cos LO t − RF t Is c1 c22 cos LO t − 2 RF t
+ 2
+ 2
+
2 Vo 2 Vo 8 Vo3
Is c1 c22 cos LO t + 2 RF t Is c12 c2 cos 2 LO t + RF t Is c12 c2 cos 2 LO t − RF t
+ 3
+ 3
+
8 Vo 8 Vo 8 Vo3

Extract and Display Coefficients

Get the non-constant i.e. non-DC harmonic frequency terms of the form cos(freq*t).

cosFreqs = cos(expand(freqs*t));
terms = collect(setdiff(cosFreqs', sym(1)));

Extract the coefficients for all harmonic frequency terms including DC.

newvars = sym('x', [1,numel(terms)]);


[cx, newvarsx] = coeffs(subs(f,terms,newvars), newvars);
tx = sym(zeros(1,numel(cx)));
for k=1:numel(newvarsx)
if newvarsx(k) ~= 1
tx(k) = terms(newvars == newvarsx(k));

3-152
Harmonic Analysis of Transfer Function Output

else
tx(k) = newvarsx(k);
end
end
cx = simplify(cx);

Display the coefficients using table, T. Use cosFreqs as a row identifier.

cosFreqs = arrayfun(@char,cosFreqs,'UniformOutput',false);
Frequencies = arrayfun(@char,freqs,'UniformOutput',false);
Coefficients = num2cell(zeros(size(freqs)));
T = table(Frequencies,Coefficients,'RowNames',cosFreqs);

Assign cx to the appropriate rows of T corresponding to the cosine terms of tx.

nonzeroCosFreqs = arrayfun(@char,tx,'UniformOutput',false).';
T(nonzeroCosFreqs,'Coefficients') = arrayfun(@char,cx,'UniformOutput',false).';

Now, remove row names as they are redundant.

T.Properties.RowNames = {};

Observe that the expressions for the terms are symmetric in LO and RF.

T=25×2 table
Frequencies Coefficients
_______________ _____________________________________________

{'0' } {'(Is*(c1^2 + c2^2))/(4*Vo^2)' }


{'RF' } {'(Is*c2*(8*Vo^2 + 2*c1^2 + c2^2))/(8*Vo^3)'}
{'2*RF' } {'(Is*c2^2)/(4*Vo^2)' }
{'3*RF' } {'(Is*c2^3)/(24*Vo^3)' }
{'LO - 3*RF' } {[ 0]}
{'LO - 2*RF' } {'(Is*c1*c2^2)/(8*Vo^3)' }
{'LO - RF' } {'(Is*c1*c2)/(2*Vo^2)' }
{'LO' } {'(Is*c1*(8*Vo^2 + c1^2 + 2*c2^2))/(8*Vo^3)'}
{'LO + RF' } {'(Is*c1*c2)/(2*Vo^2)' }
{'LO + 2*RF' } {'(Is*c1*c2^2)/(8*Vo^3)' }
{'LO + 3*RF' } {[ 0]}
{'2*LO - 3*RF'} {[ 0]}
{'2*LO - 2*RF'} {[ 0]}
{'2*LO - RF' } {'(Is*c1^2*c2)/(8*Vo^3)' }
{'2*LO' } {'(Is*c1^2)/(4*Vo^2)' }
{'2*LO + RF' } {'(Is*c1^2*c2)/(8*Vo^3)' }

Verify Coefficients

As shown below, the output waveform is reconstructed from the coefficients and has an exact match
with the output.

simplify(f0 - (dot(tx,cx)))

ans = 0

3-153
3 Mathematics

Plot Nonlinear Transfer

The following shows the particular nonlinear transfer function analyzed above, in the time and
frequency domains, for certain values of the frequencies and voltage ratios. First, extract the data.

sample_values = struct('c1',0.4,'c2',1,'LO',800,'RF',13600,'Vo',1,'Is',1);
sample_input = subs(input,sample_values)

sample_input =
2 cos 800 t
+ cos 13600 t
5

sample_output = subs(f,sample_values)

sample_output =
127 cos 800 t cos 1600 t cos 2400 t cos 12000 t cos 12800 t 233 cos 13600 t
+ + + + +
250 25 375 50 5 200
cos 14400 t cos 15200 t cos 26400 t cos 27200 t cos 28000 t cos 40800 t 29
+ + + + + + +
5 50 20 4 20 24 100

sample_freqs = zeros(size(tx));
for k=1:numel(tx)
cosTerm = subs(tx(k),sample_values);
freq = simplify(acos(cosTerm),'IgnoreAnalyticConstraints',true)/t;
sample_freqs(k) = double(freq);
end
sample_heights = double(subs(cx,sample_values));

Then, use fplot and stem to plot the functions and their harmonic frequencies.

subplot(2,2,1);
fplot(sample_input,[0,0.01])
title Input
subplot(2,2,3);
stem([sample_values.LO, sample_values.RF],[sample_values.c1,sample_values.c2]);
title 'Input Frequencies'

subplot(2,2,2);
fplot(sample_output,[0,0.01])
title Output
subplot(2,2,4);
stem(sample_freqs,sample_heights)
title 'Output Frequencies'

3-154
Harmonic Analysis of Transfer Function Output

3-155
3 Mathematics

Explore Single-Period Asset Arbitrage

This example explores basic arbitrage concepts in a single-period, two-state asset portfolio. The
portfolio consists of a bond, a long stock, and a long call option on the stock.

It uses these Symbolic Math Toolbox™ functions:

• equationsToMatrix to convert a linear system of equations to a matrix.


• linsolve to solve the system.
• Symbolic equivalents of standard MATLAB® functions, such as diag.

This example symbolically derives the risk-neutral probabilities and call price for a single-period, two-
state scenario.

Define Parameters of the Portfolio

Create the symbolic variable r representing the risk-free rate over the period. Set the assumption
that r is a positive value.

syms r positive

Define the parameters for the beginning of a single period, time = 0. Here S0 is the stock price, and
C0 is the call option price with strike, K.

syms S0 C0 K positive

Now, define the parameters for the end of a period, time = 1. Label the two possible states at the
end of the period as U (the stock price over this period goes up) and D (the stock price over this
period goes down). Thus, SU and SD are the stock prices at states U and D, and CU is the value of the
call at state U. Note that SD < = K < = SU.

syms SU SD CU positive

3-156
Explore Single-Period Asset Arbitrage

The bond price at time = 0 is 1. Note that this example ignores friction costs.

Collect the prices at time = 0 into a column vector.


prices = [1 S0 C0]'

prices =
1
S0
C0

Collect the payoffs of the portfolio at time = 1 into the payoff matrix. The columns of payoff
correspond to payoffs for states D and U. The rows correspond to payoffs for bond, stock, and call.
The payoff for the bond is 1 + r. The payoff for the call in state D is zero since it is not exercised
(because SD < = K).
payoff = [(1 + r), (1 + r); SD, SU; 0, CU]

payoff =
r+1 r+1
SD SU
0 CU

CU is worth SU - K in state U. Substitute this value in payoff.


payoff = subs(payoff, CU, SU - K)

payoff =
r+1 r+1
SD SU
0 SU − K

Solve for Risk-Neutral Probabilities

Define the probabilities of reaching states U and D.


syms pU pD real

Under no-arbitrage, eqns == 0 must always hold true with positive pU and pD.
eqns = payoff*[pD; pU] - prices

eqns =
pD r + 1 + pU r + 1 − 1
SD pD − S0 + SU pU
−C0 − pU K − SU

Transform equations to use risk-neutral probabilities.


syms pDrn pUrn real;
eqns = subs(eqns, [pD; pU], [pDrn; pUrn]/(1 + r))

eqns =
pDrn + pUrn − 1
SD pDrn SU pUrn
− S0 +
r+1 r+1
pUrn K − SU
−C0 −
r+1

3-157
3 Mathematics

The unknown variables are pDrn, pUrn, and C0. Transform the linear system to a matrix form using
these unknown variables.
[A, b] = equationsToMatrix(eqns, [pDrn, pUrn, C0]')

A =
1 1 0
SD SU
0
r+1 r+1
K − SU
0 − −1
r+1

b =
1
S0
0

Using linsolve, find the solution for the risk-neutral probabilities and call price.
x = linsolve(A, b)

x =
S0 − SU + S0 r
SD − SU
S0 − SD + S0 r

SD − SU
K − SU S0 − SD + S0 r
SD − SU r + 1

Verify the Solution

Verify that under risk-neutral probabilities, x(1:2), the expected rate of return for the portfolio,
E_return equals the risk-free rate, r.
E_return = diag(prices)\(payoff - [prices,prices])*x(1:2);
E_return = simplify(subs(E_return, C0, x(3)))

E_return =
r
r
r

Test for No-Arbitrage Violations

As an example of testing no-arbitrage violations, use the following values: r = 5%, S0 = 100, and K
= 100. For SU < 105, the no-arbitrage condition is violated because pDrn = xSol(1) is negative
(SU >= SD). Further, for any call price other than xSol(3), there is arbitrage.
xSol = simplify(subs(x, [r,S0,K], [0.05,100,100]))

xSol =
SU − 105

SD − SU
SD − 105
SD − SU
20 SD − 105 SU − 100
21 SD − SU

3-158
Explore Single-Period Asset Arbitrage

Plot Call Price as a Surface

Plot the call price, C0 = xSol(3), for 50 <= SD <= 100 and 105 <= SU <= 150. Note that the
call is worth more when the "variance" of the underlying stock price is higher for example, SD = 50,
SU = 150.

fsurf(xSol(3), [50,100,105,150])
xlabel SD
ylabel SU
title 'Call Price'

Reference

Advanced Derivatives, Pricing and Risk Management: Theory, Tools and


Programming Applications by Albanese, C., Campolieti, G.

3-159
3 Mathematics

Analytical Solutions of the Inverse Kinematics of a Humanoid


Robot

This example shows how to derive analytical solutions for the inverse kinematics of the head chain of
a humanoid robot.

Step 1: Define Parameters

Describe the kinematics of the head-chain link (the link between the torso and the head) of the NAO
humanoid robot [1] using the Denavit-Hartenberg (DH) parameters and notations based on a study by
Kofinas et al. [2]. The following transformation defines the head-chain link.

T = ABase, 0T0, 1T1, 2RxRy A2, Head

where:

• ABase, 0 is the translation from the base (torso) to the joint or reference frame 0
• T0, 1 is the orientation of reference 1 relative to 0
• T1, 2 is the orientation of reference 2 relative to 1
• Rx is the roll rotation
• Ry is the pitch rotation
• A2, Head is the translation from reference 2 to the end-effector point (the head)

T(1: 3, 4) defines the coordinates of the head, which are xc, yc, zc.

In this example, you analytically solve the inverse kinematics problem by returning all orientations of
individual joints in the head-chain link given head coordinates of xc, yc, and zc within the reachable
space. Then, you convert the analytical results to purely numeric functions for efficiency.

Solving analytically (when doing so is possible) lets you perform computations in real time and avoid
singularities, which cause difficulty for numerical methods.

Step 2: Define Forward Kinematics of Head Chain Using DH Parameters

The function getKinematicChain returns the specific kinematic chain for the NAO robot in terms of
symbolic variables. For details on getKinematicChain, see the Helper Functions section.

kinChain = 'head';
dhInfo = getKinematicChain(kinChain);
T = dhInfo.T

T =
r11 r12 r13 xc
r21 r22 r23 yc
r31 r32 r33 zc
0 0 0 1

Express the forward kinematics transformation matrix T as the following sequence of products: T =
ABase0*T01*T12*Rx*Ry*A2Head. Define the individual matrices as follows.

3-160
Analytical Solutions of the Inverse Kinematics of a Humanoid Robot

Specify the translation matrix from the torso (base) to joint 0.

ABase0 = dhInfo.ABase0

ABase0 =
100 0
010 0
0 0 1 NeckOffsetZ
000 1

Specify the transformation matrix from joint 0 to joint 1.

T01 = dhInfo.T01

T01 =
cos θ1 −sin θ1 0 0
sin θ1 cos θ1 0 0
0 0 10
0 0 01

Specify the transformation matrix from joint 1 to joint 2.

T12 = dhInfo.T12

T12 =
π π
cos θ2 − 0 −sin θ2 − 0
2 2
0 0 1 0
π π
−sin θ2 − −cos θ2 − 0 0
2 2
0 0 0 1

Specify the roll rotation matrix.

Rx = dhInfo.Rx

Rx =
1 0 0 0
0 0 −1 0
0 1 0 0
0 0 0 1

Specify the pitch rotation matrix.

Ry = dhInfo.Ry

Ry =
0 0 1 0
0 1 0 0
−1 0 0 0
0 0 0 1

Specify the translation matrix from joint 2 to the head.

A2Head = dhInfo.A2Head

3-161
3 Mathematics

A2Head =
1 0 0 CameraX
010 0
0 0 1 CameraZ
000 1

The known parameters of this problem are CameraX, CameraZ, NeckOffsetZ, and the positions xc,
yc, and zc. The unknown parameters are θ1 and θ2. After finding θ1 and θ2, you can compute the
individual transformations of T. The robot can then achieve the desired position xc, yc, zc.

Although you can see these parameters in the transformation matrices, they do not exist as variables
in the MATLAB base workspace. This is because these parameters originate from a function.
Functions do not use the base workspace. Each function workspace is separate from the base
workspace and all other workspaces to protect the data integrity. Thus, to use these variables outside
of the function getKinematicChain, use syms to create them.
syms CameraX CameraZ NeckOffsetZ xc yc zc theta_1 theta_2 real;

Step 3: Find Algebraic Solutions for θ1 and θ2

Rewrite the equation T = ABase0*T01*T12*Rx*Ry*A2Head, separating the terms that describe the
torso and head movements of the robot: inv(T01)*inv(ABase0)*T = T12*Rx*Ry*A2Head.
Simplify the left and right sides of the equation, and define equations of interest matching the
expressions for coordinate positions.
LHS = simplify(inv(T01)*inv(ABase0)*T);
RHS = simplify(T12*Rx*Ry*A2Head);
eqns = LHS(1:3,end) - RHS(1:3,end)

eqns =
xc cos θ1 − CameraZ sin θ2 − CameraX cos θ2 + yc sin θ1
yc cos θ1 − xc sin θ1
zc − NeckOffsetZ − CameraZ cos θ2 + CameraX sin θ2

This system of equations contains two variables for which you want to find solutions, θ1 and θ2.
However, the equations also imply that you cannot arbitrarily choose xc, yc, and zc. Therefore, also
consider yc as a variable. All other unknowns of the system are symbolic parameters.

This example follows a typical algebraic approach for solving inverse kinematics problems [3]. The
idea is to get a compact representation of the solution, where the expression of each variable is in
terms of parameters and variables for which you already solved the equations. As a first step, find
either θ1 or θ2 in terms of the parameters. Then, express the other variable in terms of the known
variable and parameters. To do this, start by identifying the equation that has only one variable.
intersect(symvar(eqns(1)),[theta_1,theta_2,yc])

ans = θ1 θ2 yc

intersect(symvar(eqns(2)),[theta_1,theta_2,yc])

ans = θ1 yc

intersect(symvar(eqns(3)),[theta_1,theta_2,yc])

ans = θ2

3-162
Analytical Solutions of the Inverse Kinematics of a Humanoid Robot

The third equation contains only one variable, θ2. Solve this equation first.

[theta_2_sol,theta_2_params,theta_2_conds] = ...
solve(eqns(3),theta_2,'Real',true,'ReturnConditions',true)

theta_2_sol =
2 2 2
CameraX − CameraX + CameraZ − NeckOffsetZ + 2 NeckOffsetZ zc − zc2
2 π k − 2 atan
CameraZ − NeckOffsetZ + zc
2 2 2
CameraX + CameraX + CameraZ − NeckOffsetZ + 2 NeckOffsetZ zc − zc2
2 π k − 2 atan
CameraZ − NeckOffsetZ + zc

theta_2_params = k

theta_2_conds =
2 2 2
k ∈ ℤ ∧ CameraZ + zc ≠ NeckOffsetZ ∧ NeckOffsetZ − zc ≤ CameraX + CameraZ
2 2 2
k ∈ ℤ ∧ CameraZ + zc ≠ NeckOffsetZ ∧ NeckOffsetZ − zc ≤ CameraX + CameraZ

The solutions have an additive 2πk term with the parameter k. Without loss of generalization, you can
set k equal to 0 in the solutions and conditions.

theta_2_sol = subs(theta_2_sol,theta_2_params,0)

theta_2_sol =
2 2 2
CameraX − CameraX + CameraZ − NeckOffsetZ + 2 NeckOffsetZ zc − zc2
−2 atan
CameraZ − NeckOffsetZ + zc
2 2 2
CameraX + CameraX + CameraZ − NeckOffsetZ + 2 NeckOffsetZ zc − zc2
−2 atan
CameraZ − NeckOffsetZ + zc

for p = 1:numel(theta_2_conds)
theta_2_conds(p) = simplify(subs(theta_2_conds(p),theta_2_params,0));
end

Now solve for the variables θ1 and yc in terms of the variable θ2 and other symbolic parameters.

[theta_1_sol,yc_sol,yc_theta_1_params,yc_theta_1_conds] = ...
solve(eqns(1:2),theta_1,yc,'Real',true,'ReturnConditions',true);

Display the solutions for θ1 and yc.

theta_1_sol

theta_1_sol =

3-163
3 Mathematics

2 π k − σ1
σ2 + 2 π k
2 π k − σ2
π
2πk−
2
σ1 + 2 π k
2 atan x + 2 π k
π
+2πk
2
π
2πk−
2
π
+2πk
2

where

CameraX + xc CameraX − xc
σ1 = 2 atan
CameraX − xc
σ3 σ5 σ3
σ5 + 1
+ σ +1
5
σ2 = 2 atan
σ4

θ2
σ3 = − xc − CameraX + CameraX σ5 + xc σ5 − 2 CameraZ tan σ4
2

θ2
σ4 = CameraX + xc − CameraX σ5 + xc σ5 + 2 CameraZ tan
2

θ2 2
σ5 = tan
2

yc_sol

yc_sol =

3-164
Analytical Solutions of the Inverse Kinematics of a Humanoid Robot

CameraX + xc CameraX − xc
σ1
−σ1
CameraX
− CameraX + xc CameraX − xc
0
σ2
−σ2
−CameraX

where

θ2 2 θ2 2
− xc − CameraX + σ3 + xc tan 2 − σ4 CameraX + xc − σ3 + xc tan 2 + σ4
σ1 =
θ2 2
tan 2 +1

−σ3 + σ4 + CameraX
σ2 =
θ2 2
tan 2 +1

θ2 2
σ3 = CameraX tan
2

θ2
σ4 = 2 CameraZ tan
2

The solutions depend on two parameters, k and x.

yc_theta_1_params

yc_theta_1_params = k x

The solutions have an additive 2πk term. Without loss of generalization, you can set k equal to 0 in
the solution for theta_1_sol and the conditions yc_theta_1_conds.

theta_1_sol = simplify(subs(theta_1_sol,yc_theta_1_params,[0,0]))

theta_1_sol =

3-165
3 Mathematics

CameraX + xc CameraX − xc
−2 atan
CameraX − xc
σ1
−σ1
π

2
CameraX + xc CameraX − xc
2 atan
CameraX − xc
0
π
2
π

2
π
2

where

CameraX cos θ2 − xc + CameraZ sin θ2 xc + CameraX cos θ2 + CameraZ sin θ2


σ1 = 2 atan
xc + CameraX cos θ2 + CameraZ sin θ2

for p = 1:numel(yc_theta_1_conds)
yc_theta_1_conds(p) = simplify(subs(yc_theta_1_conds(p),yc_theta_1_params,[0,0]));
end

A similar substitution is not required for yc_sol since there is no dependency on the parameters.

intersect(symvar(yc_sol),yc_theta_1_params)

ans =

Empty sym: 1-by-0

Step 4: Verify the Solutions

Starting with an arbitrary set of known numeric values for θ1 and θ2, compute the numeric values of
the end-effector positions xc, yc, and zc with forward kinematics. Then, work backwards from xc,
yc, and zc to compute all possible numeric values for θ1 and θ2 using the inverse kinematics
expressions from the previous computation. Verify that one set of the inverse solutions matches the
starting set of numeric values for θ1 and θ2.

Set the fixed parameters for the robot. The values in this example are for illustration purposes only.

CameraXValue = 53.9;
CameraZValue = 67.9;
NeckOffsetZValue = -5;

Using forward computations, find the end-effector positions corresponding to the values θ1 and θ2.

Tfk = ABase0*T01*T12*Rx*Ry*A2Head;
xyz = Tfk(1:3,end);

Create a symbolic function for these positions.

3-166
Analytical Solutions of the Inverse Kinematics of a Humanoid Robot

xyzFunc = symfun(subs(xyz,[CameraX,CameraZ,NeckOffsetZ], ...


[CameraXValue,CameraZValue,NeckOffsetZValue]),[theta_1,theta_2]);

For forward kinematics, specify two variables theta_1_known and theta_2_known that contain an
arbitrary starting set of values for θ1 and θ2.

theta_1_known = [pi/4,pi/6,pi/8,pi/10];
theta_2_known = [pi/8,-pi/12,pi/16,-pi/10];
numPts = numel(theta_1_known);
num_theta_2 = numel(theta_2_sol);
num_theta_1 = numel(theta_1_sol);

Note that there are potentially num_theta_1 solutions for each num_theta_2 solution.

Use the following sequence of operations to verify the solutions.

1 Loop over (theta_1_known,theta_2_known). For each point, compute the end positions
x_known, y_known, and z_known, which are then "known".
2 Loop over the solutions for θ2 corresponding to x_known and z_known. For each solution, check
to see if the corresponding condition cond_theta_2 is valid. If the condition is valid, compute
the corresponding numeric solution theta_2_derived.
3 Loop over the solutions for θ1 corresponding to x_known, z_known, and theta_2_derived. For
each solution, check to see if the corresponding condition cond_theta_1 is valid. If the
condition is valid, check to see if y_derived numerically matches y_known within relative and
absolute tolerances through the condition cond_yc. If this condition is valid, then compute
theta_1_derived.
4 Collect the results in a table T for display purposes.

T = table([],[],[],[],'VariableNames',{'theta_1_known','theta_2_known',...
'theta_1_derived','theta_2_derived'});

for ix1 = 1:numPts


xyz_known = double(xyzFunc(theta_1_known(ix1),theta_2_known(ix1)));
x_known = xyz_known(1);
y_known = xyz_known(2);
z_known = xyz_known(3);
for ix2 = 1:num_theta_2 % theta_2 loop
cond_theta_2 = subs(theta_2_conds(ix2),[CameraX,CameraZ,NeckOffsetZ,xc,zc],...
[CameraXValue,CameraZValue,NeckOffsetZValue,x_known,z_known]);
if isAlways(cond_theta_2) % if theta_2 is valid
theta_2_derived = subs(theta_2_sol(ix2),[CameraX,CameraZ,NeckOffsetZ,xc,zc],...
[CameraXValue,CameraZValue,NeckOffsetZValue,x_known,z_known]);
theta_2_derived = double(theta_2_derived);
for ix3 = 1:num_theta_1 % theta_1 loop
cond_theta_1 = subs(yc_theta_1_conds(ix3),[CameraX,CameraZ,NeckOffsetZ,theta_2,xc,zc],...
[CameraXValue,CameraZValue,NeckOffsetZValue,theta_2_derived,x_known,z_known]);
if isAlways(cond_theta_1) % if theta_1 is valid
y_derived = subs(yc_sol(ix3),[CameraX,CameraZ,NeckOffsetZ,theta_2,xc,zc],...
[CameraXValue,CameraZValue,NeckOffsetZValue,theta_2_derived,x_known,z_known]);
y_derived = double(y_derived);
cond_yc = abs(y_known - y_derived) < max(100*eps,1e-6*abs(y_known)); % check rounding
if isAlways(cond_yc) % if yc is valid
theta_1_derived = subs(theta_1_sol(ix3),[CameraX,CameraZ,NeckOffsetZ,theta_2,xc,zc],...
[CameraXValue,CameraZValue,NeckOffsetZValue,theta_2_derived,x_known,z_known]);
theta_1_derived = double(theta_1_derived);

3-167
3 Mathematics

T = vertcat(T,table(theta_1_known(ix1),theta_2_known(ix1),theta_1_derived,...
theta_2_derived,'VariableNames',T.Properties.VariableNames));
end
end
end
end
end
end
T

T=8×4 table
theta_1_known theta_2_known theta_1_derived theta_2_derived
_____________ _____________ _______________ _______________

0.7854 0.3927 0.7854 0.3927


0.7854 0.3927 -2.3562 -1.7346
0.5236 -0.2618 0.5236 -0.2618
0.5236 -0.2618 -2.618 -1.0801
0.3927 0.19635 0.3927 0.19635
0.3927 0.19635 -2.7489 -1.5383
0.31416 -0.31416 0.31416 -0.31416
0.31416 -0.31416 -2.8274 -1.0278

Observe that there are two possible solution pairs (theta_1_derived,theta_2_derived)


obtained using inverse kinematics for each pair of starting angles
(theta_1_known,theta_2_known). One set of the inverse solutions matches the starting angles.

References
1 SoftBank Robotics. NAO. https://www.aldebaran.com/en/nao.
2 Kofinas, N., E. Orfanoudakis, and M. G. Lagoudakis. "Complete Analytical Inverse Kinematics for
NAO." In 2013 13th International Conference on Autonomous Robot Systems. Lisbon, Portugal:
Robotica, 2013.
3 Kendricks, K. "Solving the Inverse Kinematic Robotics Problem: A Comparison Study of the
Denavit-Hartenberg Matrix and Groebner Basis Theory." Ph.D. Thesis. Auburn University,
Auburn, AL, 2007.

Helper Functions
function kinChain = getKinematicChain(link)
% This function returns the kinematic chain of the NAO humanoid robot
% represented using Denavit-Hartenberg (DH) parameters.
% The function uses as a reference the paper: Complete analytical inverse
% kinematics for NAO by Kofinas, N., Orfanoudakis, E., Lagoudakis, M.G.,
% 2013 13th International Conference on Autonomous Robot Systems
% (Robotica), Publication Year: 2013.
if nargin < 1
link = 'head';
end
% Notation: A, R, and T are the translation, rotation, and DH
% transformation matrices, respectively.
% Specify DH parameters for the desired end configuration.
syms r11 r12 r13 r21 r22 r23 r31 r32 r33 xc yc zc real;
R = [r11 r12 r13;r21 r22 r23;r31 r32 r33];
kinChain.T = [R,[xc;yc;zc];0,0,0,1];
switch link

3-168
Analytical Solutions of the Inverse Kinematics of a Humanoid Robot

case 'head' % Kinematic chain from torso (base) to head.


syms CameraX CameraZ NeckOffsetZ real;
% Translation from torso (base) to joint 0.
ABase0 = getA([0 0 NeckOffsetZ]);
% Translation from joint 2 to head.
A2Head = getA([CameraX 0 CameraZ]);
% Transformation from joint 0 to joint 1.
% theta_1 is the rotation angle corresponding to the 0-1 link.
syms theta_1 real;
alpha1 = 0; a1 = 0; d1 = 0;
T01 = getT(a1,alpha1,d1,theta_1);
% Transformation from joint 1 to joint 2.
% theta_2 is the rotation angle corresponding to the 1-2 link.
syms theta_2 real;
piby2 = str2sym('pi/2');
d2 = 0; a2 = 0; alpha2 = -piby2;
T12 = getT(a2,alpha2,d2,theta_2-piby2);
% Rx is the roll rotation.
Rx = getR('x',piby2);
% Ry is the pitch rotation.
Ry = getR('y',piby2);
% Capture the kinematic chain as a string.
% The transformation is from the base to the head.
kinChain.DHChain = 'ABase0*T01*T12*Rx*Ry*A2Head';
kinChain.ABase0 = ABase0;
kinChain.T01 = T01;
kinChain.T12 = T12;
kinChain.Rx = Rx;
kinChain.Ry = Ry;
kinChain.A2Head = A2Head;
case 'lefthand' % Kinematic chain from torso to left hand.
syms ShoulderOffsetY ElbowOffsetY ShoulderOffsetZ real;
ABase0 = getA([0 (ShoulderOffsetY+ElbowOffsetY) ShoulderOffsetZ]);
syms HandOffsetX LowerArmLength real;
AEnd4 = getA([(HandOffsetX+LowerArmLength) 0 0]);
piby2 = str2sym('pi/2');
syms theta_1 real;
alpha1 = -piby2; a1 = 0; d1 = 0;
T01 = getT(a1,alpha1,d1,theta_1);
syms theta_2 real;
d2 = 0; a2 = 0; alpha2 = piby2;
T12 = getT(a2,alpha2,d2,theta_2-piby2);
syms UpperArmLength theta_3 real;
d3 = UpperArmLength; a3 = 0; alpha3 = -piby2;
T32 = getT(a3,alpha3,d3,theta_3);
syms theta_4 real;
d4 = 0; a4 = 0; alpha4 = piby2;
T43 = getT(a4,alpha4,d4,theta_4);
Rz = getR('z',piby2);
kinChain.DHChain = 'ABase0*T01*T12*T32*T43*Rz*AEnd4';
kinChain.ABase0 = ABase0;
kinChain.T01 = T01;
kinChain.T12 = T12;
kinChain.T32 = T32;
kinChain.T43 = T43;
kinChain.Rz = Rz;
kinChain.AEnd4 = AEnd4;
end

3-169
3 Mathematics

end

function A = getA(vec)
% This function returns the translation matrix.
A = [1 0 0 vec(1);
0 1 0 vec(2);
0 0 1 vec(3);
0 0 0 1];
end

function R = getR(orientation,theta)
% This function returns the rotation matrix.
switch orientation
case 'x'
R = [1 0 0 0;
0 cos(theta) -sin(theta) 0;
0 sin(theta) cos(theta) 0
0 0 0 1];
case 'y'
R = [cos(theta) 0 sin(theta) 0;
0 1 0 0;
-sin(theta) 0 cos(theta) 0;
0 0 0 1];
case 'z'
R = [cos(theta) -sin(theta) 0 0;
sin(theta) cos(theta) 0 0;
0 0 1 0;
0 0 0 1];
end
end

function T = getT(a,alpha,d,theta)
% This function returns the Denavit-Hartenberg (DH) matrix.
T = [cos(theta),-sin(theta),0,a;
sin(theta)*cos(alpha),cos(theta)*cos(alpha),-sin(alpha),-sin(alpha)*d;
sin(theta)*sin(alpha),cos(theta)*sin(alpha),cos(alpha),cos(alpha)*d;
0,0,0,1];
end

See Also
Functions
simplify | solve | subs | double

3-170
Differentiation

Differentiation
To illustrate how to take derivatives using Symbolic Math Toolbox software, first create a symbolic
expression:
syms x
f = sin(5*x);

The command
diff(f)

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:
diff(diff(g))

ans =
-2*exp(x)*sin(x)

In this example, MATLAB software automatically simplifies the answer. However, in some cases,
MATLAB might not simplify an answer, in which case you can use the simplify command. For an
example of such simplification, see “More Examples” on page 3-173.

Note that to take the derivative of a constant, you must first define the constant as a symbolic
expression. For example, entering
c = sym('5');
diff(c)

3-171
3 Mathematics

returns

ans =
0

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

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-2. In the preceding example, diff(f) takes the
derivative of f with respect to t because the letter t is closer to x in the alphabet than the letter s is.
To determine the default variable that MATLAB differentiates with respect to, use symvar:

symvar(f,1)

ans =
t

Calculate the second derivative of f with respect to t:

diff(f,t,2)

3-172
Differentiation

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

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

diff(A)

3-173
3 Mathematics

returns
ans =
[ -a*sin(a*x), a*cos(a*x)]
[ -a*cos(a*x), -a*sin(a*x)]

You can also perform differentiation of a vector function with respect to a vector argument. Consider
the transformation from Cartesian coordinates (x, y, z) to spherical coordinates (r, λ, φ) as given by
x = rcosλcosφ, y = rcosλsinϕ, and z = rsinλ. Note that λ corresponds to elevation or latitude while φ
denotes azimuth or longitude.

To calculate the Jacobian matrix, J, of this transformation, use the jacobian function. The
mathematical notation for J is

∂(x, y, z)
J= .
∂ r, λ, φ

For the purposes of toolbox syntax, use l for λ and f for φ. The commands
syms r l f
x = r*cos(l)*cos(f);
y = r*cos(l)*sin(f);
z = r*sin(l);
J = jacobian([x; y; z], [r l f])

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

3-174
Differentiation

A table summarizing diff and jacobian follows.

Mathematical Operator MATLAB Command


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

d f
2 diff(f,b,2)
2
db
∂(r, t) J = jacobian([r; t],[u; v])
J=
∂(u, v)

See Also
diff | int | jacobian | gradient | curl | laplacian | functionalDerivative

External Websites
• Calculus Derivatives (MathWorks Teaching Resources)

3-175
3 Mathematics

Integration
If f is a symbolic expression, then

int(f)

attempts to find another symbolic expression, F, so that diff(F) = f. That is, int(f) returns the
indefinite integral or antiderivative of f (provided one exists in closed form). Similar to
differentiation,

int(f,v)

uses the symbolic object v as the variable of integration, rather than the variable determined by
symvar. See how int works by looking at this table.

Mathematical Operation MATLAB Command


log(x) if n = − 1 int(x^n) or int(x^n,x)
∫ xndx = xn + 1
otherwise.
n+1
π/2 int(sin(2*x), 0, pi/2) or int(sin(2*x), x, 0,

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

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

∫g(t)dt = sin(at + b)/a


∫ J (z)dz = − J (z)
1 0
int(besselj(1, z)) or int(besselj(1, 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.
• 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))

3-176
Integration

f int(f)
syms y int(f)
f = y^(-1);
ans =
log(y)
syms x n int(f)
f = n^x;
ans =
n^x/log(n)
syms a b theta int(f)
f = sin(a*theta+b);
ans =
-cos(b + a*theta)/a
syms u int(f)
f = 1/(1+u^2);
ans =
atan(u)
syms x int(f)
f = exp(-x^2);
ans =
(pi^(1/2)*erf(x))/2

In the last example, exp(-x^2), there is no formula for the integral involving standard calculus
expressions, such as trigonometric and exponential functions. In this case, MATLAB returns an
answer in terms of the error function erf.

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

Definite integration is also possible.

Definite Integral Command


int(f, a, b)

b
f (x)dx
a

int(f, v, a, b)

b
f (v)dv
a

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

3-177
3 Mathematics

f a, b int(f, a, b)
syms x a = 0; int(f, a, b)
f = exp(-x^2); b = inf;
ans =
pi^(1/2)/2
syms z a = 0; int(f, a, b)
f = besselj(1,z)^2; b = 1;
ans =
hypergeom([3/2, 3/2],...
[2, 5/2, 3], -1)/12

For the Bessel function (besselj) example, it is possible to compute a numerical approximation to
the value of the integral, using the double function. The commands

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

return

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

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.

syms x
a = sym(1/2);
f = exp(-a*x^2);
fplot(f)

3-178
Integration

However, if you try to calculate the integral


−∞
∫e −ax2dx

without assigning a value to a, MATLAB assumes that a represents a complex number, and therefore
returns a piecewise answer that depends on the argument of a. If you are only interested in the case
when a is a positive real number, use assume to set an assumption on a:
syms a
assume(a > 0)

Now you can calculate the preceding integral using the commands
syms x
f = exp(-a*x^2);
int(f, x, -inf, inf)

This returns
ans =
pi^(1/2)/a^(1/2)

Integration with Complex Parameters


To calculate the integral

3-179
3 Mathematics

−∞
∫a 1
2 + x2
dx

for complex values of a, enter

syms a x
f = 1/(a^2 + x^2);
F = int(f, x, -inf, inf)

Use syms to clear all the assumptions on variables. For more information about symbolic variables
and assumptions on them, see “Use Assumptions on Symbolic Variables” on page 1-41.

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 Re(z) < 0


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

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.

3-180
Integration

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.


usingIntegral =
NaN

usingVpaintegral =
0.688424

For more information, see vpaintegral.

See Also
int | diff | vpaintegral

External Websites
• Calculus Integrals (MathWorks Teaching Resources)

3-181
3 Mathematics

Taylor Series
The statements

syms x
f = 1/(5 + 4*cos(x));
T = taylor(f, 'Order', 8)

return

T =
(49*x^6)/131220 + (5*x^4)/1458 + (2*x^2)/81 + 1/9

which is all the terms up to, but not including, order eight in the Taylor series for f(x):

∞ (n)
nf (a)
∑ (x − a)
n!
.
n=0

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

These commands

syms x
g = exp(x*sin(x));
t = taylor(g, 'ExpansionPoint', 2, 'Order', 12);

generate the first 12 nonzero terms of the Taylor series for g about x = 2.

t is a large expression; enter

size(char(t))

ans =
1 99791

to find that t has about 100,000 characters in its printed form. In order to proceed with using t, first
simplify its presentation:

t = simplify(t);
size(char(t))

ans =
1 6988

Next, plot these functions together to see how well this Taylor approximation compares to the actual
function g:

xd = 1:0.05:3;
yd = subs(g,x,xd);
fplot(t, [1, 3])
hold on
plot(xd, yd, 'r-.')
title('Taylor approximation vs. actual function')
legend('Taylor','Function')

3-182
Taylor Series

Special thanks is given to Professor Gunnar Bäckstrøm of UMEA in Sweden for this example.

3-183
3 Mathematics

Fourier and Inverse Fourier Transforms


This page shows the workflow for Fourier and inverse Fourier transforms in Symbolic Math Toolbox.
For simple examples, see fourier and ifourier. Here, the workflow for Fourier transforms is
demonstrated by calculating the deflection of a beam due to a force. The associated differential
equation is solved by the Fourier transform.

Fourier Transform Definition


The Fourier transform of f(x) with respect to x at w is

F(w) = ∫ f (x)e
−∞
−iwxdx .

The inverse Fourier transform is



f (x) =
1
2π ∫ F(w)e
−∞
iwxdw .

Concept: Using Symbolic Workflows


Symbolic workflows keep calculations in the natural symbolic form instead of numeric form. This
approach helps you understand the properties of your solution and use exact symbolic values. You
substitute numbers in place of symbolic variables only when you require a numeric result or you
cannot continue symbolically. For details, see “Choose Numeric or Symbolic Arithmetic” on page 2-
32. Typically, the steps are:

1 Declare equations.
2 Solve equations.
3 Substitute values.
4 Plot results.
5 Analyze results.

Calculate Beam Deflection Using Fourier Transform


Define Equations

Fourier transform can be used to solve ordinary and partial differential equations. For example, you
can model the deflection of an infinitely long beam resting on an elastic foundation under a point
force. A corresponding real-world example is railway tracks on a foundation. The railway tracks are
the infinitely long beam while the foundation is elastic.

3-184