简体   繁体   中英

Octave - Merging matrix by columns without looping

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM