Symbolic Math Toolbox


This example shows how to compute definite integrals using Symbolic Math Toolbox™.

Definite Integrals

To maximize $F(a)=\int_{-a}^{a}\sin(ax)\sin(x/a)\,\mathrm{d}x$ for $a \geq 0$, first, define the symbolic variables and assume that $a\geq 0$:

syms a x
assume(a >= 0);

Then, define the function to maximize:

F = int(sin(a*x)*sin(x/a),x,-a,a)
F =
piecewise([a == 1, 1 - sin(2)/2], [a ~= 1, (2*a*(sin(a^2)*cos(1) - a^2*cos(a^2)*sin(1)))/(a^4 - 1)])

Note the special case here for $a=1$. To make computations easier, use assumeAlso to ignore this possibility (and later check that $a=1$ is not the maximum):

assumeAlso(a ~= 1);
F = int(sin(a*x)*sin(x/a),x,-a,a)
F =
(2*a*(sin(a^2)*cos(1) - a^2*cos(a^2)*sin(1)))/(a^4 - 1)

Create a plot of $F$ to check its shape:

ezplot(F,[0 10])

Use diff to find the derivative of $F$ with respect to $a$:

Fa = diff(F,a)
Fa =
(2*(sin(a^2)*cos(1) - a^2*cos(a^2)*sin(1)))/(a^4 - 1) + (2*a*(2*a*cos(a^2)*cos(1) - 2*a*cos(a^2)*sin(1) + 2*a^3*sin(a^2)*sin(1)))/(a^4 - 1) - (8*a^4*(sin(a^2)*cos(1) - a^2*cos(a^2)*sin(1)))/(a^4 - 1)^2

The zeros of $Fa$ are the local extrema of $F$:

hold on
ezplot(Fa,[0 10])
grid on

The maximum is between 1 and 2. Use vpasolve to find an approximation of the zero of $Fa$ in this interval:

a_max = vpasolve(Fa,a,[1,2])
a_max =

Use subs to get the maximal value of the integral:

F_max = subs(F,a,a_max)
F_max =
0.36730152527504169588661811770092*cos(1) + 1.2020566879911789986062956284113*sin(1)

The result still contains exact numbers $\sin(1)$ and $\cos(1)$. Use vpa to replace these by numerical approximations:

ans =

Check that the excluded case $a=1$ does not result in a larger value:

ans =

Multiple Integration

Numerical integration over higher dimensional areas has special functions:

integral2(@(x,y) x.^2-y.^2,0,1,0,1)
ans =


There are no such special functions for higher-dimensional symbolic integration. Use nested one-dimensional integrals instead:

syms x y
ans =

Line Integrals

Define a vector field F in 3D space:

syms x y z
F(x,y,z) = [x^2*y*z, x*y, 2*y*z];

Next, define a curve:

syms t
ux(t) = sin(t);
uy(t) = t^2-t;
uz(t) = t;

The line integral of F along the curve u is defined as $\int f\cdot\mathrm{d}u = \int f(ux(t),uy(t),uz(t))\cdot \frac{\mathrm{d}u}{\mathrm{d}t}\,\mathrm{d}t$, where the $\cdot$ on the right-hand-side denotes a scalar product. Use this definition to compute the line integral for $t$ from 0 to 1:

F_int = int(F(ux,uy,uz)*diff([ux;uy;uz],t),t,0,1)
F_int =
(19*cos(1))/4 - cos(3)/108 - 12*sin(1) + sin(3)/27 + 395/54

Get a numerical approximation of this exact result:

ans =