Why receive error Integrand output size does not match the input size?
26 views (last 30 days)
Torsten on 20 Jan 2023
Edited: Torsten on 20 Jan 2023
x and y that are inputs to Hf from integral2 are usually matrices (of the same size).
The output of Hf is expected to be of the same size as x (or y).
Thus if you only return 0 (a scalar value which is usually not of the same size as x (or y)), you get an error message.
Since I saw the typical functions you want to integrate are that complicated that this problem would never occur, I didn't include this simple case in my answer.
But if you want to cover the special case of a constant function, too, use
syms x y
Hf = matlabFunction(f,'Vars',[x y])
Hf = @(x,y)Hf(x,y).*ones(size(x))
More Answers (1)
Walter Roberson on 20 Jan 2023
If you have f, a symbolic expression nominally in x and y, but which might in practice turn out to be independent of both x and y and so matlabFunction() will not vectorize, then you have three options.
First, you can do what @Torsten showed, of multiplying the output by ones() to do implicit expansion.
Second, you can use
Hf = matlabFunction(f,'Vars',[x y]);
wrapper = @(X,Y) arrayfun(Hf, X, Y);
result = integral2(wrapper, -1, 1, -1, 1);
Third, you can use
xlow = -1; xhigh = 1;
ylow = -1; yhigh = 1;
result = double(f) .* (xhigh - xlow) .* (yhigh - ylow);
Hf = matlabFunction(f, 'vars', [x, y]);
result = integral2(Hf, xlow, xhigh, ylow, yhigh);
as there is no need to call an integration function for a result so simple.