Can I avoid double forcycle by bsxfun?

1 visualización (últimos 30 días)
Michal Roubalik
Michal Roubalik el 21 de Mzo. de 2016
Comentada: Michal Roubalik el 21 de Mzo. de 2016
Hi, I am wondering, if it is possible to use double bsxfun, or something similar. I have this piece of code:
N = 5;
prob = [0.1 0.2 0 0.1; 0 0 0.05 0.1; 0.2 0.2 0 0.1];
r = rand(size(prob,1),N);
P = zeros(N, size(prob,1));
for i = 1:N
P(i,:) = sum(bsxfun(@ge,r(:,i),cumsum(normP([zeros(size(prob,1),1),prob]),2)),2);
end
Prob matrix contains rows with elements between 0 and 1, each row is probability distribution (after normalisation done by normP). First row of prob matrix is used to generate first element of vector P (values1,2 or 4), second row for the second element (values 3 or 4), and so on.
e.g.: P =
2 4 2
4 4 1
2 4 2
2 4 4
2 3 1
I have already vectorised generating elements for one vector P, but I need to generate several (N) vectors. There must be way to avoid the for cycle.
In the attachment, there is the normP function. I will be glad for help, thank you.
Michal Roubalik
  2 comentarios
Adam
Adam el 21 de Mzo. de 2016
Editada: Adam el 21 de Mzo. de 2016
I had a quick look without managing to get the right syntax, but don't really have more time right now - I'm sure someone else will be able to suggest an answer though.
One thing I would say though is
cumsum(normP([zeros(size(prob,1),1),prob]),2)
is a constant. It never changes within the loop so take it outside the loop to only calculate it once instead of N times. Though of course that advice will likely be rendered irrelevant when someone posts a replacement for the for loop anyway so it is more just general advice on improving a for loop I guess!
Michal Roubalik
Michal Roubalik el 21 de Mzo. de 2016
Thanks a lot, I have not noticed this, because I used this line for slightly different purpose before and I did not notice this change in problem while adapting the code to this problem.
It is faster by aproximately 30% now, thank you! :)

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Matrix Indexing 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