`integral` function: "Output of the function must be same size as input" error
11 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Abhijit Kale
am 1 Dez. 2020
Kommentiert: Abhijit Kale
am 1 Dez. 2020
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 Kommentare
Akzeptierte Antwort
Walter Roberson
am 1 Dez. 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 Kommentare
Walter Roberson
am 1 Dez. 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.
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!