Matrix Operations with Apache Commons Math3: A Comprehensive Guide
Tags: java, math, apache
Published: 2023-09-27 15:57:53

Working with vectors and matrices in Java can be cumbersome and challenging when relying solely on the language's built-in support. Fortunately, we have Apache Commons Math3, a Java library that allows us to perform mathematical operations in Java code with greater ease and efficiency compared to manual implementation or creating custom math functions within the code.

In this article, our primary focus will be on the algebraic learning toolkit provided by this library, which enables us to work with matrices.


### Initializing a Matrix


First thing before we starting manipulating a matrix we need to be able to create an instance of it. We can archive this by making the use of `org.apache.commons.math3.linear.MatrixUtils` class

```java
double[][] data = {
    {1, 2, 3},
    {4, 5, 6}
};

var matrix = MatrixUtils.createRealMatrix(data);
```
The MatrixUtils class offers a variety of methods to create matrix instances in different ways. For instance, the createRealMatrix method accepts a Java array as an argument and returns a RealMatrix object.

Once we've created a 2x3 matrix, we can perform various manipulations, such as accessing a specific row or retrieving a particular column by simply calling the corresponding methods.

```java
var column = matrix.getColumn(0);
var row = matrix.getRow(1);
```
This is the full list of all the methods available in a [RealMatrix's doc](https://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/linear/RealMatrix.html)


### Operate with Matrices


We can of course perform linear algebra operations to the matrix, by simple calling methods from our same `RealMatrix` instance.

#### Transpose

```java
var transposedMatrix = matrix.transpose();

----
output:
{ 1, 2, 3 },
{ 4, 5, 6 }

transposedMatrix

{1, 4},
{2, 5},
{3, 6}

```

Remember that Real-matrix is an immutable class, which means it is likely to return a new instance instead of modifying the current one.


#### Multiply

```
matrix.multiply(matrix);
```
However as this looks syntactically correct we get a `DimensionMismatchException` because we cannot multiply a 2x3 with another 2x3 matrix, me need at least to transpose the matrix before we can make the operation.

```sh
Exception in thread "main" org.apache.commons.math3.exception.DimensionMismatchException: 3 != 2
```

```
matrix.multiply(matrix.transpose());
----
output:
{1,4}
{2,5}
{3,6}
```
#### Chaining operations

You can beautifully express mathematical expressions by chaining operations, as I did in this case while calculating a normal equation.
 
```java
// calculating optimal parameter using normal equation
// P = (Xt * X)^-1 * Xt * Y
var params = design.transpose()
    .multiply(design)
    .inverse()
    .multiply(design.transpose())
    .multiply(squares);
```

### Conclusion

Apache Commons Math3 can be a valuable asset when handling mathematical operations that are not covered by Java's standard capabilities. It enables the application of machine learning algorithms in Java without the necessity to switch to Python. This versatility makes it a valuable tool for developers seeking to harness the power of mathematics within the Java ecosystem.