Randomly number selector from a given list of numbers [duplicate]

倾然丶 夕夏残阳落幕 提交于 2020-01-06 07:56:08

问题


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.



来源:https://stackoverflow.com/questions/54844548/randomly-number-selector-from-a-given-list-of-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!