Convert matrix back to array in EJML

2.4k views Asked by At

I have started using the EJML library for representing matrices. I will use the SimpleMatrix. I did not find two important things which I need. Perhaps somebody can help me identify if the following operations are possible and if yes, how this can be done:

  1. Is it possible to convert a matrix back to a 1D double array (double[]) or 2D double array (double[][]) without just looping through all elements which would be very inefficient? I did not find a method for that. For example, Jeigen library provides a conversion to a 1D array (but I don't know how this is internally done).

  2. Is it possible to delete a row or column?

By the way, does somebody know how EJML compares to Jeigen for large matrices in terms of runtime? EJML provides much more functionality and is much better documented but I'm a bit afraid in terms of runtime.

2

There are 2 answers

0
Philip Waldman On BEST ANSWER

Manos' answer to the first question did not work for me. This is what I did instead:

public double[][] matrix2Array(SimpleMatrix matrix) {
    double[][] array = new double[matrix.numRows()][matrix.numCols()];
    for (int r = 0; r < matrix.numRows(); r++) {
        for (int c = 0; c < matrix.numCols(); c++) {
            array[r][c] = matrix.get(r, c);
        }
    }
    return array;
}

I don't know how it compares in performance to other methods, but it works fast enough for what I needed it for.

1
Manos Nikolaidis On
  1. The underlying array of a SimpleMatrix (it's always 1-dimensional to keep all elements in the same area in RAM) can be retrieved by first getting the underlying DenseMatrix64F and then getting the public data field of D1Matrix64F base class

    // where matrix is a SimpleMatrix
    double[] data = matrix.getMatrix().data;
    
  2. I don't see a straightforward way to delete arbitrary rows, columns. One workaround is to use extractMatrix (it copies the underlying double[]) to get 2 parts of the original matrix and then combine them to a new matrix. E.g. to delete the middle column of this 2x3 matrix :

    SimpleMatrix fullMatrix = new SimpleMatrix(new double[][]{{2, 3, 4}, {7, 8, 9}});
    SimpleMatrix a = fullMatrix.extractMatrix(0, 2, 0, 1);
    SimpleMatrix b = fullMatrix.extractMatrix(0, 2, 2, 3);
    SimpleMatrix matrix = a.combine(0, 1, b);
    

    Or to delete specifically the first column you can simply do:

    SimpleMatrix matrix = fullMatrix.extractMatrix(0, 2, 1, 3);
    

    Or to delete specifically the last column you can simply do (doesn't delete, copy underlying data[]):

    matrix.getMatrix().setNumCols(matrix.numCols() - 1);
    
  3. I will refer to this answer for benchmarks / performance of various java matrix libraries. The performance of ejml is excellent for small matrices and for say size 100 or more doesn't compete well with libraries backed by native C/C++ libraries (like Jeigen). As always, your mileage may vary.