Matlab Use Symbolic Math
MathWorksOfficialCreated by MathWorks
- Skill
- Tool integration
- Science and research
- BSD-2-Clause
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides the essential syntax, best practices, and workflow patterns for using the MATLAB Symbolic Math Toolbox. It covers the creation of symbolic variables, analytical calculus, algebraic equation solving, matrix-level symbolic operations, and integration with other toolboxes like PDE Toolbox and Control System Toolbox. The skill emphasizes modern conventions, such as using syms for variable creation, proper assumption management, and leveraging dedicated functions for vector calculus and coefficient extraction to ensure accurate and efficient symbolic computation.
What it does
- Generates symbolic variables, expressions, and functions for analytical computation.
- Performs symbolic differentiation, integration, limits, and summation.
- Solves algebraic and differential equations analytically or numerically.
- Extracts PDE coefficients for use in PDE Toolbox models.
- Converts symbolic expressions into numeric MATLAB functions or C code.
- Manages physical units and constants within symbolic computations.
When to use it
- When you need exact analytical solutions rather than numeric approximations.
- When performing symbolic calculus, such as finding derivatives or integrals.
- When deriving transfer functions or state-space models from differential equations.
- When working with symbolic matrices or performing symbolic linear algebra.
- When you need to convert symbolic mathematical models into executable C code or MATLAB functions.
Advantages
- Ensures correct syntax by avoiding deprecated string-based function calls.
- Provides standardized patterns for complex tasks like PDE coefficient extraction.
- Promotes efficient assumption management to prevent stale symbolic engine states.
- Reduces errors by automating the conversion between symbolic and numeric domains.
- Offers clear guidance on when to use specific symbolic functions versus standard numeric ones.
Usage examples
- “Solve the quadratic equation x^2 + 5x + 6 = 0 symbolically.”
- The agent will generate: syms x; sol = solve(x^2 + 5*x + 6 == 0, x).
- “How do I compute the gradient of f = x^2*y + y^3?”
- The agent will provide the code: syms x y; f = x^2*y + y^3; grad = gradient(f, [x, y]).
- “Convert a symbolic expression to a numeric function handle for a parametric sweep.”
- The agent will suggest: f_func = matlabFunction(f, 'Vars', {x, y}).
- “How do I clear assumptions on a symbolic variable x?”
- The agent will advise: syms x or assume(x, 'clear').
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/matlab/matlab-use-symbolic-math/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip matlab-use-symbolic-math.zip -d .agents/skills
Documentation by MathWorks
MATLAB Symbolic Math Toolbox
This skill provides guidelines, correct syntax, and common patterns for generating MATLAB® code that uses Symbolic Math Toolbox.
When to Use This Skill
Creating or manipulating symbolic variables, expressions, and functions
Performing symbolic differentiation, integration, limits, or summation
Simplifying, factoring, expanding, or collecting symbolic expressions
Computing Laplace, Fourier, or Z-transforms and their inverses
Deriving transfer functions or state-space equations from differential equations
Displaying or plotting symbolic expressions
Using variable precision arithmetic (VPA)
Generating MATLAB functions, Simulink function blocks, Simscape equations, and C code from symbolic expressions
Extracting PDE coefficients for use with PDE Toolbox
Converting symbolic expressions to C code or standalone executables
Matrix-level (atomic, textbook-style) symbolic linear algebra with
symmatrixUsing physical units or constants in symbolic computations with
symunitRewriting or combining algebraic expressions into specific forms
When NOT to Use This Skill
Purely numeric computation with no symbolic variables (use standard MATLAB numeric functions)
Statistics, machine learning, or data analysis on numeric datasets
Image processing, signal processing, or other toolbox-specific workflows that don't involve symbolic math
String manipulation or file I/O operations
When the user explicitly asks for numeric approximations only (use
doubleor numeric solvers directly)PDE Toolbox mesh generation, boundary conditions, or solving (downstream of coefficient extraction)
Numeric linear algebra (use standard MATLAB matrix operations)
Critical Rules
1. NEVER Pass Strings or Character Vectors to Symbolic Functions
WRONG (deprecated — warns today, errors in a future release; the single = in solve errors now):
solve('x^2 + 2*x - 3 = 0')
dsolve('Dy = -a*y')CORRECT:
syms x
solve(x^2 + 2*x - 3 == 0, x)
syms y(t) a
dsolve(diff(y,t) == -a*y)2. Use syms for Interactive Work, sym for Functions and Constants
syms x y z— Creates fresh symbolic variables and clears any prior assumptions. Use for interactive scripts and Live Scripts.x = sym('x')— Refers to a symbolic variable. Inherits existing assumptions. Required inside MATLAB functions (not scripts) becausesymsdynamically creates workspace variables.sym(pi)— Converts numeric to exact symbolic. Use for symbolic constants.sym('pi')— Creates a symbolic variable namedpi, NOT the mathematical constant π. This is a common source of confusion.
WRONG:
% Inside a function:
function result = myFunc()
syms x % Error or unreliable in compiled/nested functions
result = x^2;
end
% Creating symbolic constant pi:
p = sym('pi'); % Creates variable named "pi", NOT the constantCORRECT:
% Inside a function:
function result = myFunc()
x = sym('x'); % Use sym inside functions
result = x^2;
end
% Creating symbolic constant pi:
p = sym(pi); % Converts numeric pi to exact symbolic π3. Assumption Management
Assumptions persist in the symbolic engine even after clear. This is a frequent source of subtle bugs.
% Setting assumptions
syms x real % x is real (clears prior assumptions)
syms n positive integer % n is a positive integer
assume(x > 0) % x is positive (REPLACES all prior assumptions on x)
assumeAlso(x < 10) % ADDS assumption: 0 < x < 10
% Checking assumptions
assumptions(x) % Shows assumptions on x
assumptions % Shows ALL assumptions in workspace
% Clearing assumptions — two correct ways:
syms x % Recreate with syms: clears assumptions
assume(x, 'clear') % Explicitly clear assumptions on x
reset(symengine) % Nuclear option: clears EVERYTHINGBest Practice: Use syms x to clear assumptions (it resets the variable fresh). Use assume(x, 'clear') when you need to reset a specific variable mid-script. The MATLAB clear command only removes workspace variables — it has no effect on the symbolic engine's assumption store.
4. subs Does Not Modify In-Place
The subs function returns a new expression. It does NOT modify the original.
WRONG:
syms x
f = x^2 + 3*x;
subs(f, x, 2); % Result is discarded!
disp(f) % Still x^2 + 3*xCORRECT:
syms x
f = x^2 + 3*x;
f_val = subs(f, x, 2); % Assign the result
% or: f = subs(f, x, 2); % Overwrite f5. Do Not Wrap Numeric Literals in sym() Inside Symbolic Expressions
AI tools frequently over-wrap every numeric literal in sym().
When any operand in an arithmetic expression is symbolic, MATLAB automatically promotes all numeric literals in that expression to symbolic. Wrapping literals in sym() adds clutter and can cause errors.
When you DO need sym(): Only when creating a standalone symbolic number with NO symbolic variables present in the expression.
% No symbolic variable involved — sym() IS needed:
half = sym(1/2); % Exact 1/2, not 0.5 double
half = sym(1)/2; % Exact 1/2, declaring sym(1) promotes all numeric literals to symbolic
piExact = sym(pi); % Exact π, not 3.14159...
% Symbolic variable already present — sym() is NOT needed:
syms x
f = x/2 + 1/3; % Automatically exact: x/2 + 1/3
g = exp(-x^2/2) / sqrt(2*pi); % All literals promoted by xCore Workflow Patterns
Creating Variables and Expressions
% Multiple variables at once
syms a b c
% Variables with assumptions
syms a b c real
syms n positive integer
syms x
assume(x > 2)
% Symbolic matrices with auto-generated elements
syms A [3 3] % Creates A = [A1_1 A1_2 A1_3; ...]
% Symbolic vector
syms a [1 3] % Creates row vector a = [a1 a2 a3]
% Symbolic numbers (exact)
a = sym(1/3); % Exact 1/3
piSym = sym(pi); % Exact πSolving Algebraic Equations
syms x y
% Single equation
sol = solve(x^2 - 5*x + 6 == 0, x); % Returns [2; 3]
% System of equations
[solx, soly] = solve(x + y == 10, x - y == 2, x, y);
% Return all solutions along with the parameters in the solution and the conditions on the solution
[sol, params, conds] = solve(sin(x) == 0, x, 'ReturnConditions', true);
% Numerical solutions when analytic not possible
solN = vpasolve(x^5 - 3*x^4 + x - 1 == 0, x);Calculus
syms x t n
% Differentiation
diff(sin(x), x) % cos(x)
diff(x^3, x, 2) % 6*x (second derivative)
% Integration
int(x^2, x) % x^3/3 (indefinite)
int(x^2, x, 0, 1) % 1/3 (definite, from 0 to 1)
% Limits
limit(sin(x)/x, x, 0) % 1
limit(1/x, x, 0, 'right') % Inf
limit(1/x, x, 0, 'left') % -Inf
% Summation
symsum(1/n^2, n, 1, Inf) % pi^2/6
% Taylor series
taylor(exp(x), x, 0, 'Order', 6) % x^5/120 + x^4/24 + x^3/6 + x^2/2 + x + 1
% Gradient, Hessian, Jacobian, Laplacian, Divergence, Curl — use dedicated functions, not manual diff
syms x y z
f = x^2*y + y^3;
gradient(f, [x, y]) % [2*x*y; x^2 + 3*y^2]
hessian(f, [x, y]) % [2*y, 2*x; 2*x, 6*y]
laplacian(f, [x, y]) % 2*y + 6*y = 8*y (trace of Hessian)
g = [x^2*y; 5*x + sin(y)];
jacobian(g, [x, y]) % [2*x*y, x^2; 5, cos(y)]
V = [x^2*y; y^2*z; z^2*x];
divergence(V, [x, y, z]) % 2*x*y + 2*y*z + 2*z*x
curl(V, [x, y, z]) % [-y^2; -z^2; -x^2]Matrix Operations
syms a b c d
A = [a b; c d];
% Determinant
det(A) % a*d - b*c
% Inverse
inv(A) % Symbolic inverse
% Eigenvalues and eigenvectors
[V, D] = eig(A)
% Characteristic polynomial
charpoly = det(A - sym('lambda')*eye(2))
% Jacobian of a coordinate change
syms r(t) phi(t) theta(t); % polar coordinates that are a function of time
R = [r*sin(phi)*cos(theta), r*sin(phi)*sin(theta), r*cos(phi)] % coordinate transform from spherical to Cartesian
jacobian(R,[r,phi,theta])Application Patterns
For detailed workflows, see the reference files below. Read the relevant file when the user's task matches:
references/simplification-and-polynomials.md—simplify/expand/factor/collect/partfrac/rewrite,sym2polyvscoeffs, variable-precision arithmetic (VPA)references/control-systems.md— Deriving transfer functions from ODEs,tf/ssderivation from first principles, Laplace/Fourier/Z-transform, Bode plots from symbolic modelsreferences/ode-solving.md—dsolvesyntax,odeToVectorField+matlabFunction+ode45pipeline, parameterized ODE solvingreferences/plotting-and-display.md—fplot/fsurf/fmesh/fcontour/fimplicit/fanimatorfamily,disp()vspretty(), symbolic plotting best practicesreferences/matlabFunction-patterns.md— Converting symbolic expressions to function handles/files,'Vars'/'Optimize'/'File'options, piecewise handling, critical error-prevention rulesreferences/extract-pde-coefficients.md—pdeCoefficientsworkflow for extracting PDE Toolbox coefficients,pdeCoefficientsToDouble, systems of PDEsreferences/symbolic-to-c-code.md—matlabFunction(..., 'File', ...)+codegenpipeline for C/C++ generation, when to useccodevs full pipelinereferences/symmatrix-workflow.md— Atomic symbolic matrices withsymmatrix,symmatrix2symconversion,symfunmatrix, supported vs unsupported operationsreferences/symunit-workflow.md— Physical units/constants viasymunit,newUnit/removeUnit, correct constant names (u.hc,u.c_0), unit conversionreferences/rewrite-combine-expressions.md— Valid targets forrewriteandcombine,IgnoreAnalyticConstraintsfor log combination, when to use which function
Common Mistakes and Fixes
| Mistake | Fix |
|---|---|
solve('x^2=1') | syms x; solve(x^2 == 1, x) |
dsolve('Dy = y') | syms y(t); dsolve(diff(y,t) == y) |
subs(f,x,2) without assigning | f = subs(f,x,2) |
Attempting to clear assumptions with the clear command | syms x or assume(x,'clear') — only these reset the symbolic engine |
Using syms inside a function | Use x = sym('x') inside functions |
| Manually extracting PDE coefficients by inspection | Use pdeCoefficients(pdeeq, u) |
| Computing Laplacian as sum of second derivatives | Use laplacian(f, vars) |
Using ccode() and manually building C files | Use matlabFunction(..., 'File', ...) then codegen |
Using sym('A', [n n]) for matrix-level algebra | Use symmatrix('A', [n n]) |
| Hard-coding physical constants as numbers | Use u = symunit; u.hc; u.c_0; u.m_e |
Using combine(expr, 'power') | Invalid target — valid: 'atan', 'exp', 'gamma', 'int', 'log', 'sincos', 'sinhcosh' |
Computing gradient/Hessian/Jacobian/Laplacian/divergence/curl manually with diff | Use gradient, hessian, jacobian, laplacian, divergence, curl |
| Manually building numeric arrays to plot a symbolic expression | Use fplot(f, [a b]), fsurf, fmesh, fcontour, or fanimator — they accept symbolic directly |
Adding 'Optimize' to matlabFunction for a function handle | For handles: matlabFunction(expr, 'Vars', {...}) — nothing else needed. 'Optimize' is only for 'File' output |
| Keeping everything symbolic for a parametric sweep | Convert to numeric: use matlabFunction then loop, or subs+double in a loop |
See also: application-specific mistakes in each reference file.
Conventions for Modern Features
Use
gradient,hessian,jacobian,laplacian,divergence, andcurlwhen computing these standard vector calculus objects — do not manually assemble them fromdiffcallsPrefer
pdeCoefficients()for extracting PDE Toolbox coefficients when the PDE is in a supported formPrefer physical constants from
symunit(e.g.,u.hc,u.c_0) when available; hard-code only if the constant is not in the symunit catalogUse
symmatrixwhen the user asks for atomic/textbook-style matricesNever pass an invalid target to
combineorrewrite— consult the reference for valid targets
Checklist Before Generating Symbolic Code
[ ] Using
syms(not string-basedsym('...')) for variable creation in scripts[ ] Using
==for equations, not=[ ] Using
diff(y, t, n)for derivatives, notDnotation[ ] Using
gradient,hessian,jacobian,laplacian,divergence,curlinstead of manualdiffwhen computing these objects[ ] Specifying the independent variable explicitly in
diff,int,laplace[ ] Assigning
subs(...)output to a variable[ ] NOT wrapping numeric literals in
sym()when a symbolic variable is already in the expression[ ] Setting assumptions with
assume/assumeAlso, clearing withsyms xorassume(x,'clear')[ ] Using
fplot/fsurf/fanimatorfor symbolic plots (they accept symbolic expressions directly)[ ] For parametric sweeps: converting to numeric (
matlabFunctionorsubs+doublein a loop)
Troubleshooting
Issue: solve returns empty or unexpected results
Check: Are there assumptions restricting the domain? Use
assumptionsto check.Try:
solve(eqn, x, 'ReturnConditions', true)to see conditions on solutions.Try:
vpasolvefor numeric solutions when no closed form exists.
Issue: Stale assumptions causing wrong results
Fix: Add
syms <varname>at the top of your script to clear assumptions.Nuclear option:
reset(symengine)clears everything.
See also: application-specific troubleshooting in each reference file.
Copyright 2026 The MathWorks, Inc.
Files
- ATTRIBUTION.mdAdded by AutoGineer1.0 KiB
- LICENSELicence file added by AutoGineer1.4 KiB
- SKILL.md14.5 KiB
- manifest.yaml523 B
- references/control-systems.md5.1 KiB
- references/extract-pde-coefficients.md3.2 KiB
- references/matlabFunction-patterns.md6.4 KiB
- references/ode-solving.md3.2 KiB
- references/plotting-and-display.md3.6 KiB
- references/rewrite-combine-expressions.md4.7 KiB
- references/simplification-and-polynomials.md3.2 KiB
- references/symbolic-to-c-code.md3.7 KiB
- references/symmatrix-workflow.md3.0 KiB
- references/symunit-workflow.md3.6 KiB
references/rewrite-combine-expressions.md
Rewrite and Combine Expressions
Use rewrite to express a symbolic expression in terms of a target function. Use combine to merge multiple calls of the same function into one. These are distinct operations — do not confuse them.
Key Functions
| Function | Purpose |
|---|---|
rewrite(expr, target) | Rewrite expr using target function form |
combine(expr, target) | Combine terms of the same function into one |
expand(expr) | Distribute and expand (algebraic, trig, exp) |
simplify(expr) | Apply general simplification heuristics |
factor(expr) | Factor polynomial into irreducible factors |
collect(expr, var) | Group terms by powers of var |
horner(expr) | Convert polynomial to nested evaluation form |
partfrac(expr, var) | Partial fraction decomposition |
simplifyFraction(expr) | Combine fractions into single numerator/denominator |
Valid Targets for combine
Only these 7 targets are valid:
| Target | Effect | Example |
|---|---|---|
'sincos' | Products/powers of sin/cos → multiple angles | sin(x)*cos(x) → sin(2*x)/2 |
'exp' | Products of exp → single exp | exp(x)*exp(y) → exp(x+y) |
'log' | Sum of logs → single log (needs 'IgnoreAnalyticConstraints', true) | log(x)+log(y) → log(x*y) |
'atan' | Sum of atan → single atan | atan(x)+atan(y) → combined form |
'gamma' | Products of gamma → single gamma | Gamma function combinations |
'int' | Sum of integrals → single integral | int(f)+int(g) → int(f+g) |
'sinhcosh' | Products/powers of sinh/cosh → multiple arguments | Similar to sincos for hyperbolic |
INVALID targets for combine (will error):
'power'— DOES NOT EXIST'sqrt'— DOES NOT EXIST'tan'— DOES NOT EXISTAny target not in the list above
Valid Targets for rewrite
These are the common valid targets:
| Target | Rewrites to |
|---|---|
'exp' | Exponential form (Euler's formula for trig) |
'sincos' | Sine and cosine |
'sin' | Sine only |
'cos' | Cosine only |
'tan' | Tangent (half-angle) |
'log' | Logarithmic form (for inverse trig) |
'sinhcosh' | Hyperbolic sine and cosine |
'sqrt' | Square root form |
'heaviside' | Heaviside step function |
'piecewise' | Piecewise form |
INVALID targets for rewrite:
'pow'— DOES NOT EXIST'power'— DOES NOT EXIST
When to Use Which Function
| Goal | Function |
|---|---|
| Express sin/cos as exponentials | rewrite(expr, 'exp') |
| Express exponentials as sin/cos | rewrite(expr, 'sincos') |
Merge sin(x)*cos(x) into sin(2x)/2 | combine(expr, 'sincos') |
Merge exp(a)*exp(b) into exp(a+b) | combine(expr, 'exp') |
Expand (x+y)^n or sin(x+y) | expand(expr) |
Factor x^3 - x into x*(x-1)*(x+1) | factor(expr) |
| Group by powers of x | collect(expr, x) |
| Nested form for evaluation | horner(expr) |
| Decompose rational function | partfrac(expr, x) |
| General simplification | simplify(expr) |
Important: 'IgnoreAnalyticConstraints'
combine(log(x) + log(y), 'log') does not simplify by default because log(xy) = log(x) + log(y) only holds for positive reals. To force it:
combine(log(x) + log(y), 'log', 'IgnoreAnalyticConstraints', true)
% Result: log(x*y)Pattern: Rewriting Trigonometric Expressions
syms x
% Trig to exponential (Euler's formula)
rewrite(sin(x), 'exp')
% Result: (exp(1i*x) - exp(-1i*x)) / (2i)
% Exponential to trig
rewrite(exp(1i*x), 'sincos')
% Result: cos(x) + 1i*sin(x)
% Half-angle tangent substitution
rewrite(sin(x), 'tan')
% Result: (2*tan(x/2)) / (1 + tan(x/2)^2)Pattern: Combining Trigonometric Products
syms x
% Product to double angle
combine(sin(x)*cos(x), 'sincos')
% Result: sin(2*x)/2
% Power to double angle
combine(cos(x)^2 - sin(x)^2, 'sincos')
% Result: cos(2*x)
% Identity
combine(sin(x)^2 + cos(x)^2, 'sincos')
% Result: 1Common Mistakes
| Mistake | Why It's Wrong | Correct Approach |
|---|---|---|
combine(expr, 'power') | Not a valid target — will error | No equivalent; use simplify or rewrite |
combine(expr, 'sqrt') | Not a valid target | Use rewrite(expr, 'sqrt') instead |
rewrite(expr, 'pow') | Not a valid target | Use simplify for power simplification |
Using simplify when a specific form is needed | simplify picks its own "simplest" form | Use rewrite or combine with explicit target |
combine(log(x)+log(y), 'log') without IgnoreAnalyticConstraints | Won't combine (analytically unsafe) | Add 'IgnoreAnalyticConstraints', true |
Copyright 2026 The MathWorks, Inc.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- MathWorks
- Publisher
- MathWorks (Official)
- Source
- matlab/matlab-agentic-toolkit · skills-catalog/math-and-optimization/matlab-use-symbolic-math · commit 2a7f215
- Licence
- BSD 2-Clause License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE.md)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by MathWorks or MathWorks.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download matlab-use-symbolic-math.zip