Randomly number selector from a given list of numb

2019-08-29 08:54发布

问题:

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.

回答1:

You could use the function randi to randomly select an integer from the set of valid indices.

x=[x1, x2, x3, x4, x5, x6];
non_zero=find(x);

index = randi(numel(non_zero));
number = x(non_zero(index))

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)].

x=[x1, x2, x3, x4, x5, x6];
x_nz = x; 
x_nz(x == 0) = 0;

index = randi(numel(x_nz));
number = x_nz(index)

To ensure that you do not get the same sequence each time, first call rng('shuffle') to set the seed for random number generation.



回答2:

Have you considered randsample or datasample?

x = [1 4 3 2 6 5];        
randsample(x,1,'true')    % samples one element from x randomly
randsample(x,2,'true')    % two samples

datasample(x,1)

% Dealing with the nonzero condition
y = [1 2 3 0 0 7 4 5];
k = 2;                    % number of samples
randsample(y(y>0),k,'true')

datasample(y(y>0),k)   

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.