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!