Function x=weightedRandomSample(v,p), attached, does what you have requested. It returns a random sample from vector v, where the probability of the element selected is given by a vector of probabilities, p.
The function first checks that p and v have the same length and that p sums to unity (within a small tolerance). Then the function generates a uniform random number between 0 and 1. Then the funciton uses that random number, and the probability vector p, to select an index in the vector. FInally, the function returns the element of v specified by that index.
Vector p is a probability density: the probability of selecting each element. The key step in function wieghtedRandomSample is to make vector pc, which is the probability distribution. The function then uses a uniform random number and vector pc to select the index for sampling.
Example 1: p=[.7, .2, .1, 0, 0]. Then pc=[.7, .9, 1, 1, 1]. Suppose r=rand()=0.72. Let i=1. Then check if r>pc(1). Yes it is, so i=i+1=2. Check if r>pc(2). It is not, so exit the While loop, with i=2. Return element 2 from the vector v.
Example 2: p=[.2, .2, .2, .2, .2]. Then pc=[.2, .4, .6, .8, 1]. Suppose r=rand()=0.53. Let i=1. Then check if rand>pc(1). Yes it is, so i=i+1=2. Check if rand>pc(2). Yes it is, so i=i+1=3. Check if r>pc(3). It is not, so exit the While loop, with i=3. Return element 3 from the vector v.
I have also included script weightedRandomSampleDemo.m, which demonstrates the use of function weightedRandomSample.m. The script weightedRandomSampleDemo has six different probability vectors (six rows in probArray). For each probability vector, it takes 1000 random samples of vector fi=[10 20 30 40 50]. Finally, it plots six histograms, showing the number of samples of each value of fi, for the six probability vectors. The plot which it creates, showing six histograms, is below.