Fplot Limit

Posted onby admin

Next: Orthogonal Collocation, Up: Numerical Integration [Contents][Index]

Most important for our purposes here, fplot has picked the limit on the y-axes to be. Ans = 1×2-2.5488 2.5572 What is happening at. Fplot(fun, limits). fplot is used to plot a function between specified limits. fun is a function handle to the function to be plotted. limits is a vector specifying the x-axis limits (xmin,xmax) or the x and y axes limits (xmin,xmax,ymin,ymax). fplot is an alternative to plot where, instead of having to generate the x and y coordinates first and passing them as arguments to. Using fplot, plot this summation for the interval between -1fplot, plot xN(t) on the interval −1≤t.

Stem and leaf plot limitations

23.1 Functions of One Variable

Octave supports five different adaptive quadrature algorithms for computingthe integralof a function f over the interval from a to b. These are

quad

Numerical integration based on Gaussian quadrature.

quadv

Numerical integration using an adaptive vectorized Simpson’s rule.

quadl

Numerical integration using an adaptive Lobatto rule.

quadgk

Numerical integration using an adaptive Gauss-Konrod rule.

quadcc

Numerical integration using adaptive Clenshaw-Curtis rules.

In addition, the following functions are also provided:

integral

A compatibility wrapper function that will choose between quadv andquadgk depending on the integrand and options chosen.

trapz, cumtrapz

Numerical integration of data using the trapezoidal method.

Matplotlib Plot Limits

The best quadrature algorithm to use depends on the integrand. If you haveempirical data, rather than a function, the choice is trapz orcumtrapz. If you are uncertain about the characteristics of theintegrand, quadcc will be the most robust as it can handlediscontinuities, singularities, oscillatory functions, and infinite intervals.When the integrand is smooth quadgk may be the fastest of thealgorithms.

FunctionCharacteristics
quadLow accuracy with nonsmooth integrands
quadvMedium accuracy with smooth integrands
quadlMedium accuracy with smooth integrands. Slower than quadgk.
quadgkMedium accuracy (1e-6 – 1e-9) with smooth integrands.
Handles oscillatory functions and infinite bounds
quadccLow to High accuracy with nonsmooth/smooth integrands
Handles oscillatory functions, singularities, and infinite bounds

Here is an example of using quad to integrate the function

from x = 0 to x = 3.

This is a fairly difficult integration (plot the function over the rangeof integration to see why).

The first step is to define the function:

Note the use of the ‘dot’ forms of the operators. This is not necessary forthe quad integrator, but is required by the other integrators. In anycase, it makes it much easier to generate a set of points for plotting becauseit is possible to call the function with a vector argument to produce a vectorresult.

The second step is to call quad with the limits of integration:

Although quad returns a nonzero value for ier, the resultis reasonably accurate (to see why, examine what happens to the resultif you move the lower bound to 0.1, then 0.01, then 0.001, etc.).

The function 'f' can be the string name of a function, a functionhandle, or an inline function. These options make it quite easy to dointegration without having to fully define a function in an m-file. Forexample:

q =quad(f, a, b)
q =quad(f, a, b, tol)
q =quad(f, a, b, tol, sing)
[q, ier, nfun, err] =quad(…)

Numerically evaluate the integral of f from a to b usingFortran routines from QUADPACK.

f is a function handle, inline function, or a string containing thename of the function to evaluate. The function must have the form y =f (x) where y and x are scalars.

a and b are the lower and upper limits of integration. Eitheror both may be infinite.

The optional argument tol is a vector that specifies the desiredaccuracy of the result. The first element of the vector is the desiredabsolute tolerance, and the second element is the desired relativetolerance. To choose a relative test only, set the absolutetolerance to zero. To choose an absolute test only, set the relativetolerance to zero. Both tolerances default to sqrt (eps) orapproximately 1.5e-8.

Fplot

The optional argument sing is a vector of values at which theintegrand is known to be singular.

The result of the integration is returned in q.

ier contains an integer error code (0 indicates a successfulintegration).

nfun indicates the number of function evaluations that weremade.

err contains an estimate of the error in the solution.

The function quad_options can set other optional parameters forquad.

Note: because quad is written in Fortran it cannot be calledrecursively. This prevents its use in integrating over more than onevariable by routines dblquad and triplequad.

See also:quad_options, quadv, quadl, quadgk, quadcc, trapz, dblquad, triplequad.

quad_options()
val =quad_options(opt)
quad_options(opt, val)
Fplot Limit

Query or set options for the function quad.

When called with no arguments, the names of all available options andtheir current values are displayed.

Given one argument, return the value of the option opt.

When called with two arguments, quad_options sets the optionopt to value val.

Options include

'absolute tolerance'

Absolute tolerance; may be zero for pure relative error test.

'relative tolerance'

Non-negative relative tolerance. If the absolute tolerance is zero,the relative tolerance must be greater than or equal tomax (50*eps, 0.5e-28).

'single precision absolute tolerance'

Absolute tolerance for single precision; may be zero for pure relativeerror test.

'single precision relative tolerance'

Non-negative relative tolerance for single precision. If the absolutetolerance is zero, the relative tolerance must be greater than or equal tomax (50*eps, 0.5e-28).

q =quadv(f, a, b)
q =quadv(f, a, b, tol)
q =quadv(f, a, b, tol, trace)
q =quadv(f, a, b, tol, trace, p1, p2, …)
[q, nfun] =quadv(…)

Numerically evaluate the integral of f from a to busing an adaptive Simpson’s rule.

f is a function handle, inline function, or string containing the nameof the function to evaluate. quadv is a vectorized version ofquad and the function defined by f must accept a scalar orvector as input and return a scalar, vector, or array as output.

a and b are the lower and upper limits of integration. Bothlimits must be finite.

The optional argument tol defines the absolute tolerance used to stopthe adaptation procedure. The default value is 1e-6.

The algorithm used by quadv involves recursively subdividing theintegration interval and applying Simpson’s rule on each subinterval.If trace is true then after computing each of these partialintegrals display: (1) the total number of function evaluations,(2) the left end of the subinterval, (3) the length of the subinterval,(4) the approximation of the integral over the subinterval.

Additional arguments p1, etc., are passed directly to the functionf. To use default values for tol and trace, one may passempty matrices ([]).

The result of the integration is returned in q.

The optional output nfun indicates the total number of functionevaluations performed.

Note: quadv is written in Octave’s scripting language and can beused recursively in dblquad and triplequad, unlike thequad function.

See also:quad, quadl, quadgk, quadcc, trapz, dblquad, triplequad, integral, integral2, integral3.

q =quadl(f, a, b)
q =quadl(f, a, b, tol)
q =quadl(f, a, b, tol, trace)
q =quadl(f, a, b, tol, trace, p1, p2, …)
[q, nfun] =quadl(…)

Numerically evaluate the integral of f from a to b usingan adaptive Lobatto rule.

f is a function handle, inline function, or string containing the nameof the function to evaluate. The function f must be vectorized andreturn a vector of output values when given a vector of input values.

a and b are the lower and upper limits of integration. Bothlimits must be finite.

The optional argument tol defines the absolute tolerance with whichto perform the integration. The default value is 1e-6.

The algorithm used by quadl involves recursively subdividing theintegration interval. If trace is defined then for each subintervaldisplay: (1) the total number of function evaluations, (2) the left end ofthe subinterval, (3) the length of the subinterval, (4) the approximation ofthe integral over the subinterval.

Additional arguments p1, etc., are passed directly to the functionf. To use default values for tol and trace, one may passempty matrices ([]).

The result of the integration is returned in q.

The optional output nfun indicates the total number of functionevaluations performed.

Reference: W. Gander and W. Gautschi, Adaptive Quadrature -Revisited, BIT Vol. 40, No. 1, March 2000, pp. 84–101.https://www.inf.ethz.ch/personal/gander/

See also:quad, quadv, quadgk, quadcc, trapz, dblquad, triplequad, integral, integral2, integral3.

q =quadgk(f, a, b)
q =quadgk(f, a, b, abstol)
q =quadgk(f, a, b, abstol, trace)
q =quadgk(f, a, b, prop, val, …)
[q, err] =quadgk(…)

Numerically evaluate the integral of f from a to busing adaptive Gauss-Konrod quadrature.

f is a function handle, inline function, or string containing the nameof the function to evaluate. The function f must be vectorized andreturn a vector of output values when given a vector of input values.

a and b are the lower and upper limits of integration. Eitheror both limits may be infinite or contain weak end singularities. Variabletransformation will be used to treat any infinite intervals and weaken thesingularities. For example:

Note that the formulation of the integrand uses the element-by-elementoperator ./ and all user functions to quadgk should do thesame.

The optional argument tol defines the absolute tolerance used to stopthe integration procedure. The default value is 1e-10 (1e-5 for single).

The algorithm used by quadgk involves subdividing the integrationinterval and evaluating each subinterval. If trace is true then aftercomputing each of these partial integrals display: (1) the number ofsubintervals at this step, (2) the current estimate of the error err,(3) the current estimate for the integral q.

Alternatively, properties of quadgk can be passed to the function aspairs 'prop', val. Valid properties are

AbsTol

Define the absolute error tolerance for the quadrature. The defaultabsolute tolerance is 1e-10 (1e-5 for single).

RelTol

Define the relative error tolerance for the quadrature. The defaultrelative tolerance is 1e-6 (1e-4 for single).

MaxIntervalCount

quadgk initially subdivides the interval on which to perform thequadrature into 10 intervals. Subintervals that have an unacceptable errorare subdivided and re-evaluated. If the number of subintervals exceeds 650subintervals at any point then a poor convergence is signaled and thecurrent estimate of the integral is returned. The property'MaxIntervalCount' can be used to alter the number of subintervalsthat can exist before exiting.

WayPoints

Discontinuities in the first derivative of the function to integrate can beflagged with the 'WayPoints' property. This forces the ends of asubinterval to fall on the breakpoints of the function and can result insignificantly improved estimation of the error in the integral, fastercomputation, or both. For example,

signals the breakpoint in the integrand at x = 1.

Trace

If logically true quadgk prints information on the convergence of thequadrature at each iteration.

If any of a, b, or waypoints is complex then thequadrature is treated as a contour integral along a piecewise continuouspath defined by the above. In this case the integral is assumed to have noedge singularities. For example,

integrates log (z) along the square defined by[1+1i, 1-1i, -1-1i, -1+1i].

The result of the integration is returned in q.

err is an approximate bound on the error in the integralabs (q - I), where I is the exact value of theintegral.

Reference: L.F. Shampine,'Vectorized adaptive quadrature in MATLAB', Journal ofComputational and Applied Mathematics, pp. 131–140, Vol 211, Issue 2,Feb 2008.

See also:quad, quadv, quadl, quadcc, trapz, dblquad, triplequad, integral, integral2, integral3.

q =quadcc(f, a, b)
q =quadcc(f, a, b, tol)
q =quadcc(f, a, b, tol, sing)
[q, err, nr_points] =quadcc(…)

Numerically evaluate the integral of f from a to b usingdoubly-adaptive Clenshaw-Curtis quadrature.

f is a function handle, inline function, or string containing the nameof the function to evaluate. The function f must be vectorized andmust return a vector of output values if given a vector of input values.For example,

which uses the element-by-element “dot” form for all operators.

a and b are the lower and upper limits of integration. Either orboth limits may be infinite. quadcc handles an infinite limit bysubstituting the variable of integration with x = tan (pi/2*u).

The optional argument tol is a 1- or 2-element vector that specifies thedesired accuracy of the result. The first element of the vector is the desiredabsolute tolerance, and the second element is the desired relative tolerance.To choose a relative test only, set the absolute tolerance to zero. To choosean absolute test only, set the relative tolerance to zero. The defaultabsolute tolerance is 1e-10 (1e-5 for single), and the default relativetolerance is 1e-6 (1e-4 for single).

The optional argument sing contains a list of points where the integrandhas known singularities, or discontinuities in any of its derivatives, insidethe integration interval. For the example above, which has a discontinuity atx=1, the call to quadcc would be as follows

The result of the integration is returned in q.

err is an estimate of the absolute integration error.

nr_points is the number of points at which the integrand was evaluated.

If the adaptive integration did not converge, the value of err will belarger than the requested tolerance. Therefore, it is recommended to verifythis value for difficult integrands.

quadcc is capable of dealing with non-numeric values of the integrandsuch as NaN or Inf. If the integral diverges, and quadccdetects this, then a warning is issued and Inf or -Inf isreturned.

Note: quadcc is a general purpose quadrature algorithm and, as such,may be less efficient for a smooth or otherwise well-behaved integrand thanother methods such as quadgk.

The algorithm uses Clenshaw-Curtis quadrature rules of increasingdegree in each interval and bisects the interval if either the function doesnot appear to be smooth or a rule of maximum degree has been reached. Theerror estimate is computed from the L2-norm of the difference between twosuccessive interpolations of the integrand over the nodes of the respectivequadrature rules.

Implementation Note: For Octave versions ≤ 4.2, quadcc accepted asingle tolerance argument which specified the relative tolerance. Forversions 4.4 and 5, quadcc will issue a warning when called with asingle tolerance argument indicating that the meaning of this input haschanged from relative tolerance to absolute tolerance. The warning ID for thismessage is 'Octave:quadcc:RelTol-conversion'. The warning may bedisabled with warning ('off', 'Octave:quadcc:RelTol-conversion').

Reference: P. Gonnet, Increasing the Reliability of AdaptiveQuadrature Using Explicit Interpolants, ACM Transactions onMathematical Software, Vol. 37, Issue 3, Article No. 3, 2010.

See also:quad, quadv, quadl, quadgk, trapz, dblquad, triplequad.

q =integral(f, a, b)
q =integral(f, a, b, prop, val, …)

Numerically evaluate the integral of f from a to b usingadaptive quadrature.

integral is a wrapper for quadcc (general scalar integrands),quadgk (integrals with specified integration paths), and quadv(array-valued integrands) that is intended to provide MATLABcompatibility. More control of the numerical integration may be achievableby calling the various quadrature functions directly.

f is a function handle, inline function, or string containing the nameof the function to evaluate. The function f must be vectorized andreturn a vector of output values when given a vector of input values.

a and b are the lower and upper limits of integration. Eitheror both limits may be infinite or contain weak end singularities. If eitheror both limits are complex, integral will perform a straight linepath integral. Alternatively, a complex domain path can be specified usingthe 'Waypoints' option (see below).

Additional optional parameters can be specified using'property', value pairs. Valid properties are:

Waypoints

Specifies points to be used in defining subintervals of the quadraturealgorithm, or if a, b, or waypoints are complex thenthe quadrature is calculated as a contour integral along a piecewisecontinuous path. For more detail see quadgk.

ArrayValued

integral expects f to return a scalar value unlessarrayvalued is specified as true. This option will causeintegral to perform the integration over the entire array and returnq with the same dimensions as returned by f. For more detailsee quadv.

AbsTol

Define the absolute error tolerance for the quadrature. The defaultabsolute tolerance is 1e-10 (1e-5 for single).

RelTol

Define the relative error tolerance for the quadrature. The defaultrelative tolerance is 1e-6 (1e-4 for single).

Adaptive quadrature is used to minimize the estimate of error until thefollowing is satisfied:

Known MATLAB incompatibilities:

  1. If tolerances are left unspecified, and any integration limits or waypointsare of type single, then Octave’s integral functions automaticallyreduce the default absolute and relative error tolerances as specifiedabove. If tighter tolerances are desired they must be specified.MATLAB leaves the tighter tolerances appropriate for doubleinputs in place regardless of the class of the integration limits.
  2. As a consequence of using quadcc, quadgk, and quadv,certain option combinations are not supported. Currently,'ArrayValued' cannot be combined with 'RelTol' or'Waypoints'.

See also:integral2, integral3, quad, quadgk, quadv, quadl, quadcc, trapz, dblquad, triplequad.

Fplot Limit

Sometimes one does not have the function, but only the raw (x, y) points fromwhich to perform an integration. This can occur when collecting data in anexperiment. The trapz function can integrate these values as shown inthe following example where 'data' has been collected on the cosine functionover the range [0, pi/2).

The answer is reasonably close to the exact value of 1. Ordinary quadratureis sensitive to the characteristics of the integrand. Empirical integrationdepends not just on the integrand, but also on the particular points chosen torepresent the function. Repeating the example above with the sine functionover the range [0, pi/2) produces far inferior results.

However, a slightly different choice of data points can change the resultsignificantly. The same integration, with the same number of points, butspaced differently produces a more accurate answer.

In general there may be no way of knowing the best distribution of points aheadof time. Or the points may come from an experiment where there is no freedomto select the best distribution. In any case, one must remain aware of thisissue when using trapz.

q =trapz(y)
q =trapz(x, y)
q =trapz(…, dim)

Numerically evaluate the integral of points y using the trapezoidalmethod.

trapz (y) computes the integral of y along the firstnon-singleton dimension. When the argument x is omitted an equallyspaced x vector with unit spacing (1) is assumed.trapz (x, y) evaluates the integral with respect to thespacing in x and the values in y. This is useful if the pointsin y have been sampled unevenly.

If the optional dim argument is given, operate along this dimension.

Application Note: If x is not specified then unit spacing will beused. To scale the integral to the correct value you must multiply by theactual spacing value (deltaX). As an example, the integral of x^3over the range [0, 1] is x^4/4 or 0.25. The following code usestrapz to calculate the integral in three different ways.

See also:cumtrapz.

q =cumtrapz(y)
q =cumtrapz(x, y)
q =cumtrapz(…, dim)

Cumulative numerical integration of points y using the trapezoidalmethod.

cumtrapz (y) computes the cumulative integral of yalong the first non-singleton dimension. Where trapz reports onlythe overall integral sum, cumtrapz reports the current partial sumvalue at each point of y.

When the argument x is omitted an equally spaced x vector withunit spacing (1) is assumed. cumtrapz (x, y) evaluatesthe integral with respect to the spacing in x and the values iny. This is useful if the points in y have been sampledunevenly.

If the optional dim argument is given, operate along this dimension.

Application Note: If x is not specified then unit spacing will beused. To scale the integral to the correct value you must multiply by theactual spacing value (deltaX).

See also:trapz, cumsum.

Next: Orthogonal Collocation, Up: Numerical Integration [Contents][Index]

MATLAB Function Reference
fplot

Plot a function between specified limits

Syntax

Description

fplot plots a function between specified limits. The function must be of the form y = f(x), where x is a vector whose range specifies the limits, and y is a vector the same size as x and contains the function's value at the points in x (see the first example). If the function returns more than one value for a given x, then y is a matrix whose columns contain each component of f(x) (see the second example).

fplot(fun,limits)plots fun between the limits specified by limits. limits is a vector specifying the x-axis limits ([xminxmax]), or the x- and y-axes limits, ([xminxmaxyminymax]).

fun must be

  • The name of an M-file function
  • A string with variable x that may be passed to eval, such as 'sin(x)', 'diric(x,10)', or '[sin(x),cos(x)]'
  • A function handle for an M-file function or an anonymous function (see Function Handles and Anonymous Functions for more information)

The function f(x) must return a row vector for each element of vector x. For example, if f(x) returns [f1(x),f2(x),f3(x)] then for input [x1;x2] the function should return the matrix

fplot(fun,limits,LineSpec)plots fun using the line specification LineSpec.

fplot(fun,limits,tol)plots fun using the relative error tolerance tol (the default is 2e-3, i.e., 0.2 percent accuracy).

fplot(fun,limits,tol,LineSpec)plots fun using the relative error tolerance tol and a line specification that determines line type, marker symbol, and color. See LineSpec for more information.

fplot(fun,limits,n)with n >= 1 plots the function with a minimum of n+1 points. The default n is 1. The maximum step size is restricted to be (1/n)*(xmax-xmin).

fplot(fun,lims,...) accepts combinations of the optional arguments tol, n, and LineSpec, in any order.

fplot(axes_handle,...)plots into the axes with handle axes_handle instead of the current axes (gca).

[X,Y] = fplot(fun,limits,...)returns the abscissas and ordinates for fun in X and Y. No plot is drawn on the screen; however, you can plot the function using plot(X,Y).

Remarks

fplot uses adaptive step control to produce a representative graph, concentrating its evaluation in regions where the function's rate of change is the greatest.

Examples

Plot the hyperbolic tangent function from -2 to 2:

Create an M-file, myfun, that returns a two-column matrix:

Create a function handle pointing to myfun:

Plot the function with the statement

Addition Examples

This example passes function handles to fplot, one created from a MATLAB function and the other created from an anonymous function.

See Also

eval, ezplot, feval, LineSpec, plot

Function Plots for related functions

Plotting Mathematical Functions for more examples


formatfprintf

© 1994-2005 The MathWorks, Inc.