user34790
user34790

Reputation: 2036

Storing the indices of unique elements in a matrix

I have this matrix

1 2
1 3
1 4
2 1
2 2
3 1

From this matrix I want a data structure something of this sort

1={2 3 4}
2 = {1 2}
3 = {1}

How can I do this efficiently in matlab?

Upvotes: 2

Views: 35

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

You can use accumarray for that. Let your matrix be denoted M.

[bb, ~, jj] = unique(M(:,1));
occ = accumarray(jj,M(:,2),[],@(v) {v(:).'});
result = [num2cell(bb) occ];

The result is a 2-column cell array. With your example data,

>> result{:,1}
ans =
     1
ans =
     2
ans =
     3
>> result{:,2}
ans =
     2     3     4
ans =
     1     2
ans =
     1

Upvotes: 2

Daniel
Daniel

Reputation: 36710

Unique nearly gives you the information you want:

[a,b,c]=unique(x)

where a contains the groups [1,2,3] in this case, and c indicates to which group a row belongs. Now you can get a row, using:

x(c==1,2) %first row

Put this into arrayfun to get all rows:

arrayfun(@(e)x(c==e,2),a,'UniformOutput',false)

Upvotes: 0

Related Questions