Matlab中的几个随机函数-randperm,sort,rand,randint

来源:互联网 发布:淘宝店铺修改发货地址 编辑:程序博客网 时间:2024/05/19 17:51

Matlab自带函数randperm(n)产生1到n的整数的无重复的随机排列,利用它就可以得到无重复的随机数。

function p =randperm(n);

%RANDPERM Randompermutation.

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

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

%

% Note thatRANDPERM calls RAND and therefore changes RAND's state. %

% See alsoPERMUTE. % 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,[1N]):生成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

0 0