2

I need to generate vector r of N values 1-6 (they can be repetitive) to given permutation p of N elements. But the values are generated with some probability distribution depending on the i-th value of the permutation.

E.g. I have permutation p = [2 3 1 4] and probabilistic distribution matrix (Nx6): Pr = [1, 0, 0, 0, 0, 0; 0, 0.5, 0, 0.5, 0, 0; 0, 0, 0, 1, 0, 0; 0.2, 0.2, 0.2, 0.2, 0.2, 0]

i-th row represents prob. distribution of values 1-6 to element i in permutation p (its value, not position), sum of rows is 1.

For example, we can assign value 1 to value 1, value 2 or 4 to value 2 etc. So it can look like this: r = [2 4 1 2] or r = [4 4 1 5].

Currently I am using this code:

for i = 1:N 
   r(i) = randsample(1:6,1,true,Pr(p(i),:));
end

But it is quite slow and I am trying to avoid the for-cycle, maybe by function bsxfun or something similar.

Does anyone have any clue, please? :-)

MartyIX
  • 27,828
  • 29
  • 136
  • 207

1 Answers1

0

A solution to your problem is basically available in this answer, everything needed for your case is replacing the vector prob with a matrix and fix all operations to work properly on matrices.

Pr=[1, 0, 0, 0, 0, 0; 0, 0.5, 0, 0.5, 0, 0; 0, 0, 0, 1, 0, 0; 0.2, 0.2, 0.2, 0.2, 0.2, 0];
p = [2 3 1 4];
prob=Pr(p,:);
r=rand(size(pPr,1),1);
x=sum(bsxfun(@ge,r,cumsum(padarray(prob,[0,1],'pre'),2)),2);
Community
  • 1
  • 1
Daniel
  • 36,610
  • 3
  • 36
  • 69