Why does the QUAD function within MATLAB return an error when I specify an integrand as a string expression representing a constant value?

1 view (last 30 days)
For example, if I try to integrate "f(t) = 3" using:
quad('3', 0, 1)
I receive the following error:
??? Attempted to access y(7); index out of bounds because numel(y)=1.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 22 Jan 2010
This error occurs because the function you are passing to QUAD returns a scalar value, not the required vector value, as the documentation for QUAD indicates. For example, when using:
quad('0',-5,5)
QUAD attempts to evaluate the function '0' at all the points in “x”. It will then this resultant to determine if it needs to adapt the set of quadrature points to more accurately compute the integral on the specified region. However, when it checks to see if the values at the endpoints (the first and last quadrature points) are finite, it fails since there is no value at the last quadrature point.
As a workaround, ensure that your function returns a vector the same size as the input to the function. In the case where you are attempting to integrate the constant function f(x) = n, use the following syntax:
quad(@(x) repmat(n, size(x)),-5,5)
If you are using a version of MATLAB prior to MATLAB 7.0 (R14), you will need to use an inline function or a function file rather than an anonymous function. For this example, use:
quad('n*ones(size(x))', -5, 5,[],[],n)

More Answers (0)

Categories

Find more on Function Creation in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!