Reputation: 3
I would like to merge a table on Octave without looping. Here is an example of what I want to do:
column1 column2 column3
1 1 1
1 2 2
1 1 2
1 1 3
2 1 3
2 1 1
to like this:
column1 column2 column3
1 1 6
1 2 2
2 1 4
I tried to do it with looping but it's really too slow. Is there a function that can do it without looping ?
Upvotes: 0
Views: 1113
Reputation: 10790
You can use a combination of unique
and accumarray
:
A = [1 1 1
1 2 2
1 1 2
1 1 3
2 1 3
2 1 1];
[U,~,ind] = unique(A(:,1:2),'rows'); %get the unique rows based on the column 1 and 2.
AC = accumarray(ind,A(:,3)); %sum the value of column 3 based on column 1 and 2
M = [U,AC] % creation of the final matrix.
Result:
M =
1 1 6
1 2 2
2 1 4
Upvotes: 4