from
RANDSUBSET
by Bruno Luong
Return a random subset of k elements of the set of n elements
|
| randsubset(v, k)
|
function a = randsubset(v, k)
% A = RANDSUBSET(N, K)
%
% returns a random array A composed of K distinct and sorted elements of
% the set (1:N). The probablity of the subsets is uniform.
%
% A = RANDSUBSET(V, K), where V is a (cell) vector of length N, will pick K
% distinct elements of the set V. The elements of A respect the same order
% with respect to V.
%
% To get random sampling without replacement of the set, call RANDPERM
% after RANDSUBSET.
%
% The function uses Robert Floyd's sampling algorithm.
%
% See also: randperm, nchoosek
%
% Author: Bruno Luong
% Original: 24-Jun-2010
% 24-Jun-2010: mex engine
if isscalar(v)
n = v;
else
n = length(v);
end
if k>n
error('Calling: randsubset(n,k) with n>=k')
end
a64 = int64(ceil(rand(1,k).*(n-k+1:n)));
n64 = int64(n);
% Mex Robert Floyd engine, inplace change of a64
rssfloyd(a64, n64);
a = double(a64);
if ~isscalar(v)
a = v(a);
end
end % randsubset
|
|
Contact us at files@mathworks.com