从给定的数字列表中随机选择数字
我给出了数字列表,
x=[x1, x2, x3, x4, x5, x6];
non_zero=find(x);
我希望Matlab一次在'non_zero'元素中随机选择任何一个.我在网上搜索过,但是没有可用的功能来提供所需的结果.
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.
您可以使用函数randi
从有效索引集中随机选择一个整数.
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))
或者,也许更清楚一点,首先创建一个x
的副本,从该副本中删除零个元素,然后从[1 numel(x_nz)]
范围中选择一个随机整数.
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)
为确保每次都不会获得相同的序列,请首先调用rng('shuffle')
设置用于随机数生成的种子.
To ensure that you do not get the same sequence each time, first call rng('shuffle')
to set the seed for random number generation.