Question

I use the JAMA.matrix package..how do i print the columns of a matrix

Was it helpful?

Solution

You can invoke the getArray() method on the matrix to get a double[][] representing the elements.
Then you can loop through that array to display whatever columns/rows/elements you want.

See the API for more methods.

OTHER TIPS

The easiest way would probably be to transpose the matrix, then print each row. Taking part of the example from the API:

double[][] vals = {{1.,2.,3},{4.,5.,6.},{7.,8.,10.}};
Matrix a = new Matrix(vals);
Matrix aTransposed = a.transpose();
double[][] valsTransposed = aTransposed.getArray();

// now loop through the rows of valsTransposed to print
for(int i = 0; i < valsTransposed.length; i++) {
    for(int j = 0; j < valsTransposed[i].length; j++) {        
        System.out.print( " " + valsTransposed[i][j] );
    }
}

As duffymo pointed out in a comment, it would be more efficient to bypass the transposition and just write the nested for loops to print down the columns instead of across the rows. If you need to print both ways that would result in twice as much code. That's a common enough tradeoff (speed for code size) that I leave it to you to decide.

public static String strung(Matrix m) {
    StringBuffer sb = new StringBuffer();
    for (int r = 0; r < m.getRowDimension(); ++ r) {
        for (int c = 0; c < m.getColumnDimension(); ++c)
            sb.append(m.get(r, c)).append("\t");
        sb.append("\n");
    }
    return sb.toString();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top