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

조회 수: 117 (최근 30일)
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?

채택된 답변

Walter Roberson
Walter Roberson 2020년 12월 1일
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
Walter Roberson
Walter Roberson 2020년 12월 1일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by