Creating new vector that only has duplicates from original vector.

I need help with a small part of my code.
r1=randi(6,1,5)
rollnumber=0;
if Y==0 && rollnumber<2
rollnumber=rollnumber+1;
uniquer1=unique(r1)
countOfr1=hist(r1,uniquer1)
indexToRepeatedValue = (countOfr1~=1)
repeatedValues=uniquer1(indexToRepeatedValue)
numberOfAppearancesOfRepeatedValues=countOfr1(indexToRepeatedValue);
r1repeated=repeatedValues
r1numberofrepeated=numberOfAppearancesOfRepeatedValues
r1repeated=repeatedValues %this gives me the value of the repeated numbers
r1numberofrepeated=numberOfAppearancesOfRepeatedValues %this gives me how many times each number is repeated
Both of these are useful but I need a new vector that just has the repeated values.
The problem is I cannot figure out how to create a new vector with just the repeated values.
Example
r1=randi(6,1,5)
r1=[1 1 4 5 5] %values of r1
r2=[1 1 5 5] %the new r2 vector I need
I have read through my book and searched online and I have not been able to figure this out.
Thank you.

回答(1 个)

[ur1 a b] = unique(r1);
r2 = r1(ismember(r1, ur1(find(histc(b, unique(b)) == 2))));

2 个评论

I see. Please use
[ur1 a b] = unique(r1);
r2 = r1(ismember(r1, ur1(find(histc(b, unique(b)) > 1))));
And if you need it sorted, add
r2 = sort(r2);

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

标签

提问:

Z
Z
2015-5-7

Community Treasure Hunt

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

Start Hunting!

Translated by