Problem with quad: how to handle a loop in the integrand function ?
2 views (last 30 days)
Show older comments
I would like to integrate over a function which uses a loop. I simplified the example on purpose. This integrand function is :
function [EU]=toy(d1,M)
test=zeros(size(M,1),size(M,2))
for i=1:size(M,1)
for j=1:size(M,2)
test(i,j)=M(i,j)+d1;
end
end
EU=sum(sum(test);
When I use:
ex=quad(@(d1) toy(d1,M),0.3,0.5)
I get an error message:
??? Subscripted assignment dimension mismatch.
Error in ==> toy at 6
test(i,j)=M(i,j)+d1;
Error in ==> @(d1)toy(d1,M)
Error in ==> quad at 76
y = f(x, varargin{:});
However, for any particular value of d1, the function yields a unique number. When I try alternative functions within the loop, I always get some kind of error. Has this to do with the way quad works ? Is there some solution ?
Thanks a lot in advance for your replies.
Best regards,
Guillaume
0 Comments
Accepted Answer
Mike Hosea
on 24 Jun 2013
QUAD, and most of the other integration functions in MATLAB, is written to evaluate the integrand at more than one point at a time. So it is expects to pass a vector input and get a vector output. You can add this "vectorization" with a loop in your integrand:
function EU = toy(d1,M)
EU = zeros(size(d1));
for k = 1:numel(EU)
test = zeros(size(M,1),size(M,2));
for i=1:size(M,1)
for j=1:size(M,2)
test(i,j) = M(i,j) + d1(k);
end
end
EU(k) = sum(sum(test));
end
Another way to add the outer loop (without modifying the integrand) is to use ARRAYFUN. Finally, QUAD is obsolete. We now recommend INTEGRAL. INTEGRAL expects the same kind of vectorization, but it also has the 'ArrayValued' option. If you set 'ArrayValued' to true, it will assume your function is vector-valued (doesn't matter if the vector only has one element!), so it will only call the integrand with scalar inputs. -- Mike
More Answers (0)
See Also
Categories
Find more on Function Creation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!