这个问题在这里已有答案:
我给出了数字列表,
x=[x1, x2, x3, x4, x5, x6];
non_zero=find(x);
我希望Matlab一次随机选择'non_zero'元素中的任何一个。我在网上搜索但是没有这样的功能可以提供我所需的结果。
您可以使用函数randi
从有效索引集中随机选择一个整数。
x=[x1, x2, x3, x4, x5, x6];
non_zero=find(x);
index = randi(numel(non_zero));
number = x(non_zero(index))
或者,或许更清楚一点,首先制作x
的副本,从该副本中删除零元素,然后从[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)
为了确保每次都没有得到相同的序列,首先调用rng('shuffle')
来设置随机数生成的种子。
你考虑过randsample
或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)
在发布这个答案之后,我从@Rashid找到了this excellent answer(由@ChrisLuengo链接)。他还建议考虑datasample(unique(y(y>0),k)
是否合适。