【问题标题】:Generate Unique Random Matlab Numbers with a range生成具有范围的唯一随机 Matlab 数
【发布时间】:2013-12-14 22:05:17
【问题描述】:

假设我想要 1 到 10 之间的 5 个数字。但是,我不希望任何数字重复。我该怎么做?

我想过做

 randi([1,length(a)])

或者这个:

 (10-1).*rand(5,1) + 1

但是,这一次只能给我一个数字!我想要唯一的数字,这不能保证。

【问题讨论】:

  • 请尝试一下。
  • K.好吧,这就是我到目前为止所做的。

标签: matlab random-sample


【解决方案1】:

一种方法是使用randperm

N = 10;    % Numbers from 1 to N will be permuted
n = 5;    % Numbers to be extracted
x = randperm(N);    % Permute numbers between 1 and N
x = x(1:n);    % Retain first n

这可以推广到任何一组值:

N = 10;    % Length of vector of N numbers to be permuted
y = randn(N, 1);    % Vector from which you want to extract values
n = 5;    % Numbers to be extracted
x = randperm(N);    % Permute numbers between 1 and N
x = y(x(1:n));    % Retain first n of y

问题是当N大而n小时:

tic
N = 1e7;
n = 2;
x = randperm(N);
x = x(1:n);
toc

那么你需要找到一个更好的解决方案。如果您有统计工具箱,请尝试:

tic
x = randsample(N, n, false);
toc

另一种方法,也很慢,但没有使用randpermrandsample

N = 1e7;
n = 2;
y = randn(N, 1);
tic
x = randn(N, 1);
[x x] = sort(x);
x = y(x(1:n));
toc

【讨论】:

  • 其实,你为什么不直接使用:x = randperm(10,5),单线。
  • @roybatty 你是对的 - 在新的 Matlab 版本上,你可以在一行中完成。
猜你喜欢
  • 2015-10-28
  • 2011-08-02
  • 1970-01-01
  • 2011-07-01
  • 2019-08-06
  • 1970-01-01
  • 2015-12-22
  • 2016-05-09
  • 1970-01-01
相关资源
最近更新 更多