Random matrix - Code efficiency

2 次查看(过去 30 天)
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.

采纳的回答

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

请先登录,再进行评论。

更多回答(1 个)

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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by