从集合中随机生成数字? [英] Generate numbers randomly from a set?

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

问题描述

在MATLAB中,我有一组P数字.我想从该集合中生成一个大小为N的随机数组.

In MATLAB, I have a set of P numbers. I would like to generate a random array of size N from this set.

为示例起见,假设我有一个{1, 4}集合.假设我想生成一个大小为5(例如[1 1 4 1 4])的数组.

For the sake of example, let say I have the set {1, 4}. Let say I would like to generate an array of size 5 (e.g., [1 1 4 1 4]).

这是我做的:我使用randi生成了以下数组.

What I did is this: I generated the following array using randi.

N = 5;
v = randi([1 4],[1 N]);

问题是我得到了一个随机数组,其中包含1:4中的值,而不包含{1, 4}中的值. 我可以简单地做到这一点,但是我需要一个更好的方法.

The problem is that I got a random array which contains values in 1:4 and not in {1, 4}. I can simply do this but I need a better way.

for i = 1:length(v)
    if v(i) ~= 1 || v(i) ~= 4
       v(i) = 1; % or v(i) = 4
    end
end

我想我在这里没有一个简单的提示.

I think I am missing a simple hint here.

推荐答案

您应使用datasample

y = datasample(data,k)data中的数据返回随机替换后均匀采样的k个观测值.

y = datasample(data,k) returns k observations sampled uniformly at random, with replacement, from the data in data.

a = [1,4];
datasample(a,5)

根据使用情况,您可以考虑使用

Depending on the usage, you might consider using,

datasample(unique(a),5)

这篇关于从集合中随机生成数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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