您的位置:首页 > 编程语言 > MATLAB

【转】Matlab 产生无重复随机数

2009-07-29 17:41 330 查看
http://blog.chinaunix.net/u1/45066/showart_452505.html
Matlab自带函数randperm(n)产生1到n的整数的无重复的随机排列,利用它就可以得到无重复的随机数。

function p = randperm(n);

%RANDPERM Random permutation.

% RANDPERM(n) is a random permutation of the integers from 1 to n.

% For example, RANDPERM(6) might be [2 4 5 6 1 3].

%

% Note that RANDPERM calls RAND and therefore changes RAND's state. %

% See also PERMUTE. % Copyright 1984-2002 The MathWorks, Inc.

% $Revision: 5.10 $ $Date: 2002/04/09 00:26:14 $

[ignore,p] = sort(rand(1,n));

原理:

1. rand(1, n)产生1行n列的0-1之内的随机数矩阵。

2. sort()把这个矩阵排序,返回的ignore是排序后的序列,p是排序后的序列的各数原来的索引,这个索引肯定是随机的,而且是在1到n间无重复的整数。

附:《Matlab中的几个随机函数》

rand

rand(n):生成0到1之间的n阶随机数方阵

rand(m,n):生成0到1之间的m×n的随机数矩阵

randint

randint(m,n,[1 N]):生成m×n的在1到N之间的随机整数矩阵,其效果与randint(m,n,N+1)相同。

>> randint(3,4,[1 10])

ans =

5 7 4 10
5 1 2 7
8 7 8 6
>> randint(3,4,11)

ans =

10 9 6 9
5 10 8 9
10 0 2 6

randperm

randperm(n):产生一个1到n的随机顺序。
>> randperm(10)

ans =

6 4 8 9 3 5 7 10 2 1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: