randi(x,y,1) 和 randsample(x,y,true) 有什么区别?

What is the difference between randi(x,y,1) and randsample(x,y,true)?

我平时用的是randsample,但是遇到了randi,不知道有什么区别

例如,这些似乎都是从 [1,10] 中选取随机数并返回 10 x 1 向量:

n = randi(10,10,1);
n2 = randsample(10,10,true);

这两行代码有什么区别?

让我们考虑两个来源:

  1. randsample的文档,我们在其中看到:

    y = randsample(s,...) uses the stream s for random number generation. s is a member of the RandStream class. Default is the MATLAB® default random number stream.

  2. randsample (Copyright 1993-2010 The MathWorks, Inc.) 的源代码我们发现当第 3 个输入是 true 时的以下行为:

    % Sample with replacement
    case {true, 'true', 1}
        if n == 0
            if k == 0
                y = zeros(0,1);
            else
                error(message('stats:randsample:EmptyPopulation'));
            end
        elseif isempty(w)
            if defaultStream
                y = randi(n,k,1);
            else
                y = randi(s,n,k,1);
            end
    
        else
            % Irrelevant case as it concerns weighting which randi doesn't support.
        end
    ...
    

所以从上面我们了解到以下内容:

  • 在某些情况下 randsample 的输入只是重定向到 randi
  • 边缘情况的行为略有不同,例如 randi(0,0,1)(错误)与 randsample(0,0,true)(输出空数组)。

一般来说 randsample 有更多的功能:它能够处理非默认 RandStream 和加权。