mkv
mkv

Reputation: 23

Unique Function based on 2 columns [Instead of rows] <<Cell Array>> Matlab

I have a cell array, a, with contents as follows:

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.]

Any hint is greatly appreciated.

Upvotes: 1

Views: 2658

Answers (2)

Autonomous
Autonomous

Reputation: 9075

You can do it as follows:

desiredCol=3;
B=unique(a{1}(:,desiredCol));
count=histc(a{1}(:,desiredCol),B);
desiredMat(:,2)= count(count~=1);
multipleOccElm= (count~=1).*B;
desiredMat(:,1)=multipleOccElm(multipleOccElm~=0);

This is how you interpret desiredMat:

Take the first row for example. first column will contain the element. Second column will contain how many times it occurred in that particular column. Note that single occurrences will not be displayed.

For the 4th column this is how desiredMat looks:

desiredMat =

     5     3
     6     2

Upvotes: 0

Roney Michael
Roney Michael

Reputation: 3994

You could use:

[B,I,J] = unique(a{1}(:,[3,4]),'rows');
N = hist(J,numel(unique(J)));
N(N~=1)

This would give you:

ans =

     2     3

Upvotes: 1

Related Questions