Why is vectorizing way slower than the for-next loop it replaced?
So wrote this program that iterates 7 variables, each nested in to the next, so my run times are from 5 to 45 minutes. Naturally, I want to speed this up, so I read all this about using vectors instead of for-next loops. Therefore, I replaced the following code:
for i=1:4 if z(i)<100 ea(i)=0; td(i)=tdo*z(i)/100; elseif z(i)<200 ea(i)=0; td(i)=tdo; else ea(i)=eds(i)*(z(i)-200)/100; td(i)=tdo; end psifirst(i) = -(eds(i) - ea(i)) / td(i); ed(i) = (eds(i) + ea(i)) / 2; end
with:
ea(z<200 | z==200)=0; ea(z>200)=eds(z>200).*(z(z>200)-200)/100; td(z>100)=tdo; td(z<100 | z==100)=tdo*z(z<100)/100; psifirst = -(eds - ea)./ td; ed = (eds + ea) / 2;
This little piece of code is located in a function, that is called from another function, and so on for 7 nested loops. The results of the two version are identical, but the vectorized version is way slower. By the time the whole program converges, this portion will have run through 153 million times, so any improvement is a big improvement. But, my original version with for next loops takes about 5 minutes, the vectorized version took over 45 minutes. What did I do wrong, or how can I make this faster than the for-next loop version?
Thank you so much!
Erin
1 Comment
Accepted Answer
0 Comments
More Answers (1)
2 Comments
See Also
Categories
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!