vectorizing a for loop when nested loop varies in size
6 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Stephen23
el 28 de Mayo de 2020
Editada: Stephen23
el 28 de Mayo de 2020
"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.
Respuestas (1)
Vaibhav Tomar
el 28 de Mayo de 2020
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:
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!