randperm,sort,rand,randint---Matlab中常用的随机函数

    xiaoxiao2021-09-07  173

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

    function p =randperm(n);

    %RANDPERM Randompermutation.

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

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

    %

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

    % See also PERMUTE. % Copyright1984-2002 The MathWorks, Inc.

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

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

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

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

    常用用法:

    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(10)

    ans =

        6    4    8    9    3    5    7   10    2    1

    转载请注明原文地址: https://ju.6miu.com/read-677476.html

    最新回复(0)