Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

replaces randsample with a custom-built randSample function and removes range #324

Merged
merged 10 commits into from
Jan 29, 2025
39 changes: 22 additions & 17 deletions utilities/misc/randSample.m
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,36 @@
% weights : vector
% a weight vector, where the i'th index of ``weights`` is the
% weight for the i'th member of the population.
%
% Returns
% -------
% vector
% The resulting sample of values.
%

% if the user is trying to get multiple items from a single-integer array,
% assume that they want to sample between 1 and n
if isscalar(population) && numItems > 1
population = 1:population;
arguments
population (1,:) double {mustBeNonempty}
numItems int16 {mustBeNonempty, mustBeInteger, mustBePositive}
weights (1,:) double = []
end

nargs = nargin;

if nargs > 3
error("Too many arguments.")
if isscalar(population) && numItems > 1
population = 1:population;
end

if nargs == 3

if isempty(weights)
if numItems > length(population)
coderException(coderEnums.errorCodes.invalidOption, 'numItems is larger than the number of items in the population.')
end
% to generate unweighted numbers without replacement, we just randomise
% the array and take the first numItems items
population = population(randperm(length(population)));
outputSample = population(1:numItems);
else
if length(weights) ~= length(population)
error("Weights and population must be the same length.")
coderException(coderEnums.errorCodes.invalidOption, 'Weights and population must be the same length.')
end

% we generate weighted random integers by creating bins from our weights
Expand All @@ -45,13 +58,5 @@

outputSample = population(randomIndices);

% we can generate unweighted numbers far more efficiently
% just randomise the array and return the first numItems items
else
if numItems > length(population)
error("numItems is larger than the number of items in the population.")
end
population = population(randperm(length(population)));
outputSample = population(1:numItems);
end
end
Loading