Can I avoid double forcycle by bsxfun?

2 views (last 30 days)
Michal Roubalik
Michal Roubalik on 21 Mar 2016
Commented: Michal Roubalik on 21 Mar 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 Comments
Adam
Adam on 21 Mar 2016
Edited: Adam on 21 Mar 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 on 21 Mar 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! :)

Sign in to comment.

Answers (0)

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!