randomly select different elements of a vector

14 ビュー (過去 30 日間)
stephen cusack
stephen cusack 2016 年 7 月 21 日
コメント済み: stephen cusack 2016 年 7 月 22 日
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

採用された回答

Thorsten
Thorsten 2016 年 7 月 22 日
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

その他の回答 (2 件)

the cyclist
the cyclist 2016 年 7 月 21 日
編集済み: the cyclist 2016 年 7 月 21 日
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 件のコメント
stephen cusack
stephen cusack 2016 年 7 月 22 日
Apologies I did not frame the question very well. I am looking to take the sample based on the occurrence of each element. So 1 has probability 3/12, 2=1/12, 3=1/12, 4=3/12, 5=1/12, 6=1/12, 7=2/12. Once one element has been chosen it cannot be selected again.

サインインしてコメントする。


Andrei Bobrov
Andrei Bobrov 2016 年 7 月 21 日
x=[1 1 1 2 3 4 4 4 5 6 7 7];
a = unique(x);
out = a(randperm(numel(a),4))
  1 件のコメント
stephen cusack
stephen cusack 2016 年 7 月 22 日
Apologies I did not frame the question very well. I am looking to take the sample based on the occurrence of each element. So 1 has probability 3/12, 2=1/12, 3=1/12, 4=3/12, 5=1/12, 6=1/12, 7=2/12. Once one element has been chosen it cannot be selected again.

サインインしてコメントする。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by