3

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

At this point, I use randsample in my program as follows:

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 t(i) describes for each person which neighbor they will select.

My T matrix, when read rowwise describes the probability of a person to select their neighbor. For example, the first row says the 1st person will select node 2 or 3 with 50% probability each. They cannot select his own node 1. As I scale up my model, they will always have equal probability of selecting a neighbor, 1/number of neighbors. I have hardcoded the T matrix here for brevity's sake.

I tried to use histc as suggested in the linked topic, but since there is always a 0 in each row of my T matrix, I don't think the cumulative sum accurately sets up bins for rows with a 0 in the middle (here the second row of T).

I also tried to use bsxfun, and I was able to get sensical output when looking at each row of my T matrix individually, but I failed to put it in a loop. I feel the solution may be here, but I'm not sure I fully understand how this function is operating in my context.

So, does anybody have any ideas of how I can speed up my randsample function? At the moment, I iterate it 10000x, and so it is a major bottleneck in my program. It works as I need it to, it's just far too slow.

Community
  • 1
  • 1
  • Your question seems ok to me. But just in case, these are manuals on how to ask good questions: [ask], http://stackoverflow.com/help/mcve – Nick Volynkin Jun 17 '15 at 04:25

1 Answers1

1

So you want, for each person, to pick a neighbour among all other persons, with uniform probability.

I would do it this way. It 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, the generated t(k) is randomly picked from the set {1, 2, ..., k-1, k+1, ..., n} with uniform distribution. To achieve this, two steps are used:

  1. A random value is picked from {1, ..., n-1};
  2. If this value is greater than or equal to k it is incremented by 1.
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147