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?
Let us consider two sources:
randsample
, where we see:
y = randsample(s,...)
uses the streams
for random number generation.s
is a member of theRandStream
class. Default is the MATLAB® default random number stream.
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:
randsample
is just redirected to randi
.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.