MATLAB: `integral` function: “Output of the function must be same size as input” error

integrationMATLABnumerical integration

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?

Best Answer

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.