0

I have a probability vector e.g., P = [0.1,0.2,0.3,0.4]. Then I use the command cumsum to create another vector Q = cumsum(P) = [0.1,0.3,0.6,1.0] I generate a Uniform [0,1] random vector,X = [0.11,0.72,0.32,0.94], and I want to know whether each entry of X is lying between [0,0.1] or [0.1,0.3] or [0.3,0.6], or [0.6,1.0] and I want to return a vector, which contains the index of the interval that each entry of X belongs to.

Is there a fast way of doing this, without writing a for loop?

KevinKim
  • 1,382
  • 3
  • 18
  • 34

1 Answers1

0

For inputs: number x and vector Q

Assuming you want equality in the upper endpoint of each interval (as is usual in probability), it's as simple as

ind = find(x<=Q, 1);

For equality in the lower endpoint,

ind = find(x<Q, 1);

For inputs: vector x and matrix Q

In this case you can use the second output of max, which acts as a sort of vectorized find:

x = [.5; .3; .2];
Q = [.1 .3 .5 .7 1;
     .2 .3 .4 .8 1
     .1 .1 .3 .6 1]
[~, ind] = max(bsxfun(@le, x(:), Q), [], 2)

This gives

ind =
     3
     2
     3
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147