How to Vectorize Dependent For-Loops
Mostra commenti meno recenti
I was wondering if anyone could help me to vectorize this part of my code. Here, bin_pdf is binomial coefficient function. pb and pd are scalar parameters.
for t=0:min(T,r)
for n=0:r-t
pp = (bin_pdf(n,pb,r-t) * bin_pdf(t,pd,min(T,r)));
pt = pt + t/r * pp;
pn = pn + n/r * pp;
pc = pc + (r-t-n)/r * pp;
end
end
Risposte (1)
John D'Errico
il 3 Lug 2016
0 voti
Why do you feel the need to "vectorize"this? Is the function bin_pdf vectorized? I can't tell, since you don't show us that code.
If not, then you will still need to write a loop. So why is there a need to write difficult to read code that will not run any more quickly?
Yes, you COULD use meshgrid to generate a complete set of all possible values for n and t, then exclude those that fail the requirements. Or you could use other tricky schemes. Buy why bother? In fact, there is no assurance that these schemes will be any faster, unless bin_pdf is intelligently vectorized also.
Programmer time is far more important than a few microseconds of CPU time. In fact, between you writing this question, and me answering it, we have already wasted far more time than this is would have taken anyway.
3 Commenti
soheil
il 3 Lug 2016
Modificato: per isakson
il 3 Lug 2016
per isakson
il 4 Lug 2016
Modificato: per isakson
il 4 Lug 2016
With a reasonable modern release of Matlab,   "I have been using nested for loops and it takes forever to run"   is not a convincing argument.
In some cases it is possible to significantly improve performance by vectorizing, in others the best vectorized code is slower, and everything in-between.
Use the function, profile, to analyze the performance of the for-loop based code. The result will help you decide how to improve the code.
The for-loop based code will then help you to debug the improved code.
Categorie
Scopri di più su Function Creation in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!