This question already has an answer here:
- Generate numbers randomly from a set? 2 answers
I have given list of numbers,
x=[x1, x2, x3, x4, x5, x6];
non_zero=find(x);
I want Matlab to randomly select anyone among elements of 'non_zero' at a time. I searched online but there is no such function available to provide my required results.
Have you considered
randsample
ordatasample
?After posting this answer, I found this excellent answer from @Rashid (linked by @ChrisLuengo). He also suggests considering if
datasample(unique(y(y>0),k)
is appropriate.You could use the function
randi
to randomly select an integer from the set of valid indices.Or, perhaps a bit more clear, first make a copy of
x
, remove the zero elements from this copy, and then select a random integer from the range[1 numel(x_nz)]
.To ensure that you do not get the same sequence each time, first call
rng('shuffle')
to set the seed for random number generation.