ejml icon indicating copy to clipboard operation
ejml copied to clipboard

Propose to add a double[][] convenience method to convert back from DMatrixRMaj

Open ee08b397 opened this issue 1 year ago • 3 comments

DMatrixRMaj can be converted from a double-dimensional array (doulbe[][]) but not the other way around. Can we natively provide an interface for easier testing?

To be more specific, a DMatrixRMaj can be converted from a single-dimensional array or a double-dimensional array, as we can see from the constructors. One use case is asserting the exported matrix is the same as the input matrix. We also have convenience methods to process a Java Matrix or DenseMatrix following processing a DMatrixRMaj.

https://github.com/lessthanoptimal/ejml/blob/c305711410e7f655445f4361ecb2931bbfc6aefc/main/ejml-core/src/org/ejml/data/DMatrixRMaj.java#L93

public class DMatrixRMaj extends DMatrix1Row {

    public DMatrixRMaj(double[][] data) {
        this(1, 1);
        this.set(data);
    }

    public DMatrixRMaj(double[] data) {
        this.data = (double[])data.clone();
        this.numRows = this.data.length;
        this.numCols = 1;
    }

A DMatrixRMaj can export a single-dimensional array, as this is how the data is stored internally. But shouldn't we support all types from input to output as well?

https://github.com/lessthanoptimal/ejml/blob/c305711410e7f655445f4361ecb2931bbfc6aefc/main/ejml-core/src/org/ejml/data/DMatrixD1.java#L60

public abstract class DMatrixD1 implements ReshapeMatrix, DMatrix {

    public double[] getData() {
        return this.data;
    }

ee08b397 avatar Jun 28 '23 15:06 ee08b397

It could be as simple as this, or converting from the double[] data to a double[][], but I do think this should be natively supported in the library natively.

    /**
     * Convert a {@link DMatrixRMaj} to a two-dimensional array
     * 
     * @param matrix is an input DMatrixRMaj
     * @return a 2D array
     */
    public double[][] get2DData(DMatrixRMaj matrix) { 
        double[][] array = new double[matrix.numRows][matrix.numCols];
        for (int row = 0; row < matrix.numRows; row++) {
            for (int column = 0; column < matrix.numCols; column++) {
                array[row][column] = matrix.get(row, column);
            }
        }
        
        return array;
    }

ee08b397 avatar Jun 28 '23 16:06 ee08b397

Thanks for the suggestion. I think this is a good idea. If you submit a PR for adding this to DMatrixRMaj with a unit test I'll go over it, but otherwise I'll get around to it this weekend or next week.

lessthanoptimal avatar Jun 29 '23 02:06 lessthanoptimal

Thanks, @lessthanoptimal. Submitted a PR at https://github.com/lessthanoptimal/ejml/pull/194 with a unit test.

So far, we only use DMatrixRMaj a lot. In the future, it might be useful for other types of matrices as well.

ee08b397 avatar Jul 04 '23 03:07 ee08b397