Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 45 ยท Numerical Methods

Symbolic Math

Do algebra and calculus with exact formulas in MATLAB and Octave: syms, solve, diff, int, simplify, limits and dsolve, with SymPy stand-ins you can run.

Everything so far has worked with numbers. Symbolic math works with formulas. Ask a numeric program for the derivative of x^2 * sin(x) at one point and you get one approximate number; ask a symbolic program and you get the formula 2*x*sin(x) + x^2*cos(x), exact for every x. Symbolic tools solve equations exactly, simplify expressions, integrate in closed form and keep fractions as fractions instead of rounding them.

In MATLAB this lives in the Symbolic Math Toolbox, a paid add-on. Octave has the symbolic package (pkg load symbolic), which uses the Python library SymPy behind the scenes, so it needs Python and SymPy installed. MATLAB and Octave are not available in your browser here, so the MATLAB code is read-only. The runnable stand-ins use SymPy directly, which is close to what Octave's package does and very close to the MATLAB commands in spirit. Where names differ, the comments say so.

Numbers or formulas?

Numeric Fast, approximate, works on anything.
Symbolic Exact, slower, needs a formula.

Symbolic answers can often be turned into numbers afterwards.

1 / 2

Creating symbolic variables

A symbolic variable is declared with syms. After that, any expression built from it stays a formula instead of being evaluated.

MATLAB
syms x y
f = x^2 - 5*x + 6        % a symbolic expression, not a number
g = sin(x)^2 + cos(x)^2  % stays as written until you simplify it

Numbers that you want to keep exact must be wrapped: sym(1)/3 is the exact fraction 1/3, while plain 1/3 is already the rounded double 0.3333. This is a classic trap. By default sym(0.1) guesses a nearby simple fraction and gives 1/10, but that guess is only a guess: the double itself is slightly off. Write sym(1)/10 or sym('1/10') when exactness matters. Constants such as pi should likewise be passed through sym (as in sym(pi)), because the plain pi is a rounded double. You can also restrict a variable: syms x real or syms n positive lets the solver make stronger conclusions.

Solving equations with solve

solve(eqn, var) finds exact solutions. Write equations with ==, or give an expression that should equal zero.

MATLAB
syms x
solve(x^2 - 5*x + 6 == 0, x)      % [2; 3]
solve(x^2 + 1 == 0, x)            % [-1i; 1i], complex roots are found too

syms a b c
solve(a*x^2 + b*x + c == 0, x)    % the quadratic formula, with symbols

syms x y
S = solve([x + y == 3, x - y == 1], [x, y])   % a system: S.x = 2, S.y = 1

The answer for a system comes back as a structure with one field per unknown. If an equation has no closed-form solution, MATLAB returns an unevaluated or partial answer along with a warning; then use the numeric vpasolve or fzero from Solving Equations and Optimization.

Python Solve equations exactly with SymPy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Calculus: diff, int, limit

diff(f, x) differentiates; add a number for higher derivatives, as in diff(f, x, 2). int(f, x) integrates without adding a constant of integration; int(f, x, a, b) computes a definite integral. limit and taylor complete the picture.

MATLAB
syms x
f = x^2 * sin(x);
df = diff(f, x)                 % 2*x*sin(x) + x^2*cos(x)
d2 = diff(f, x, 2)              % second derivative
F  = int(x^2, x)                % x^3/3
A  = int(x^2, x, 0, 3)          % 9
G  = int(exp(-x^2), x, -Inf, Inf)   % pi^(1/2)
L  = limit(sin(x)/x, x, 0)      % 1
T  = taylor(exp(x), x, 'Order', 5)  % 1 + x + x^2/2 + x^3/6 + x^4/24

Not every integral has a formula in elementary functions. If int cannot find one, it returns the integral unevaluated, and you switch to the numeric integral from Integration, Differentiation and ODEs. A symbolic derivative, by contrast, almost always exists.

Python Derivatives, integrals and limits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Simplifying, expanding and factoring

Symbolic results are not always in the shape you want. A small family of functions rewrites an expression:

MATLAB
syms x
expand((x + 1)^3)               % x^3 + 3*x^2 + 3*x + 1
factor(x^3 - x)                 % x*(x - 1)*(x + 1)
simplify(sin(x)^2 + cos(x)^2)   % 1
collect(x*(x + 2) + 3*x, x)     % x^2 + 5*x

simplify tries several rewriting strategies and returns the shortest result it finds, but "simplest" is a matter of taste and some identities need hints: simplify(f, 'Steps', 50) searches longer, and rewrite(f, 'exp') rewrites trigonometric functions as exponentials. Two expressions that look different may still be equal; test with simplify(a - b) == 0 instead of comparing text.

From symbols back to numbers

At some point you want numbers or a plot. subs replaces a symbol with a value, double converts an exact result to an ordinary floating-point number, and vpa(expr, digits) gives many digits. To use a symbolic expression in fast numeric code (for example in plot), turn it into an ordinary function handle with matlabFunction.

MATLAB
syms x
f = x^2 * sin(x);
subs(f, x, 2)                   % 4*sin(2), still exact
double(subs(f, x, 2))           % 3.6372
vpa(sym(pi), 30)                % 3.14159265358979323846264338328
h = matlabFunction(f);          % ordinary handle: h(2) is 3.6372
fplot(f, [0 10])                % quick plot straight from the symbol

Symbolic math can solve a differential equation exactly when a formula exists. dsolve is the symbolic counterpart of ode45:

MATLAB
syms y(t)
sol = dsolve(diff(y, t) == -0.5*y, y(0) == 10)   % 10*exp(-t/2)
Python From a formula to numbers and a plot

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Toolbox, package and cost

The command names above are the same in MATLAB and Octave for the basics (syms, solve, diff, int, simplify, subs, double, limit), but the engines differ. MATLAB's Symbolic Math Toolbox uses its own engine (MuPAD historically) and needs a license. Octave's symbolic package forwards every command to SymPy through Python, so the answers match the SymPy stand-ins above and failures often show up as Python error messages. A few MATLAB features, such as matlabFunction and some dsolve forms, are missing or spelled differently in Octave; test before you rely on them. In Octave, load the package at the top of the script:

MATLAB
pkg load symbolic
syms x
diff(sin(x)^2, x)

If you do not need exact formulas, numerical methods are usually faster and work on problems that have no closed form. Use symbolic math to derive a formula once, check it by hand, then turn it into a numeric function with matlabFunction and run it on lots of data.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main difference between diff on a vector and diff(f, x) on a symbolic expression?

    diff(v) subtracts neighbouring elements. With a symbolic expression and a variable, diff returns the exact derivative.
  2. 2. Which expression is guaranteed to hold the exact fraction one tenth?

    Plain 0.1 and 1/10 are rounded doubles, and double() rounds too. sym(1)/10 (or sym('1/10')) keeps the exact fraction.
  3. 3. How do you get a result like 4*sin(2) as an ordinary number?

    double converts a symbolic result to a floating-point number. vpa gives it with more digits.
  4. 4. What does int(f, x) return for an indefinite integral?

    int returns one antiderivative and leaves out + C. Supply limits, as in int(f, x, a, b), for a definite integral.
  5. 5. In Octave, what must you do before using syms?

    Octave's symbolic functionality is a package that uses SymPy via Python. Install it once and load it with pkg load symbolic.

Summary

  • syms creates symbolic variables, and expressions built from them stay exact formulas.
  • solve finds exact roots and solves systems; a system returns a structure with one field per unknown.
  • diff, int, limit and taylor do calculus; int returns an antiderivative without + C.
  • simplify, expand, factor and collect reshape an expression; test equality with simplify(a - b) == 0.
  • subs, double, vpa and matlabFunction bring symbolic results back to numbers, handles and plots.
  • MATLAB needs the Symbolic Math Toolbox; Octave uses the symbolic package, which runs SymPy through Python.

Next: Image Processing Basics.