Sum colums of a matrix based on vector

Dear all,

Given a matrix A=MxM, I would like to construct a new matrix B=MxN, where each column of B is the sum of selected columns of A. The selection is given by a vector V of integer that determines the columns to be summed.

For example, if A is 128x128 and I have a vector V of 128 integers filled with number between 0 and 9, B should be 128x10 where the column i of B is equal to the sum of the columns of A where V[x]=i and x is the index of all columns to be summed.

Thanks,

David

For example,

A = 5x6
[
[0 2 4 1 4 0]
[2 3 4 5 1 1]
[1 5 2 2 3 1]
[2 5 1 2 3 0]
[3 4 1 2 1 1]
]

And V = [2 0 0 2 2 0]

Then

B = 5x4
[
[6 0 5 0]
[8 0 8 0]
[8 0 6 0]
[6 0 7 0]
[6 0 6 0]
]

Does anyone have any idea?

I don’t completely understand the use case.
How is the shape of B created as [5, 4], if V only contains values in [0, 2].

In your example, for i=0, this should be true:

i = 0
B[:, i] = sum(A[:, V==i])

which would be a scalar output.
Could you post a manual calculation of the result, so that we could come up with a code snippet? :slight_smile:

Thanks for answering!

The B has the same number of lines of A. This fact allows us to sum columns of A to construct B. So B has to have 5 lines. Think the number of lines as the number of training examples.

Think the number of columns of A as the number of features of the problem. For example, our example is considering we have 6 features. Therefore, the number of columns of A is 6.

Think the number of columns of B as the number of class of the problem. This example is considering we have, for instance, 4 classes. Therefore, B has 4 columns.

In our problem, the size of the vector V is equal to the number of columns of A. This value may be lower, equal or higher than the number of classes. Nevertheless, the size of V is equal to the number of columns of A.

The V vector has only non-negative integer representing the targets classes (the columns of A to be summed to construct the columns of B. Each column of B represents a class.).

Naturally, V can not have an integer bigger than the number of columns of B, which represents the number of classes. So, there is no problem in V only having the classes 0 and 2. This is the reason why B has the column 1 and 3 equals to zero (we have no columns to sum to targets 1 and 3).

For example,

The first (0-index) column of B is the sum of the columns 1, 2 and 5 of A because V has 0 in these positions.

The second (1-index) column of B is zero because the V vector has no value 1.

The third (2-index) column of B is the sum of the columns 0, 3 and 4 of A because V has 2 in these positions.

The fourth (3-index) column of B is zero because the V vector has no value 3.