vectorizing a for loop when nested loop varies in size
6 次查看(过去 30 天)
显示 更早的评论
i have a cell array firmsandC, that is 1x123. each of these cells has a table that is NxL, where N ranges from 1 to 4 and L ranges from 8 to 60000.
funcomplete is a function that takes the indexes for each of these entries in firmsandC, and each of the columns in each cell, and spits out a Nx5 table.
it currently takes 1.3 seconds per iteration, and would like to vectorize this. the main problem i have is that the inner loop has different size for each k, and have been trying to vectorize it with little success
for k=1:length(firmsandC)
for i=1:size(firmsandC{1,k},2)-2
tic
tempfinal{k,i}=funcomplete(k,i);
toc
end
end
any suggestions?
thank you
7 个评论
Stephen23
2020-5-28
编辑:Stephen23
2020-5-28
"Am I interpreting this wrong?"
If your Bugatti Chiron is faster than your Porsche 911, then is the Porsche slow?
We agree that the Bugatti is much faster than the Porsche, but I still rather doubt that the police would accept your excuse that you can't possibly be speeding whilst driving your Porsche because your Bugatti is much faster.
Note that not all code can be vectorized, and not all vectorized code is faster than loops: naive code vectorization can easily lead to large intermediate data arrays which require a lot of memory, and this definitely slows things down (or even makes the vectorization untenable) (this is not just a hypothetical situation, it really does happen).
That line really says more about code vectorization than it does about the speed of loops.
回答(1 个)
Vaibhav Tomar
2020-5-28
Hey John,
Be aware of background processes that share computational resources and decrease the performance of your MATLAB® code.
While organizing your code:
- Use functions instead of scripts. Functions are generally faster.
- Prefer local functions over nested functions. Use this practice especially if the function does not need to access variables in the main function.
- Use modular programming. To avoid large files and files with infrequently accessed code, split your code into simple and cohesive functions. This practice can decrease first-time run costs.
You may refer to the following link for more information:
另请参阅
类别
在 Help Center 和 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!