Collapse All in Page: Syntax

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

integral

Numerical integration

collapse all in page

Syntax

q = integral(fun,xmin,xmax)

q = integral(fun,xmin,xmax,Name,Value)

Description

example

q = integral(fun,xmin,xmax) numerically integrates function fun from xmin to xmax using global
adaptive quadrature and default error tolerances.

example

q = integral(fun,xmin,xmax,Name,Value) specifies additional options with one or


more Name,Value pair arguments. For example, specify 'WayPoints' followed by a vector of real or
complex numbers to indicate specific points for the integrator to use.

Examples

collapse all

Improper Integral

Try this Example

Create the function .

fun = @(x) exp(-x.^2).*log(x).^2;

Evaluate the integral from x=0 to x=Inf.

q = integral(fun,0,Inf)

q = 1.9475

Parameterized Function

Try this Example

Create the function with one parameter, .

fun = @(x,c) 1./(x.^3-2*x-c);


Evaluate the integral from x=0 to x=2 at c=5.

q = integral(@(x)fun(x,5),0,2)

q = -0.4605

Singularity at Lower Limit

Try this Example

Create the function .

fun = @(x)log(x);

Evaluate the integral from x=0 to x=1 with the default error tolerances.

format long

q1 = integral(fun,0,1)

q1 =

-1.000000010959678

Evaluate the integral again, specifying 12 decimal places of accuracy.

q2 = integral(fun,0,1,'RelTol',0,'AbsTol',1e-12)

q2 =

-1.000000000000010

Complex Contour Integration Using Waypoints

Try this Example

Create the function .

fun = @(z) 1./(2*z-1);

Integrate in the complex plane over the triangular path from 0 to 1+1i to 1-1i to 0 by specifying
waypoints.

q = integral(fun,0,0,'Waypoints',[1+1i,1-1i])

q=

-0.0000 - 3.1416i
Vector-Valued Function

Try this Example

Create the vector-valued function and integrate


from x=0 to x=1. Specify 'ArrayValued',true to evaluate the integral of an array-valued or vector-
valued function.

fun = @(x)sin((1:5)*x);

q = integral(fun,0,1,'ArrayValued',true)

q=

0.4597 0.7081 0.6633 0.4134 0.1433

Improper Integral of Oscillatory Function

Try this Example

Create the function .

fun = @(x)x.^5.*exp(-x).*sin(x);

Evaluate the integral from x=0 to x=Inf , adjusting the absolute and relative tolerances.

format long

q = integral(fun,0,Inf,'RelTol',1e-8,'AbsTol',1e-13)

q=

-14.999999999998364

Input Arguments

collapse all

fun — Integrand
function handle

Integrand, specified as a function handle, which defines the function to be integrated


from xmin to xmax.
For scalar-valued problems, the function y = fun(x) must accept a vector argument, x, and return a
vector result, y. This generally means that fun must use array operators instead of matrix operators.
For example, use .* (times) rather than * (mtimes). If you set the 'ArrayValued' option to true,
then fun must accept a scalar and return an array of fixed size.

xmin — Lower limit of x


real number | complex number

Lower limit of x, specified as a real (finite or infinite) scalar value or a complex (finite) scalar value. If
either xmin or xmax are complex, then integral approximates the path integral
from xmin to xmax over a straight line path.

Data Types: double | single


Complex Number Support: Yes

xmax — Upper limit of x


real number | complex number

Upper limit of x, specified as a real number (finite or infinite) or a complex number (finite). If
either xmin or xmax are complex, integral approximates the path integral from xmin to xmax over a
straight line path.

Data Types: double | single


Complex Number Support: Yes

Name-Value Pair Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name
and Value is the corresponding value. Name must appear inside single quotes (' '). You can specify
several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.

Example: 'AbsTol',1e-12 sets the absolute error tolerance to approximately 12 decimal places of
accuracy.

collapse all

'AbsTol' — Absolute error tolerance


nonnegative real number

Absolute error tolerance, specified as the comma-separated pair consisting of 'AbsTol' and a
nonnegative real number. integral uses the absolute error tolerance to limit an estimate of the
absolute error, |q – Q|, where q is the computed value of the integral and Q is the (unknown) exact
value. integral might provide more decimal places of precision if you decrease the absolute error
tolerance. The default value is 1e-10.

Note

AbsTol and RelTol work together. integral might satisfy the absolute error tolerance or the relative
error tolerance, but not necessarily both. For more information on using these tolerances, see
the Tips section.
Example: 'AbsTol',1e-12 sets the absolute error tolerance to approximately 12 decimal places of
accuracy.

Data Types: single | double

'RelTol' — Relative error tolerance


nonnegative real number

Relative error tolerance, specified as the comma-separated pair consisting of 'RelTol' and a
nonnegative real number. integral uses the relative error tolerance to limit an estimate of the
relative error, |q – Q|/|Q|, where q is the computed value of the integral and Q is the (unknown)
exact value. integral might provide more significant digits of precision if you decrease the relative
error tolerance. The default value is 1e-6.

Note

RelTol and AbsTol work together. integral might satisfy the relative error tolerance or the absolute
error tolerance, but not necessarily both. For more information on using these tolerances, see
the Tips section.

Example: 'RelTol',1e-9 sets the relative error tolerance to approximately 9 significant digits.

Data Types: single | double

'ArrayValued' — Array-valued function flag


false (default) | true | 0 | 1

Array-valued function flag, specified as the comma-separated pair consisting of 'ArrayValued' and
either false, true, 0, or 1. Set this flag to true to indicate that fun is a function that accepts a scalar
input and returns a vector, matrix, or N-D array output.

The default value of 'false' indicates that fun is a function that accepts a vector input and returns a
vector output.

Example: 'ArrayValued',true indicates that the integrand is an array-valued function.

'Waypoints' — Integration waypoints


vector

Integration waypoints, specified as the comma-separated pair consisting of 'Waypoints' and a vector
of real or complex numbers. Use waypoints to indicate any points in the integration interval that you
would like the integrator to use. You can use waypoints to integrate efficiently across discontinuities
of the integrand. Specify the locations of the discontinuities in the vector you supply.

You can specify waypoints when you want to perform complex contour integration. If xmin, xmax, or
any entry of the waypoints vector is complex, the integration is performed over a sequence of
straight line paths in the complex plane.

Example: 'Waypoints',[1+1i,1-1i] specifies two complex waypoints along the interval of integration.
Data Types: single | double
Complex Number Support: Yes

Tips

 Do not use waypoints to specify singularities. Instead, split the interval and add the results of
separate integrations with the singularities at the endpoints.

 The integral function attempts to satisfy:

abs(q - Q) <= max(AbsTol,RelTol*abs(q))

where q is the computed value of the integral and Q is the (unknown) exact value. The absolute and
relative tolerances provide a way of trading off accuracy and computation time. Usually, the relative
tolerance determines the accuracy of the integration. However if abs(q) is sufficiently small, the
absolute tolerance determines the accuracy of the integration. You should generally specify both
absolute and relative tolerances together.

 If you specify a complex value for xmin, xmax, or any waypoint, all of your limits and
waypoints must be finite.

 If you are specifying single-precision limits of integration, or if fun returns single-precision


results, you might need to specify larger absolute and relative error tolerances.

References

[1] L.F. Shampine “Vectorized Adaptive Quadrature in MATLAB®,” Journal of Computational and
Applied Mathematics, 211, 2008, pp.131–140.

MuPAD Functions
int Definite and indefinite integrals
int::addpattern Add patterns for integration
intlib::byparts Integration by parts
intlib::changevar Change of variable
intlib::intOverSet Integration over a set
intlib::printWarnings Enable or disable warnings
numeric::gldata Weights and abscissae of Gauss-Legendre quadrature
numeric::gtdata Weights and abscissae of Gauss-Tschebyscheff quadrature
numeric::int Numerical integration (the Float attribute of Int )
numeric::ncdata Weights and abscissae of Newton-Cotes quadrature
numeric::quadrature Numerical integration ( Quadrature )

Examples and How To

Compute Indefinite Integrals


To integrate a mathematical expression f means to find an expression F such that the first derivative
of F is f.

Compute Definite Integrals

For definite integration, the int command restricts the integration variable x to the given range of
integration.

Compute Multiple Integrals

To compute multiple integrals, use nested calls to int.

Apply Standard Integration Methods Directly

Integration by parts is one of the common methods for computing integrals.

Get Simpler Results

When computing integrals, MuPAD® applies strict mathematical rules.

If an Integral Is Undefined

Handling undefined integrals.

If MuPAD Cannot Compute an Integral

If the int command cannot compute a closed form of an integral, MuPAD returns an unresolved
integral:

Concepts

Integration Utilities

Use only in the MuPAD Notebook Interface.

Numeric Algorithms Library

Use only in the MuPAD Notebook Interface.

Complex Line Integrals


Try this Example
This example shows how to calculate complex line integrals using the 'Waypoints' option of
the integral function. In MATLAB®, you use the 'Waypoints' option to define a sequence of
straight line paths from the first limit of integration to the first waypoint, from the first waypoint to the
second, and so forth, and finally from the last waypoint to the second limit of integration.

Define the Integrand with an Anonymous Function


Integrate
where is a closed contour that encloses the simple pole of at the origin.
Define the integrand with an anonymous function.
fun = @(z) exp(z)./z;

Integrate Without Using Waypoints


You can evaluate contour integrals of complex-valued functions with a parameterization. In general, a
contour is specified, and then differentiated and used to parameterize the original integrand. In this
case, specify the contour as the unit circle, but in all cases, the result is independent of the contour
chosen.
g = @(theta) cos(theta) + 1i*sin(theta);
gprime = @(theta) -sin(theta) + 1i*cos(theta);
q1 = integral(@(t) fun(g(t)).*gprime(t),0,2*pi)
q1 =
0.0000 + 6.2832i

This method of parameterizing, although reliable, can be difficult and time consuming since a
derivative must be calculated before the integration is performed. Even for simple functions, you need
to write several lines of code to obtain the correct result. Since the result is the same with any closed
contour that encloses the pole (in this case, the origin), instead you can use the 'Waypoints' option
of integral to construct a square or triangular path that encloses the pole.

Integrate Along a Contour That Encloses No Poles


If any limit of integration or element of the waypoints vector is complex, then integral performs the
integration over a sequence of straight line paths in the complex plane. The natural direction around a
contour is counterclockwise; specifying a clockwise contour is akin to multiplying by -1. Specify the
contour in such a way that it encloses a single functional singularity. If you specify a contour that
encloses no poles, then Cauchy's integral theorem guarantees that the value of the closed-loop
integral is zero.
To see this, integrate fun around a square contour away from the origin. Use equal limits of
integration to form a closed contour.
C = [2+i 2+2i 1+2i];
q = integral(fun,1+i,1+i,'Waypoints',C)
q =
3.3307e-16 - 7.7716e-16i

The result is on the order of eps and effectively zero.

Integrate Along a Contour with a Pole in the Interior


Specify a square contour that completely encloses the pole at the origin, and then integrate.
C = [1+i -1+i -1-i 1-i];
q2 = integral(fun,1,1,'Waypoints',C)
q2 =
0.0000 + 6.2832i

This result agrees with the q1 calculated above, but uses much simpler code.

The exact answer for this problem is .


2*pi*i
ans =
0.0000 + 6.2832i

Integration of Numeric Data


Try this Example
This example shows how to integrate a set of discrete velocity data numerically to approximate the
distance traveled. The integral family only accepts function handles as inputs, so those functions
cannot be used with discrete data sets. Use trapz or cumtrapz when a functional expression is not
available for integration.

View the Velocity Data


Consider the following velocity data and corresponding time data.
vel = [0 .45 1.79 4.02 7.15 11.18 16.09 21.90 29.05 29.05 ...
29.05 29.05 29.05 22.42 17.9 17.9 17.9 17.9 14.34 11.01 ...
8.9 6.54 2.03 0.55 0];
time = 0:24;
This data represents the velocity of an automobile (in m/s) taken at 1 s intervals over 24 s.
Plot the velocity data points and connect each point with a straight line.
figure
plot(time,vel,'-*')
grid on
title('Automobile Velocity')
xlabel('Time (s)')
ylabel('Velocity (m/s)')
The slope is positive during periods of acceleration, zero during periods of constant velocity, and
negative during periods of deceleration. At time t = 0, the vehicle is at rest with vel(1) = 0 m/s.
The vehicle accelerates until reaching a maximum velocity at t = 8 s of vel(9) = 29.05 m/s and
maintains this velocity for 4 s. It then decelerates to vel(14) = 17.9 m/s for 3 s and eventually back
down to rest. Since this velocity curve has multiple discontinuities, a single continuous function cannot
describe it.

Calculate the Total Distance Traveled


trapz performs discrete integration by using the data points to create trapezoids, so it is well suited to
handling data sets with discontinuities. This method assumes linear behavior between the data points,
and accuracy may be reduced when the behavior between data points is nonlinear. To illustrate, you
can draw trapezoids onto the graph using the data points as vertices.
xverts = [time(1:end-1); time(1:end-1); time(2:end); time(2:end)];
yverts = [zeros(1,24); vel(1:end-1); vel(2:end); zeros(1,24)];
p = patch(xverts,yverts,'b','LineWidth',1.5);

trapz calculates the area under a set of discrete data by breaking the region into trapezoids. The
function then adds the area of each trapezoid to compute the total area.
Calculate the total distance traveled by the automobile (corresponding to the shaded area) by
integrating the velocity data numerically using trapz. By default, the spacing between points is
assumed to be 1 if you use the syntax trapz(Y). However, you can specify a different uniform or
nonuniform spacing X with the syntax trapz(X,Y). In this case, the spacing between readings in
the time vector is 1, so it is acceptable to use the default spacing.
distance = trapz(vel)
distance = 345.2200
The distance traveled by the automobile in t = 24 s is about 345.22 m.

Plot Cumulative Distance Traveled


The cumtrapz function is closely related to trapz. While trapz returns only the final integration
value, cumtrapz also returns intermediate values in a vector.
Calculate the cumulative distance traveled and plot the result.
cdistance = cumtrapz(vel);
T = table(time',cdistance','VariableNames',{'Time','CumulativeDistance'})
T=25x2 table
Time CumulativeDistance
____ __________________

0 0
1 0.225
2 1.345
3 4.25
4 9.835
5 19
6 32.635
7 51.63
8 77.105
9 106.15
10 135.2
11 164.25
12 193.31
13 219.04
14 239.2
15 257.1

plot(cdistance)
title('Cumulative Distance Traveled Per Second')
xlabel('Time (s)')
ylabel('Distance (m)')

You might also like