Can I avoid double forcycle by bsxfun?
Afficher commentaires plus anciens
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 commentaires
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
le 21 Mar 2016
Réponses (0)
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!