Effacer les filtres
Effacer les filtres

Random matrix - Code efficiency

2 vues (au cours des 30 derniers jours)
Guillaume A.
Guillaume A. le 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.

Réponse acceptée

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

Connectez-vous pour commenter.

Plus de réponses (1)

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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by