Reputation: 2036
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
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
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