从给定的数字列表中随机选择数字 [英] Randomly number selector from a given list of numbers

查看:244
本文介绍了从给定的数字列表中随机选择数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我给出了数字列表,

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.

这篇关于从给定的数字列表中随机选择数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆