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

NOTE:-

Matlabsolutions.com provide latest MatLab Homework Help,MatLab Assignment Help for students, engineers and researchers in Multiple Branches like ECE, EEE, CSE, Mechanical, Civil with 100% output.Matlab Code for B.E, B.Tech,M.E,M.Tech, Ph.D. Scholars with 100% privacy guaranteed. Get MATLAB projects with source code for your learning and research.

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:

SEE COMPLETE ANSWER CLICK THE LINK

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store