2
votes

I have a matrix A in Matlab of dimension m x 3, e.g. m=18

A=[ 2| 1 1;
    3| 1 2;
   -8| 1 3;
   -------
   -5| 1 1;
    2| 1 2;
    6| 1 3;
   -------
    7| 2 1;
    3| 2 2;
    1| 2 3;
    5| 2 4;
   -------
    3| 2 1;
   -8| 2 2;
    1| 2 3;
    0| 2 4;
   -------
    1| 2 1;
    2| 2 2;
    7| 2 3;
    9| 2 4]

The characteristics of A are the following:

  1. It is composed by t submatrices. In the example t=5.

  2. Each submatrix t has dimension b x 3 with b<=m and b can take any value in {3,4,5,...,m} (clearly, in a way such that the sum of all rows is m). In the example, the first and the second submatrices have dimension 3 x 3, the last three submatrices have dimension 4 x 3.

  3. All submatrices of the same dimension are stacked one after the other. In the example, firstly we have the submatrices 3 x 3 and then the submatrices 4 x 3.

I want to compute the vector B of dimension f x 1 where f=size(unique(A(:,2:end),'rows','stable'),1), (in the example f=7), such that B(i,1) is obtained by summing the elements j of A(:,1) having A(j,2:end) equal to the i-th row of unique(A(:,2:end),'rows','stable'), i.e.

B=[2-5;
   3+2;
  -8+6
   7+3+1;
   3-8+2;
   1+1+7;
   5+0+9]
1

1 Answers

3
votes

Use the third output of unique when examining A over the rows and with the 'stable' flag, then use this as input into accumarray. The third output assigns a unique ID for each unique occurrence of a row vector seen in your matrix A, which is very suitable for use in accumarray:

[~,~,f] = unique(A(:,2:end), 'rows', 'stable');
B = accumarray(f, A(:,1));

We get:

B =

    -3 %// 2-5
     5 %// 3+2
    -2 %// -8+6
    11 %// 7+3+1
    -3 %// 3-8+2
     9 %// 1+1+7
    14 %// 5+0+9