Random matrix - Code efficiency

4 visualizaciones (últimos 30 días)
Guillaume A.
Guillaume A. el 29 de Mzo. de 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.

Respuesta aceptada

the cyclist
the cyclist el 29 de Mzo. de 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 comentario
Guillaume A.
Guillaume A. el 29 de Mzo. de 2011
hmmm very interesting approach ! I'll try it asap, thanks !

Iniciar sesión para comentar.

Más respuestas (1)

Matt Fig
Matt Fig el 29 de Mzo. de 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 comentario
Guillaume A.
Guillaume A. el 29 de Mzo. de 2011
In fact it is preallocated... just wanted to not surcharge the code presented

Iniciar sesión para comentar.

Categorías

Más información sobre Random Number Generation 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!

Translated by