Question
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
Prashant Kumar
PhD Expert
Answered Aug 25, 2026
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.
100% Run Guarantee
3-Hour Fast-Track Delivery
Need a Custom Version or Complete Simulation for This Problem?
Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.
Tested on MATLAB R2024b / R2026a
Turnitin 0% Plagiarism Report
Free 7-Day Revisions Guarantee
Have a different question? Ask here
Related random Questions & Solutions
Browse All →
Explore similar technical troubleshooting questions and verified MATLAB solutions:
Ready-to-Run MATLAB & Simulink Projects
Browse All Projects →