Problem with quad: how to handle a loop in the integrand function ?

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

채택된 답변

Mike Hosea
Mike Hosea 2013년 6월 24일
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

추가 답변 (0개)

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by