Integration

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

Definite Integral

Show that the definite integral abf(x)dx for f(x)=sin(x) on [π2,3π2] is 0.

syms x
int(sin(x),pi/2,3*pi/2)
ans = 0

Definite Integrals in Maxima and Minima

To maximize F(a)=-aasin(ax)sin(x/a)dx for a0, first, define the symbolic variables and assume that a0:

syms a x
assume(a >= 0);

Then, define the function to maximize:

F = int(sin(a*x)*sin(x/a),x,-a,a)
F = 

{1-sin(2)2 if  a=12asin(a2)cos(1)-a2cos(a2)sin(1)a4-1 if  a1

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 = 

2asin(a2)cos(1)-a2cos(a2)sin(1)a4-1

Create a plot of F to check its shape:

fplot(F,[0 10])

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

Fa = diff(F,a)
Fa = 

2σ1a4-1+2a2acos(a2)cos(1)-2acos(a2)sin(1)+2a3sin(a2)sin(1)a4-1-8a4σ1a4-12where  σ1=sin(a2)cos(1)-a2cos(a2)sin(1)

The zeros of Fa are the local extrema of F:

hold on
fplot(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 = 1.5782881585233198075558845180583

Use subs to get the maximal value of the integral:

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

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

vpa(F_max)
ans = 1.2099496860938456039155811226054

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

vpa(int(sin(x)*sin(x),x,-1,1))
ans = 0.54535128658715915230199006704413

Multiple Integration

Numerical integration over higher dimensional areas has special functions:

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

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

syms x y
int(int(x^2-y^2,y,0,1),x,0,1)
ans = 0

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 fdu=f(ux(t),uy(t),uz(t))dudtdt, where the on the right-hand-side denotes a scalar product.

Use this definition to compute the line integral for t from [0,1]

F_int = int(F(ux,uy,uz)*diff([ux;uy;uz],t),t,0,1)
F_int = 

19cos(1)4-cos(3)108-12sin(1)+sin(3)27+39554

Get a numerical approximation of this exact result:

vpa(F_int)
ans = -0.20200778585035447453044423341349