Random matrix - Code efficiency

4 visualizzazioni (ultimi 30 giorni)
Guillaume A.
Guillaume A. il 29 Mar 2011
Hi, I've got a code to fill a matrix with random numbers. However, I haven't found a way to use efficient code and I must use for loop. Here is the code I would like to optimize :
PoissonZ=poissrnd(Lambda,NbTraj,NbDay);
for i=1:NbDay
for j=1:NbTraj
PoissonSauts(j,i)=sum(randn(PoissonZ(j,i),1));
end
end
As NbTraj and/or NbDay can achieve quickly high value, the code become very slow... I did not found a way to vectorize it. Thanks for suggestions !
G.

Risposta accettata

the cyclist
the cyclist il 29 Mar 2011
Looks to me that each element of PoissonSauts is the sum of K normally distributed variables, where K is itself drawn from a Poisson. I believe you can take advantage of the fact that the sum of K i.i.d. variables that are N(0,1) distributions is equal to sqrt(K) times an N(0,1):
PoissonZ=poissrnd(Lambda,NbTraj,NbDay);
PoissonSauts = randn(NbTraj,NbDay).*sqrt(PoissonZ);
  1 Commento
Guillaume A.
Guillaume A. il 29 Mar 2011
hmmm very interesting approach ! I'll try it asap, thanks !

Accedi per commentare.

Più risposte (1)

Matt Fig
Matt Fig il 29 Mar 2011
I would bet that your code is slow primarily because you did not pre-allocate the PoissonSauts array before the loops. Thus every time through the loop you are causing MATLAB to re-allocate memory for the array, which, as you discovered, is slow.
PoissonZ=poissrnd(Lambda,NbTraj,NbDay);
PoisonSauts = zeros(NBTraj,NbDay); % Pre-allocate the array!
for i=1:NbDay
for j=1:NbTraj
PoissonSauts(j,i)=sum(randn(PoissonZ(j,i),1));
end
end
Try that and see if your code speeds up dramatically.
  1 Commento
Guillaume A.
Guillaume A. il 29 Mar 2011
In fact it is preallocated... just wanted to not surcharge the code presented

Accedi per commentare.

Categorie

Scopri di più su Random Number Generation in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by