randomly select different elements of a vector
Show older comments
Hello,
I am looking to select n random elements from a vector, but none of the elements can be the same. for example x=[1 1 1 2 3 4 4 4 5 6 7 7], I want to select 4 random unique elements from x, giving 1, 4, 7, 6.
Thanks
Steve
Accepted Answer
More Answers (2)
the cyclist
on 21 Jul 2016
Edited: the cyclist
on 21 Jul 2016
x=[1 1 1 2 3 4 4 4 5 6 7 7];
ux = unique(x);
rx = randsample(ux,4,false);
Note that this will break if there are fewer than four unique elements in x, but it is easy to put in a safeguard against that. For example,
rx = randsample(ux,min(numel(ux),4),false);
1 Comment
stephen cusack
on 22 Jul 2016
Andrei Bobrov
on 21 Jul 2016
x=[1 1 1 2 3 4 4 4 5 6 7 7];
a = unique(x);
out = a(randperm(numel(a),4))
1 Comment
stephen cusack
on 22 Jul 2016
Categories
Find more on Uniform Distribution (Continuous) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!