I'm trying to do a few things with multidimensional arrays. I'm new to Java and not an excellent programmer, and I couldn't find anything else on the internet about this topic, so I thought I'd ask here.
Essentially I'm making a method that will add the values of two multidimensional integer arrays together to create a third multidimensional array. This is identical to matrix addition in the cases where the multidimensional arrays ARE matrices (e.g. two 2x3 arrays added together), but not so if I have a multidimensional array with variable row lengths. So far the method I have is this:
public static int[][] addMDArray(int[][] a, int[][] b)
{
boolean columnequals = true;
for (int row = 0; row < a.length; row++)
{
if (a[row].length != b[row].length)
{
columnequals = false;
}
}
if (columnequals == false || a.length != b.length)
System.out.println("The arrays must have the same dimensions!");
else
{
int[][] sum = new int[a.length][a[0].length];
for (int row = 0; row < a.length; row++)
{
for (int column = 0; column < a[row].length; column++)
sum[row][column] = a[row][column] + b[row][column];
}
return sum;
}
return null;
}
As I said, this works with MD arrays without variable row lengths; however, with the exception of the first part that checks that they have the same dimensions, this method will not work with two arrays like this:
int[][] g = {{2, 1}, {3, 5, 4}, {5, 7, 7}};
int[][] d = {{1, 2}, {3, 4, 5}, {5, 6, 7}};
The issue I'm running into is that I can't declare the "sum" MD array without specifying dimensions... Is there a way to create the sum array in the for loop itself? I feel like this would be the simplest solution (if possible), but otherwise I don't know what else to try.
Any help would be appreciated!
System.arraycopy()After creating a new matrix with the calculated height and width. Check this code out that I wrote to alter the size of a matrix:MatrixUtils.java