How to Vectorize Dependent For-Loops
이전 댓글 표시
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
답변 (1개)
John D'Errico
2016년 7월 3일
0 개 추천
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
soheil
2016년 7월 3일
편집: per isakson
2016년 7월 3일
per isakson
2016년 7월 4일
편집: per isakson
2016년 7월 4일
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.
카테고리
도움말 센터 및 File Exchange에서 Function Creation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!