I would like to create 2 separate 1 dimensional arrays from the 2d array using the first column in the first array and the 2nd column in the 2nd array.
double[][] 2dArray = {{1,2,3,4,5,6},{1,2,3,4,5,6}}
CodePudding user response:
A 2D array is just a group of arrays nested within an array. This means that each array index is an array of items. Therefore, you can easily extract the value of the index into its own array.
double[][] my2dArray = {{1,2,3,4,5,6},{1,2,3,4,5,6}};
double[] myFirstArray = my2dArray[0];
double[] mySecondArray = my2dArray[1];
This will give you 2 arrays, each containing {1, 2, 3, 4, 5, 6}
CodePudding user response:
It could be something like this (read the comments):
double[][] my2dArray = {{1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}};
double[] myFirstArray = new double[my2dArray.length];
double[] mySecondArray = new double[my2dArray.length];
int idxCnt = 0; // new arrays index incrementer.
// Get each array in the matrix one at a time:
for (double[] ary : my2dArray) {
myFirstArray[idxCnt] = ary[0]; // Get the first column value from current inner Array.
mySecondArray[idxCnt] = ary[1]; // Get the second column value from current inner Array.
idxCnt ; // increment index for new Arrays.
// continue loop to get next array from matrix.
}
System.out.println("myFirstArray[] contains: -> " Arrays.toString(myFirstArray));
System.out.println("mySecondArray[] contains: -> " Arrays.toString(mySecondArray));
If run, the Console Window should display:
myFirstArray[] contains: -> [1.0, 7.0]
mySecondArray[] contains: -> [2.0, 8.0]