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?
y = randsample( n , k ) returns k values sampled uniformly at random, without replacement, from the integers 1 to n . y = randsample( population , k ) returns a vector of k values sampled uniformly at random, without replacement, from the values in the vector population .
To take a random sample from a matrix in R, we can simply use sample function and if the sample size is larger than the number of elements in the matrix replace=TRUE argument will be used.
x=randi([1,10],1,10);
The rand function returns floating-point numbers between 0 and 1 that are drawn from a uniform distribution. For example: rng('default') r1 = rand(1000,1); r1 is a 1000-by-1 column vector containing real floating-point numbers drawn from a uniform distribution.
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, :);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With