【发布时间】:2019-02-23 18:09:31
【问题描述】:
我已经给出了数字列表,
x=[x1, x2, x3, x4, x5, x6];
non_zero=find(x);
我希望 Matlab 一次在“非零”元素中随机选择任何人。我在网上搜索过,但没有这样的功能可以提供我需要的结果。
【问题讨论】:
标签: matlab random matlab-guide
我已经给出了数字列表,
x=[x1, x2, x3, x4, x5, x6];
non_zero=find(x);
我希望 Matlab 一次在“非零”元素中随机选择任何人。我在网上搜索过,但没有这样的功能可以提供我需要的结果。
【问题讨论】:
标签: matlab random matlab-guide
您可以使用函数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(由@ChrisLuengo 链接)找到了this excellent answer。他还建议考虑datasample(unique(y(y>0),k) 是否合适。
【讨论】: