Search code examples
matlabfunctionrandombuilt-in

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


I usually use randsample, but I came across randi, and I'm wondering if there is any difference.

For example, these seem to be both picking random numbers from [1,10] and returning a 10 x 1 vector:

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

What is the difference between these two lines of code?


Solution

  • Let us consider two sources:

    1. The documentation of randsample, where we see:

      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. The source code of randsample (Copyright 1993-2010 The MathWorks, Inc.) we find the following behavior for the case when the 3rd input is 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
      ...
      

    So from the above we learn the following:

    • In some cases the input of randsample is just redirected to randi.
    • There's a slightly different behavior for edge cases, like randi(0,0,1) (which errors) vs. randsample(0,0,true) (which outputs an empty array).

    Generally randsample has more features: it is able to handle a non-default RandStream, and weighting.