How to select random samples from a dataset in Matlab

robguinness picture robguinness · Nov 28, 2012 · Viewed 29k times · Source

Possible Duplicate:
How do I randomly select k points from N points in MATLAB?

Let's say I have a dataset that includes 10,000 rows of data. What is the best way to create a subset that includes 1,000 randomly chosen rows?

Answer

H.Muster picture H.Muster · Nov 28, 2012

You can use randperm for this task:

Sampling without replacement:

nRows = 10000; % number of rows
nSample = 1000; % number of samples

rndIDX = randperm(nRows); 

newSample = data(rndIDX(1:nSample), :); 

Sampling with replacement:

nRows = 10000; % number of rows
nSample = 1000; % number of samples

rndIDX = randi(nRows, nSample, 1); 

newSample = data(rndIDX, :);