`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?
댓글 수: 0
채택된 답변
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
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 Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!