Symbolic Math
Everything in the previous lessons was numeric: numbers in, numbers out, with rounding errors around 10⁻¹⁶. Symbolic computation manipulates formulas instead, the way you would on paper: differentiate x³·sin(x) to get x³·cos(x) + 3x²·sin(x), integrate exactly, solve equations in closed form, simplify expressions. In MATLAB this is the job of the Symbolic Math Toolbox, an add-on product. GNU Octave offers a free alternative, the symbolic package, which uses Python's SymPy behind the scenes.
Note: The toolbox isn't part of base MATLAB and the playground's Octave doesn't load the
symbolicpackage, so the symbolic examples on this page are not runnable; they show MATLAB's output. Each topic is followed by a runnable numeric cross-check that confirms the symbolic answer with base functions, a good habit in any case.
| Task | Symbolic (toolbox) | Numeric equivalent (base) |
|---|---|---|
| Declare variables | syms x y |
— |
| Derivative | diff(f, x) |
finite differences, gradient, polyder |
| Integral | int(f, x), int(f, x, a, b) |
integral, trapz, polyint |
| Solve equations | solve(eq, x) |
fzero, roots, \ |
| Simplify / expand | simplify, expand, factor |
conv for polynomials |
| Substitute | subs(f, x, 2) |
evaluate a function handle |
| Limits, series | limit, taylor |
evaluate near the point |
| Exact digits | vpa(expr, 50) |
rats, format long |
| ODE in closed form | dsolve |
ode45 |
| Formula → fast code | matlabFunction(f) |
write the anonymous function |
Symbolic variables and expressions
syms creates symbolic variables. Any expression built from them is symbolic too, and MATLAB displays it as a formula:
syms x
f = x^3 * sin(x)
class(f)MATLAB output:
f =
x^3*sin(x)
ans =
'sym'Numbers become exact when they enter a symbolic expression: sym(1)/3 stays one third instead of 0.3333, and sqrt(sym(2)) stays √2. Be careful with sym(0.1): the double 0.1 is already rounded, and sym converts it to the nearest simple fraction, 1/10, which is usually what you meant.
Derivatives
syms x
diff(x^3 * sin(x))
syms a
diff(exp(a*x), a) % differentiate with respect to aMATLAB output:
ans =
x^3*cos(x) + 3*x^2*sin(x)
ans =
x*exp(a*x)A numeric cross-check: evaluate the symbolic derivative at a point and compare with a central difference (see Numerical Differentiation):
f = @(x) x.^3 .* sin(x);
df = @(x) x.^3 .* cos(x) + 3*x.^2 .* sin(x); % the toolbox's answer
x0 = 1.3; h = 1e-5;
numeric = (f(x0 + h) - f(x0 - h)) / (2*h);
fprintf('symbolic formula: %.8f\n', df(x0));
fprintf('central diff: %.8f\n', numeric);
fprintf('agree within 1e-8: %d\n', abs(numeric - df(x0)) < 1e-8);symbolic formula: 5.47293493
central diff: 5.47293493
agree within 1e-8: 1
Integrals
int(f, x) returns an antiderivative (without the constant); int(f, x, a, b) returns the exact definite integral, infinite limits included:
syms x
int(x * exp(x), x)
int(1 / (1 + x^2), x, 0, 1)
int(exp(-x^2), x, -inf, inf)MATLAB output:
ans =
exp(x)*(x - 1)
ans =
pi/4
ans =
pi^(1/2)The numeric check uses integral, and the antiderivative is checked with the fundamental theorem of calculus, F(b) − F(a):
F = @(x) exp(x) .* (x - 1); % symbolic antiderivative of x*e^x
fprintf('F(2) - F(0) = %.10f\n', F(2) - F(0));
fprintf('integral = %.10f\n', integral(@(x) x .* exp(x), 0, 2));
fprintf('pi/4 = %.10f vs %.10f\n', pi/4, integral(@(x) 1 ./ (1 + x.^2), 0, 1));
fprintf('sqrt(pi) = %.10f vs %.10f\n', sqrt(pi), integral(@(x) exp(-x.^2), -Inf, Inf));F(2) - F(0) = 8.3890560989
integral = 8.3890560989
pi/4 = 0.7853981634 vs 0.7853981634
sqrt(pi) = 1.7724538509 vs 1.7724538509
Solving equations
solve returns exact solutions, as a column when there are several. For systems, list the equations and the unknowns:
syms x
solve(x^2 - 2*x - 3 == 0, x)
solve(x^2 + 1 == 0, x)
syms a b
[sa, sb] = solve([a + b == 10, a - b == 2], [a, b])MATLAB output:
ans =
-1
3
ans =
-1i
1i
sa =
6
sb =
4Numerically, polynomial roots come from roots (in its own order, not necessarily sorted), other equations from fzero, and linear systems from backslash:
disp(roots([1 -2 -3])') % x^2 - 2x - 3
disp(roots([1 0 1]).') % x^2 + 1: use .' to keep the signs of the imaginary parts
sol = [1 1; 1 -1] \ [10; 2];
fprintf('a = %g, b = %g\n', sol);
fprintf('fzero on x^2 - 2x - 3 near 2: %g\n', fzero(@(x) x.^2 - 2*x - 3, 2)); 3 -1
0 + 1i 0 - 1i
a = 6, b = 4
fzero on x^2 - 2x - 3 near 2: 3
Simplify, expand, substitute
syms x
simplify(sin(x)^2 + cos(x)^2)
simplify((x^2 - 1) / (x - 1))
expand((x + 1)^3)
f = x^3 * sin(x);
subs(f, x, pi/2)MATLAB output:
ans =
1
ans =
x + 1
ans =
x^3 + 3*x^2 + 3*x + 1
ans =
pi^3/8For polynomials, base MATLAB already does exact algebra on coefficient vectors: conv multiplies, deconv divides, polyder and polyint differentiate and integrate:
p = conv(conv([1 1], [1 1]), [1 1]); % (x + 1)^3
fprintf('expand((x+1)^3): %s\n', mat2str(p));
[q, r] = deconv([1 0 -1], [1 -1]); % (x^2 - 1) / (x - 1)
fprintf('quotient %s, remainder %s\n', mat2str(q), mat2str(r));
fprintf('d/dx of x^3 + 3x^2 + 3x + 1: %s\n', mat2str(polyder(p)));
fprintf('antiderivative of x^2 + 1: %s\n', strjoin(cellfun(@(c) strtrim(rats(c)), num2cell(polyint([1 0 1])), 'UniformOutput', false), ' '));
fprintf('subs check: (pi/2)^3*sin(pi/2) = %.6f, pi^3/8 = %.6f\n', (pi/2)^3 * sin(pi/2), pi^3/8);expand((x+1)^3): [1 3 3 1]
quotient [1 1], remainder [0 0 0]
d/dx of x^3 + 3x^2 + 3x + 1: [3 6 3]
antiderivative of x^2 + 1: 1/3 0 1 0
subs check: (pi/2)^3*sin(pi/2) = 3.875785, pi^3/8 = 3.875785
rats turns a double into the closest simple fraction as text, a handy way to recognise exact values in numeric results.
Limits and Taylor series
syms x
limit(sin(x) / x, x, 0)
limit((1 + 1/x)^x, x, inf)
taylor(exp(x), x, 'Order', 4)MATLAB output:
ans =
1
ans =
exp(1)
ans =
x^3/6 + x^2/2 + x + 1The numeric counterparts: evaluate close to the limit point, and measure the error of the Taylor polynomial (the next term, x⁴/24, predicts it well for small x):
x = 10.^-(1:4);
fprintf('sin(x)/x at x = %.0e: %.10f\n', [x; sin(x) ./ x]);
n = 1e6;
fprintf('(1 + 1/n)^n for n = 1e6: %.6f, e = %.6f\n', (1 + 1/n)^n, exp(1));
p = [1/6 1/2 1 1]; % x^3/6 + x^2/2 + x + 1
for x0 = [0.5 0.1]
fprintf('x = %.1f: Taylor error %.2e, next term x^4/24 = %.2e\n', ...
x0, exp(x0) - polyval(p, x0), x0^4 / 24);
endsin(x)/x at x = 1e-01: 0.9983341665
sin(x)/x at x = 1e-02: 0.9999833334
sin(x)/x at x = 1e-03: 0.9999998333
sin(x)/x at x = 1e-04: 0.9999999983
(1 + 1/n)^n for n = 1e6: 2.718280, e = 2.718282
x = 0.5: Taylor error 2.89e-03, next term x^4/24 = 2.60e-03
x = 0.1: Taylor error 4.25e-06, next term x^4/24 = 4.17e-06
Exact digits with vpa
vpa (variable-precision arithmetic) evaluates an expression to as many digits as you ask:
vpa(pi, 30)
vpa(sqrt(sym(2)), 25)MATLAB output:
ans =
3.14159265358979323846264338328
ans =
1.414213562373095048801689Doubles carry about 16 significant digits; format long or fprintf('%.15f') shows all of them, and anything beyond is rounding noise. If you need more digits without the toolbox, Octave's symbolic package also has vpa.
Differential equations with dsolve
syms y(t)
ySol = dsolve(diff(y, t) == -0.5 * y, y(0) == 4)MATLAB output:
ySol =
4*exp(-t/2)The closed form checks ode45 exactly as in Integration & ODEs:
opts = odeset('RelTol', 1e-9, 'AbsTol', 1e-9);
[t, y] = ode45(@(t, y) -0.5 * y, 0:2:6, 4, opts);
fprintf('t = %d: ode45 %.6f, dsolve formula %.6f\n', [t'; y'; 4 * exp(-t' / 2)]);t = 0: ode45 4.000000, dsolve formula 4.000000
t = 2: ode45 1.471518, dsolve formula 1.471518
t = 4: ode45 0.541341, dsolve formula 0.541341
t = 6: ode45 0.199148, dsolve formula 0.199148
From formula to fast numeric code: matlabFunction
Symbolic expressions are slow to evaluate in loops. matlabFunction converts one into an ordinary, vectorised function handle (or writes it to a .m file with 'File', 'name'):
syms x
g = matlabFunction(diff(x^3 * sin(x)))
g(1.3)MATLAB output:
g =
function_handle with value:
@(x)x.^3.*cos(x)+x.^2.*sin(x).*3.0
ans =
5.4729The exact arrangement of the generated code (term order, 3.0 factors) varies between releases. The typical workflow is: derive with symbols, convert with matlabFunction, compute with numbers. Without the toolbox, write the handle yourself with element-wise operators, as in the first cross-check above:
g = @(x) x.^3 .* cos(x) + 3 * x.^2 .* sin(x);
fprintf('g(1.3) = %.4f\n', g(1.3));
fprintf('vectorised: %s\n', mat2str(round(g([0 0.5 1]) * 1e4) / 1e4));g(1.3) = 5.4729
vectorised: [0 0.4693 3.0647]
Octave's symbolic package
In a desktop Octave you can install and use the package like this (it needs Python with SymPy):
pkg install -forge symbolic % once
pkg load symbolic % in each session
syms x
diff(x^3 * sin(x))Most of the commands on this page (syms, diff, int, solve, simplify, subs, limit, taylor, vpa, dsolve, matlabFunction) exist there with the same names. The display is different (a (sym) header and pretty-printed formulas), and results may be arranged differently, for example a different order of terms, while being mathematically equal.
Learn more: the numeric tools used for the cross-checks are covered in Numerical Differentiation, Integration & ODEs, Roots & Minimization and Polynomials; other add-ons are surveyed in Toolboxes.
Test yourself
What does int(f, x, a, b) return in the Symbolic Math Toolbox?
- A numeric approximation with rounding error
- The exact definite integral as a symbolic expression
- A function handle
- The antiderivative without limits
Which function converts a symbolic expression into a fast, vectorised function handle?
vpasubsmatlabFunctionsimplify
Without any toolbox, how can you differentiate the polynomial x³ + 3x² + 3x + 1 exactly?
diff([1 3 3 1])polyder([1 3 3 1])gradient([1 3 3 1])- It is impossible