user3086819
user3086819

Reputation: 107

extending two 2D Arrays into a larger one

I have two java 2D arrays(array1 and array2), both of type Double which I would like to join together. array1 and array2 are n-by-d matrices. the n-rows for each array can vary from eachother but the d-columns are always the same. The question is: i have to concatenate array2 after the first one.(at best into the new outputMatrix)

Example:

array1:

2 3
6 5
4 7

array2:

1 5
3 7

Output Array (n-array1 + n-array2)-by-d:

2 3 
6 5 
4 7 
1 5
3 7 

My idea was to copy array1 into the outputMatrix, and then fill the continuation of it with array2.

My Java code for merging the two arrays(that are already implemented) looks like:

private static double[][] outputMatrix ;
outputMatrix = new double[array1.length+array2.length][array1[0].length];  

for (int column = 0; column < array1[0].length; column++) { 
    for (int row = 0; row < (array1.length); row++) {       
        outputMatrix[row][column] = array1[row][column];
    }
}

for (int column = 0; column < array1[0].length; column++) { 
        for (int row = array1.length; row < (array1.length+ array2.length); row++) {    
            outputMatrix[row][column] = array2[row][column]; //error here as array2 starts iterating at field [4][0] which isnt defined in the example
        }
}

Upvotes: 0

Views: 117

Answers (2)

timtour97
timtour97

Reputation: 222

So what's happening is that when you are trying to transfer the data from the second array into the outputMatric variable, you go out of bounds in the second array (array2). This is due to the fact that you're outputMatrix is trying to put a value at [array1.length + row][array1.length + column] and the second array isn't as big as that one. On top of that, your row index is wrong, you need to add the array1 length to make up for it or start the for loop's row variable at that spot. I elected just to add the length into the storing of the variable. So, you should make your code:

outputMatrix[row + array1.length][column] = array2[row - array1.length][column - array1[0].length];

Upvotes: 1

Eran
Eran

Reputation: 393896

Your indices are wrong.

Should be

for (int column = 0; column < array1[0].length; column++) { 
    for (int row = 0; row < array2.length; row++) {    
        outputMatrix[row+array1.length][column] = array2[row][column]; 
    }
}

since array2 has indices from 0 to array2.length-1.

Upvotes: 4

Related Questions