-1

I want to add two matrices together and return a new matrix. Example:

matrixAdd({{1, 2, 3}, {4, 4, 4}}, {{5, 5, 6}, {0, -1, 2}})

is expected to return:

{{6, 7, 9}, {4, 3, 6}}

I can't understand why my code generates index out of bounds exception... Btw, arrays passed as parameters will always have the same dimensions so i don't need to worry about that.

public static int[][] matrixAdd(int[][] a, int[][] b) {
    int[][] matrix = new int[a.length][b.length];
    for (int r = 0; r < a.length; r++) {
        for (int c = 0; c < a[r].length; c++) {
            matrix[r][c] = a[r][c] + b[r][c];
        }
    }
    return matrix;
}
Pawel Veselov
  • 3,996
  • 7
  • 44
  • 62
kaukasar
  • 1
  • 1

3 Answers3

2

Because you use b.length as in matrix creation.

That means for your data it's like

int[][] matrix = new int[2][2];

but you need

int[][] matrix = new int[2][3];

You can use something like this

int[][] matrix = new int[a.length][a[0].length];
Community
  • 1
  • 1
Eklavya
  • 17,618
  • 4
  • 28
  • 57
0

Here is the problem

int[][] matrix = new int[a.length][b.length];

Matrix a and b both are of size 2X3. So new matrix created by them will also be of size 2X3. But declared matrix matrix is of size 2X2 as a.length & b.length both returns 2.

As you have mentioned dimension of matrix is always same, you can do following.

int[][] matrix = new int[2][3];

If it is dynamic then do following

int[][] matrix = new int[a.length][a[0].length];
Community
  • 1
  • 1
Dhiraj Sharma
  • 4,364
  • 24
  • 25
  • Thanks for the explanation. Now i understand my error - i initialized the column length after the row length, but i needed to initialize the column length after the column length with b[0].length (or a[0].length). – kaukasar May 08 '20 at 11:56
0

Try the below code:

public static int[][] matrixAdd(int[][] a, int[][] b) {
    int[][] matrix = new int[a.length][b[0].length];
    for (int r = 0; r < a.length; r++) {
        for (int c = 0; c < a[r].length; c++) {
            matrix[r][c] = a[r][c] + b[r][c];
        }
    }
    return matrix;
}
Community
  • 1
  • 1
Prog_G
  • 1,539
  • 1
  • 8
  • 22