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.

3
  • Why are you traversing the whole matrix? Why not simply: for (i = 0; i < 4; i++) { b[i] = a[i][0]; }? Commented Jul 10, 2011 at 17:27
  • that is because i need to extract all the columns as separate arrays. and problem is the matrix is so big, so i want to know if there is some simpler method available. Commented Jul 10, 2011 at 17:29
  • 3
    Then please update your question to explain what you're really trying to do... Commented Jul 10, 2011 at 17:31

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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!
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.
0

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.