randomly select different elements of a vector
11 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
stephen cusack
el 21 de Jul. de 2016
Comentada: stephen cusack
el 22 de Jul. de 2016
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
0 comentarios
Respuesta aceptada
Thorsten
el 22 de Jul. de 2016
x = [1 1 1 2 3 4 4 4 5 6 7 7];
for i = 1:4
ind = randperm(numel(x), 1); % select one element out of numel(x) elements, with the probability of occurrence of the element in x
r(i) = x(ind);
x(x==r(i)) = []; % delete this element from the sample, such that the picked elements are unique
end
Más respuestas (2)
the cyclist
el 21 de Jul. de 2016
Editada: the cyclist
el 21 de Jul. de 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);
Andrei Bobrov
el 21 de Jul. de 2016
x=[1 1 1 2 3 4 4 4 5 6 7 7];
a = unique(x);
out = a(randperm(numel(a),4))
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!