How to vectorize a "For Loop"
1 view (last 30 days)
Show older comments
Ahmad Jamialahmadi
on 30 Oct 2013
Commented: Ahmad Jamialahmadi
on 30 Oct 2013
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 Comments
Accepted Answer
Andrei Bobrov
on 30 Oct 2013
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(:)));
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!