Random sample without replacement

Illustration
Qinpeng Wang - 2022-04-02T10:55:53+00:00
Question: Random sample without replacement

Hi,all,   Does anybody know how to do random sample without replacement? The randsample function in matlab only supports sampling with replacement.   I made codes on my own, and it is really weird sometimes it works, but sometimes it shows error (Error using ==> randsample at 94 W must have length equal to N.):     function C=randsample_WithoutReplacement(m,n,A1,A2) %A1:population %A2:probability B=zeros(m,1); C=zeros(n,m); s=transpose(1:1:length(A1)); ut=0; loc=0; A=A2; for j=1:n A=A2; s=transpose(1:1:length(A1)); for i=1:m B(i)=randsample(s,1,true,A); [ut, loc] = ismember(B(i), s); s(loc)=[]; A(loc)=[]; end for i=1:m C(j,i)=A1(B(i)); end end  

Expert Answer

Profile picture of Prashant Kumar Prashant Kumar answered . 2025-11-20

Here is a recursive function that will return one row of your matrix C:

 

function y = randsampleWithoutReplacement(population,k,w)

y = [];
if ~isempty(population) && k > 0
  n = length(population);
  ii = randsample(1:n,1,true,w);
  newpop = setdiff(1:n,ii);
  y = [population(ii) randsampleWithoutReplacement(population(newpop),k-1,w(newpop))];
end

and here is an example of a call:

y = randsampleWithoutReplacement(1:100,20,ones(100,1)/100)

EDIT: And here is one that is closer to your version:

function C=randsample_WithoutReplacement(A1,k,A2)
%A1:population 
%A2:probability
C=zeros(1,k);
A=A2;
n = length(A1);
for i=1:k
  loc=randsample(n-i+1,1,true,A);
  A(loc)=[];
  C(i)=A1(loc);
end

However, I have designed it to act more like randsample.


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!