Search code examples
javaapache-commons-math

Apache Commons Math: how to perform sum along rows/columns?


I'm pretty new to Apache Common Math, so please pardon the trivial questions.

Based on the API doc, I'm unable to figure out how to perform column-wise or row-wise sum.

import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.linear.MatrixUtils;

double[][] values = {{1.0, 2.0}, {3.0, 4.0}, {5.0, 6.0}};
RealMatrix mtx = MatrixUtils.createRealMatrix(values);

The above code generate a matrix like the following:

[[1, 2],
 [3, 4],
 [5, 6]]

What's the right syntax to perform column-wise sum? Which would give me:

[9, 12]

And how do I perform row-wise sum? Which would give me:

[3,
 7,
 11
]

For comparison, below is the syntax in Scala's Breeze library:

import breeze.linalg._
val mtx = DenseMatrix((1.0, 2.0), (3.0, 4.0), (5.0, 6.0))

// sum along the column direction
sum(mtx(::, *))
// Transpose(DenseVector(9.0, 12.0))


// sum along the row direction
sum(mtx(*, ::))
// DenseVector(3.0, 7.0, 11.0)

Solution

  • Seems there is no simple method to achieve that, how about generating a ones matrix to do the sum?, like:

    //get the row sums
    mtx.multiply(MatrixUtils.createRealMatrix(new double[][]{{1}, {1}}))
    > Array2DRowRealMatrix{{3.0},{7.0},{11.0}}
    //get the column sums
    MatrixUtils.createRealMatrix(new double[][]{{1, 1, 1}}).multiply(mtx)
    > Array2DRowRealMatrix{{9.0,12.0}}