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

Antworten (1)

John D'Errico
John D'Errico am 3 Jul. 2016

0 Stimmen

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 Kommentare

soheil
soheil am 3 Jul. 2016
Bearbeitet: per isakson am 3 Jul. 2016
Thanks John! this is just part of my code. I have been using nested for loops and it takes forever to run. My best option is vectorization to see what will happen. the function of the program is
function p = bin_pdf(x,rho,n)
if (x > n) | (n < 0)
p = 0;
else
p = Choosenk(n,x) * rho^x * (1-rho)^(n-x);
end
end
--------------
function C=Choosenk(n,k)
if k>n/2
k=n-k;
end;
C=1;
for i=0:k-1
C=C*(n-i)/(k-i);
end;
end
per isakson
per isakson am 4 Jul. 2016
Bearbeitet: per isakson am 4 Jul. 2016
With a reasonable modern release of Matlab, &nbsp "I have been using nested for loops and it takes forever to run" &nbsp 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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Function Creation finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 3 Jul. 2016

Kommentiert:

am 4 Jul. 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by