Need alternative randsample for probability vectors with 0s in MATLAB

I have a question similar to this one: Weighted random numbers in MATLAB

At this point, I am using randsample in my program like this:

T = [0 .5 .5; .5 0 .5; .5 .5 0]
choices = 1:3

for i = 1:3
    t(i) = transpose(randsample(choices,1,true,T(i,:)));
end

      

Thus, it t(i)

describes for each person whom he chooses.

My matrix T

when the information read describes the likelihood that a person will choose their neighbor. For example, the first line says that the 1st person will select node 2 or 3 with a 50% probability. They cannot choose their own node 1. When I grow my model, they will always have an equal probability of choosing a neighbor, 1 / number of neighbors. I've hardcoded the T matrix here for brevity.

I tried to use histc

as suggested in the linked thread, but since T

there is always one in every row of my matrix 0

, I don't think the cumulative sum exactly sets the bins for rows with 0 in the middle (second row here T

).

I also tried using bsxfun

and I was able to get sensational output when looking at each row of my matrix T

individually, but I was unable to put it in a loop. I feel like a solution might be here, but I'm not sure I fully understand how this feature works in my context.

So, does anyone have any ideas on how I can speed up my randsample function? At the moment I am iterating it 10000x and therefore this is a serious bottleneck in my program. It works the way I need it, it is too slow.

+3


source to share


1 answer


Thus, you want each person to choose a neighbor with equal probability among all other people.

I would do it like this. This should be pretty fast.

n = 7;                      %// number of persons
t = ceil((n-1)*rand(1,n));  %// step 1
t = t + (t>=(1:n));         %// step 2

      



For each k

generated t(k)

randomly chosen from the set { 1

, 2

, ..., k-1

, k+1

, ... n

} with uniform distribution. There are two steps for this:

  • A random value is selected from { 1

    , ..., n-1

    };
  • If this value is greater than or equal k

    , it is incremented by 1

    .
+1


source







All Articles