I have function "" f(t,z)=cos(t).*z "" which for every value of t must be integrated wrt z and output the result as a matrix. I use the following code which takes approximately 15 sec for my real long formulas while the function f which has to be integrated executes almost instantly for any value of its variables.
f=@(t,z) cos(t) .* z
t= linspace(0,3,100);
z= linspace(0,10,1000);
out=zeros(1,numel(t));
for i = 1:numel(t)
Y=f(t(i),z);
out(i)=trapz(z,Y);
end
Any help on how to vectorize this would be greatly appreciated :-)

댓글 수: 2

David Sanchez
David Sanchez 2013년 10월 30일
what is zz?
Ahmad Jamialahmadi
Ahmad Jamialahmadi 2013년 10월 30일
oh ! sorry , typo !!! it's z

댓글을 달려면 로그인하십시오.

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2013년 10월 30일

0 개 추천

f=@(t,z) cos(t) .* z;
t= linspace(0,3,100);
z= linspace(0,10,1000);
out = trapz(z(:),bsxfun(@(t,z)f(t,z),t(:)',z(:)));

댓글 수: 1

Thank you Andrei for your response but unfortunately this vectorization method doesn't seem to optimize the loop !
Using for loop :
Elapsed time is 15.282242 seconds.
Vectorization using bsxfun :
Elapsed time is 15.361217 seconds.
However the above answer was what I was looking for :-)
Although switching from using "Integral" to "trapz" in order to optimize the integration saved me almost 60 sec, but yet it is desirable time for my calculations. Any other idea on how to approach this kinda questions ?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by