Search code examples
javamatrixdoubleejml

DMatrixRMaj: get data in matrix form


When I'm initializing a new DMatrixRMaj in ejml (standard format for real matrix), it can store internally a double[][] matrix. Example

double[][] a = new double[][];
//init a
DMatrixRMaj d = new DMatrixRMaj(a);
//math operations on d

now, after the necessary calculations, how I can obtain back a double[][] form of d? With d.getData() i can only obtain the row form. I've also tried wrapping in SimpleMatrix, or creating a SimpleMatrix from doubles, but I haven't find any methods (or matrix format) to retrieve doubles back!

Do you know how I can do it? Or can you suggest a straigthforward workaround without having to write a personalized function?


Solution

  • I am not very familiar with the library, but considering matrix is stored using data[ y*numCols + x ] = data[y][x] format, you could write your own function to retrieve data using the same format.

    Example:.

    import org.ejml.data.DMatrixRMaj;
    
    public class Main {
    
        public static void main(String[] args) throws Exception {
            double [] [] doubles = new double[2][2];
            for (int i = 0; i < 2; i++) {
                for (int j = 0; j < 2; j++) {
                    doubles[i][j] = 0.1;
                }
            }
    
            //init a
            DMatrixRMaj d = new DMatrixRMaj(doubles);
    
            double [] [] doublesAfter = getInitMatrix(d);
    
            System.out.println("Initial matrix: ");
            printMatrix(doubles);
    
            System.out.println("Same matrix after DMatrixRMaj: ");
            printMatrix(doublesAfter);
        }
    
        private static double [][] getInitMatrix(DMatrixRMaj dMatrixRMaj) {
            double [] [] doubles = new double[dMatrixRMaj.getNumRows()][dMatrixRMaj.getNumCols()];
            for (int x = 0; x < dMatrixRMaj.getNumRows(); x++) {
                for (int y = 0; y <dMatrixRMaj.getNumCols(); y++) {
                    doubles[x][y] = dMatrixRMaj.getData()[y*dMatrixRMaj.getNumCols() + x];
                }
            }
            return doubles;
        }
    
        private static void printMatrix(double [][] matrix) {
            for (int i = 0; i < matrix.length; i++) {
                for (int j = 0; j < matrix[i].length; j++) {
                    System.out.print(matrix[i][j] + " ");
                }
                System.out.println();
            }
        }
    }
    
    **Print result:**
    
    //Initial matrix: 
    0.1 0.1 
    0.1 0.1 
    //Same matrix after DMatrixRMaj: 
    0.1 0.1 
    0.1 0.1