Search code examples
javaapache-commons-math

Access the non-zero elements of a sparse matrix in the Commons Math library


I am using the Apache Commons Math library for matrix operations because it seems quite complete despite its absolute lack of proper documentation.

import org.apache.commons.math3.linear.SparseFieldMatrix;  

//inside a function:  
    int n = 300;
    SparseFieldMatrix Y = new SparseFieldMatrix(ComplexField.getInstance(), n, n);
    // some code to fill values into Y

I have seen the method Y.walkInRowOrder(FieldMatrixChangingVisitor<Complex>() );, which I guess does what I want: to list the columns that contain elements for every row.

However I have no idea on how to use it, since FieldMatrixChangingVisitor cannot be instantiated. What would be the right approach?


Solution

  • Despite the negative voting, I believe this is a legit question, for which I found an answer after a lot of code reading.

    The answer is that with Sparse implementation of the commons math library it is not possible to find the non-zero elements of a stored sparse matrix. Instead you need to loop for all the rows and columns to 'rediscover' which elements are not zero (in other words, which elmenets are in the internal storage structure).

    So, if you are reading this, consider building an structure to map your sparse matrix indices, or changing to another sparse algebra library.