Clear Filters
Clear Filters

Random matrix - Code efficiency

2 views (last 30 days)
Guillaume A.
Guillaume A. on 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.

Accepted Answer

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

Sign in to comment.

More Answers (1)

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

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!