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].



 dlmacedo:

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.


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?