Matrix indexes with ejml (or other Java libraries)

571 Views Asked by At

I'm using ejml library for writing mathematical algorithms in java. I think it is pretty useful, but I need to know if there is a fast mode (like print()) to print a matrix with indexes. Example:

    1    2
1  0.00 0.01
2  0.03 0.54
3  3.45 7.88
4  2.24 5.66

Otherwise, do you know other libraries aimed at the purpose?

1

There are 1 best solutions below

2
Mikhail Kholodkov On

Take a look at MatrixIO class. It has over 10 different print(...) methods, for all kinds of matrices. Altough there are no indices will be printed you can override needed methods at your wish.

On the other hand, custom implementation should be fairly simple algorithm. Some generic method which accepts all kinds of matrices should be sufficient.

Here's a working example with comments:

Code

public class MatrixWithIndices {

    public static void main(String[] args) {
        SimpleMatrix simpleMatrix = SimpleMatrix.random_DDRM(5, 5, 1, 9, new Random());

        printMatrixWithIndices(simpleMatrix.getDDRM(), 5, 5);
    }

    public static void printMatrixWithIndices(DMatrix matrix, int numChar, int precision) {
        String format = "%" + numChar + "." + precision + "f "; // default format

        StringBuilder columnIndexes = new StringBuilder();
        columnIndexes.append("    "); //skips first 4 chars

        // Append column indices
        for (int i = 0; i < matrix.getNumCols(); i++) {
            columnIndexes.append(i + 1);

            // Print spaces till next column
            for (int j = 0; j < String.format(format, matrix.get(0, i)).length() - 1; j++) {
                columnIndexes.append(" ");
            }
        }

        // Print column indices
        System.out.println(columnIndexes.toString());

        // Print horizontal dotted line
        System.out.println("  " + columnIndexes.toString().replaceAll(".", "-").substring(3));

        // Print rows
        for (int y = 0; y < matrix.getNumRows(); ++y) {

            // Prints row's index with 'border' (vertical line)
            System.out.print((y + 1) + " | ");

            // Print matrix values
            for (int x = 0; x < matrix.getNumCols(); ++x) {
                System.out.printf(format, matrix.get(y, x));
            }

            // Breaks line
            System.out.println();
        }
    }
}

Output

    1       2       3       4       5       
  -----------------------------------------
1 | 7.16880 6.12461 3.67458 8.26479 2.07274 
2 | 1.73381 6.81084 7.52687 3.40099 4.50719 
3 | 2.56602 8.93279 3.83817 7.26837 2.54689 
4 | 6.17946 2.56854 6.42016 3.85734 5.58872 
5 | 5.89330 4.50916 1.15128 8.49580 6.02326 

It's far from being perfect. Formatting will break for large values, but it should give you a good start.

GitHub Gist: https://gist.github.com/MSBlastt/7c4f3e25b8bed74fac90b6e0ef2f8e7a