`integral` function: "Output of the function must be same size as input" error

111 views (last 30 days)
I am trying to use the integral function in MatLab, but I get the following error depending on the anonymous function I use.
f = @(x) x;
integral(f, 1, 2) % WORKS %
ans = 1.5
% Change function
f = @(x) 1;
integral(f, 1, 2) % ERROR %
Error using integralCalc/finalInputChecks (line 526)
Output of the function must be the same size as the input. If FUN is an array-valued integrand, set the 'ArrayValued'
option to true.
What is this error, and why is it sensitive to the function I use?

Accepted Answer

Walter Roberson
Walter Roberson on 1 Dec 2020
integral() will call the given function with a vector of values, and the function must return one value for each element in the vector.
f = @(x) 1;
however, that code returns the scalar constant 1, rather than one 1 for each element of the input x. You should instead code
f = @(x) ones(size(x));
Alternately you can code
integral(f, 1, 2, 'arrayvalued', true)
but that can be slower as it forces integral() to not use vectorized calls.
  3 Comments
Walter Roberson
Walter Roberson on 1 Dec 2020
It isn't just "like" using vector ops to speed things up, it is using that.
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.

Sign in to comment.

More Answers (0)

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!