Hello everyone,
I have a vector, A, of n elements each of which has a weight stored in another vector W (clearly A and W are of the same size!)
How can I choose k samples from A according to the vector W (a weighted random selection).
In matlab it would be: randsample(A,k,true,W)
but I don't know how to do eit in octave.
Thank you
Hamid
I have a vector, A, of n elements each of which has a weight stored in another vector W (clearly A and W are of the same size!)
How can I choose k samples from A according to the vector W (a weighted random selection).
In matlab it would be: randsample(A,k,true,W)
but I don't know how to do eit in octave.
Thank you
Hamid
-
I don't know octave but you could use a process like this...
To chose one weighted element:
Make another vector, Wc, which is the cumulative totals of W(0) through to W(n)
Use a random function to get a number between zero and Wc(n)
Starting at Wc(0), the chosen element is first one where Wc(i) is greater than the random number.
Return the number of that element, call it e.
To chose k random elements:
Use the above procedure to chose one element, e
Remove the element e from A and W eg by shifting the elements above it across. Note that the vectors are now one element shorter.
Repeat until you have k elements.
To chose one weighted element:
Make another vector, Wc, which is the cumulative totals of W(0) through to W(n)
Use a random function to get a number between zero and Wc(n)
Starting at Wc(0), the chosen element is first one where Wc(i) is greater than the random number.
Return the number of that element, call it e.
To chose k random elements:
Use the above procedure to chose one element, e
Remove the element e from A and W eg by shifting the elements above it across. Note that the vectors are now one element shorter.
Repeat until you have k elements.