This is machine translation

Translated by Microsoft
Mouse over text to see original. Click the button below to return to the English verison of the page.


Random sample


y = randsample(n,k)
y = randsample(population,k)
y = randsample(n,k,replacement)
y = randsample(population,k,replacement)
y = randsample(n,k,true,w)
y = randsample(population,k,true,w)
y = randsample(s,...)


y = randsample(n,k) returns a k-by-1 vector y of 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. The orientation of y (row or column) is the same as population.

y = randsample(n,k,replacement) or y = randsample(population,k,replacement) returns a sample taken with replacement if replacement is true, or without replacement if replacement is false. The default is false.

y = randsample(n,k,true,w) or y = randsample(population,k,true,w) returns a weighted sample taken with replacement, using a vector of positive weights w, whose length is n. The probability that the integer i is selected for an entry of y is w(i)/sum(w). Usually, w is a vector of probabilities. randsample does not support weighted sampling without replacement.

y = randsample(s,...) uses the stream s for random number generation. s is a member of the RandStream class. Default is the MATLAB® default random number stream.


Draw a single value from the integers 1 through 10:

n = 10;
x = randsample(n,1);

Draw a single value from the population 1 through n, where n > 1:

y = randsample(1:n,1);

    Note:   If population is a numeric vector containing only nonnegative integer values, and population can have length 1, use

    y = population(randsample(length(population),k))

    instead of y = randsample(population,k).

Generate a random sequence of the characters A, C, G, and T, with replacement, according to the specified probabilities.

R = randsample('ACGT',48,true,[0.15 0.35 0.35 0.15])

More About

collapse all


  • To randomly sample data, with or without replacement, use datasample.

Introduced before R2006a

Was this topic helpful?