Unique Function based on 2 columns [Instead of rows]

Suppose, I have a cell array, a, with contents as such:
a{1}=[1 3 4 5;
3 3 4 5;
5 5 4 5
2 4 2 6;
6 5 2 6
7 2 3 1;]
How can I apply the 'unique' function on 2 columns [column 3 and 4] such that they will return the value '3' and '2'. [Since there are 3 duplicates for the pair 4,5 and 2 duplicates for the pair 2,6.]
Solution proposed:
diff(find([true; any(diff(a{1}(:,3:4)),2); true]))
-----------------------------------------------------------------------
However, when the arrangement of the contents is changed, for eg.
a{1}=[ 1 3 4 5;
3 3 2 6;
5 5 4 5
2 4 3 1;
6 5 2 6
7 2 3 1;]
The code doesn't seem to identify the similarity/duplicated for column 3 and 4 [Corresponding rows: 1 & 3; 2 & 5; 4 & 6]

댓글 수: 1

No, this code assumes blocks of similar rows (for cols 3 and 4), as it seems to be the case in your first example.

댓글을 달려면 로그인하십시오.

 채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2013년 4월 9일

2 개 추천

b=a{1}
c=b(:,3:4)
[~,idx]=unique(c,'rows','first','stable')
out=b(idx,:)

댓글 수: 4

RDG
RDG 2013년 4월 9일
Thank you Azzi for the concise steps. However, it doesn't give the count of the number of duplicates. [In this case, 2,2,2 for each pair of duplicates]. Is there a way to count the number of duplicates?
Cedric
Cedric 2013년 4월 9일
편집: Cedric 2013년 4월 9일
There is certainly a simpler way, but if you add a 3rd output parameter to the call to UNIQUE
[~,idx,cnt] = unique(c, ... )
you can get effective counts with the following
>> cnt = accumarray(cnt, ones(size(cnt)))
cnt =
2
2
2
RDG
RDG 2013년 4월 9일
This problem which I'm facing has exposed me to so many new commands in Matlab and logic which I never thought of before. Thank you for your great insight!
Cedric
Cedric 2013년 4월 9일
편집: Cedric 2013년 4월 9일
Yep, in some sense it is easier to understand how to solve an ODE than to understand how to perform data manipulation efficiently ;-)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by