4

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

duffymo
  • 305,152
  • 44
  • 369
  • 561
user64480
  • 43
  • 1
  • 4

3 Answers3

2

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.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • So do we have 2 matricies here, a and aTransposed? There's no doubt it "works", but that's a big memory price to pay for the sake of printing columns. It's trivial for this example, but any matrix for a real problem will take a big hit. – duffymo Mar 11 '09 at 13:20
  • The transpose method returns a new matrix, so in the example there are two. You can always say a = a.transpose() if you don't want to keep both. – Bill the Lizard Mar 11 '09 at 14:39
  • I would have to look at the API to see if a simple loop construct over the original matrix would have done the job without any transposition needed. – duffymo Mar 11 '09 at 15:14
  • I did link to the API, so you can look at it. The point is that you can write one printMatrix() method that encapsulates the nested for loops in the example, then use it on either the original or transposed matrix. – Bill the Lizard Mar 11 '09 at 15:24
0

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.

tehvan
  • 10,189
  • 5
  • 27
  • 31
0
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();
}
Carl Manaster
  • 39,912
  • 17
  • 102
  • 155