I'm using apache-commons-math RealMatrix on my project to handle matrix operations, however I can't print it with proper formatting.
For every matrix i have so far it goes like this:
double coord[][] = new double[3][3];
coord[0][0] = 1d;
coord[0][1] = 0d;
coord[0][2] = 0d;
coord[1][0] = 2d;
coord[1][1] = 1d;
coord[1][2] = 1d;
coord[2][0] = 3d;
coord[2][1] = 2d;
coord[2][2] = 0d;
System.out.println("coordinates [nó, x, y]");
for(int co = 0 ; co < 3 ; co++){
for(int or = 0 ; or < 3 ; or++){
System.out.printf("%10.5f\t",coord[co][or]);
}
System.out.print("\n");
}
outputing:
coordinates [nó, x, y]
1,00000 0,00000 0,00000
2,00000 1,00000 1,00000
3,00000 2,00000 0,00000
But when i'm using RealMatrix to print, it only prints in string (as far as i could find by myself) like this:
double coord[][] = new double[3][3];
coord[0][0] = 1d;
coord[0][1] = 0d;
coord[0][2] = 0d;
coord[1][0] = 2d;
coord[1][1] = 1d;
coord[1][2] = 1d;
coord[2][0] = 3d;
coord[2][1] = 2d;
coord[2][2] = 0d;
RealMatrix m = MatrixUtils.createRealMatrix(coord);
System.out.println(m.toString());
outputing:
Array2DRowRealMatrix{{1.0,0.0,0.0},{2.0,1.0,1.0},{3.0,2.0,0.0}}
How can I get the same output as in the first case using RealMatrix? From the error messages I get when I try to do it by myself, it seems that if I can convert the realmatrix back to an array it would solve my problem, but I cant manage to do that either...
Edit 1: As I'm trying to solve this, I found that getting the results of my matrix operations in an array would be very helpful, or at least a way of reading specific values out of them.
Edit 2: Added Java tag
Example. public class Print2DArray { public static void main(String[] args) { final int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; for (int i = 0; i < matrix. length; i++) { //this equals to the row in our matrix. for (int j = 0; j < matrix[i].
Apache's commons-math
has a facility for formatting matrices to strings, it is in RealMatrixFormat . Here is a simple example that will generate a table like output:
import org.apache.commons.math3.linear.MatrixUtils;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.linear.RealMatrixFormat;
public class Main {
public static void main(String[] args) {
double data[][] = new double[2][3];
data[0][0] = 11;
data[0][1] = 12;
data[0][2] = 13;
data[1][0] = 21;
data[1][1] = 22;
data[1][2] = 23;
RealMatrix matrix = MatrixUtils.createRealMatrix(data);
RealMatrixFormat matrixFormat = new RealMatrixFormat("", "", "", "\n", "", ", ");
System.out.println(matrixFormat.format(matrix));
}
}
produces:
11, 12, 13
21, 22, 23
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With