public static boolean sameShape(int[][] matrixA, int[][] matrixB) {
// check if # of rows is same
if (matrixA.length != matrixB.length)
return false; // error
// for each row, check if # cols is same
for (int row = 0; row < matrixA.length; row++)
if (matrixA[row].length != matrixB[row])
return false; // error
return true;
}
int[][] sum;
// first check that A and B have the same shape
if (sameShape(A, B) {
// assume all rows have same number of columns
sum = new int[A.length, A[0].length];
// compute A + B
for (int row = 0; row < A.length; row++)
for (int col = 0; col < A[row].length; col++)
sum[row][col] = A[row][col] + B[row][col];
}
else
System.out.println("Can't add matrices of different sizes");