views:

942

answers:

5

I know that 2d arrays are arrays of arrays. To get a row you can do:

rowArray = my2Darray[row]

Since each row can be a different size, I'm assuming it's not built in to get a column from a 2D array. It leads me to believe you'd have to do something like:

for(int row = 0; row < numRows; row++)
{
    colArray[row] = m2Darray[row][columnOfInterest];
}

Is this correct? Is it the only way?

+2  A: 

Your way is the way to go. However, if you have to do that many times, I may recommended storing it in columns. (or both ways)

jjnguy
+2  A: 

Commons math has some tools you might want to check out:

double[][] data = new double[10][10];
BigMatrix matrix = MatrixUtils.createBigMatrix(data);
matrix.getColumnAsDoubleArray(0);

Commons Math Library

daveb
A: 

Well actually I'd write this as a comment, but my reputation is still to low, so I have to answer:

Guess you mean:

for(int row = 0; row < numRows; row++)
{
    colArray[row] = m2Darray[row][columnOfInterest];
}

BTW: I suppose you are right. There is no easier way.

Curd
+1  A: 

If you are locked down to using a 2d array, then yes, this is it afaik. However, a suggestion that may help you (if possible):

Wrap the array in a class that handles the column fetching.

Good luck.

javamonkey79
A: 

Another way is to store the rows as columns and vice versa. e.g. I needed to do exactly the same thing and I was originally planning to have an array with 10 rows and 2 cols. Because of this limitation, I just swapped my rows and columns and created an array with 10 columns and 2 rows. Then I can use array[0] to get the row from the new array (which would be a column of my original array). Of course you have this flexibility only if you are the creator of that array.

Hope that helps...