3

Let's say I have a 2D array:

int[][] a = new int[4][3];

populated such that:

1 2 3
4 5 6
7 8 9
2 5 7

Is there any shortcut method in java to extract lets say column 1 as single array:

array1 = {1 4 7 2};

Currently what I am doing is traversing through the whole 2D matrix and with if condition (if j==0), I traverse over the rows and add values to 1D array.
Just wondering if there is any standard method offered in java for such tasks.

pb2q
  • 58,613
  • 19
  • 146
  • 147
Johnydep
  • 6,027
  • 20
  • 57
  • 74

3 Answers3

2

No there is no shortcut to doing this. You have to loop over the arrays, switching the x & y indices.

Lawrence Dol
  • 63,018
  • 25
  • 139
  • 189
  • Of course, if it's a recurring pattern in your code, you should write a helper method to do it for you. Or consider whether the fact that you're continually transposing matrices means that your design is broken! – Oliver Charlesworth Jul 10 '11 at 17:36
  • actually i have to calculate cosineSimilarity which requires traversing over the transposed columns and it is recursive calculation over a huge matrix of the size [2500]x[3000]. The only idea i can think of is to integrated the calculation inside the matrix for now. – Johnydep Jul 10 '11 at 17:48
0

There is no such build-in method. You have to write a simple loop.

zacheusz
  • 8,750
  • 3
  • 36
  • 60
0

You might want to consider use of a matrix library. But this is pretty simple stuff - if this is all you need, you can probably write it quicker than you can get up to speed on a library.

Community
  • 1
  • 1
Ed Staub
  • 15,480
  • 3
  • 61
  • 91