tags:

views:

298

answers:

5

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

A: 

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
A: 

You must add JAMA.matrix to the title of the question.

stepancheg
All set. Better? 8)
duffymo
Much better. Unfortunately some evil man voted down for my comment :)
stepancheg
A: 

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
how do i print each row?
I added some code to illustrate.
Bill the Lizard
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
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
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
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
I agree - thanks, Bill.
duffymo
A: 
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
A: 

another question>>?

where should i store jama package in java pleases........

yousef