Matrix Addition & Substraction
Part of the Logic & Flow section of Coddy's Java journey — lesson 5 of 59.
To add or subtract two matrices, they must have the same dimensions (i.e., the same number of rows and columns). The operation is performed element-wise, meaning you add or subtract corresponding elements in each matrix.
For example:
Matrix A:
1 2
3 4
Matrix B:
5 6
7 8
A + B:
(1+5) (2+6)
(3+7) (4+8)
Result:
6 8
10 12Matrix multiplication is more complex and it will be covered in a later section.
Challenge
EasyCreate a method named subMatrices that takes two 2D arrays (matrices) as input and return their difference as a new 2D array.
Cheat sheet
To add or subtract matrices, they must have the same dimensions. The operation is performed element-wise on corresponding elements.
Example of matrix addition:
Matrix A:
1 2
3 4
Matrix B:
5 6
7 8
A + B:
(1+5) (2+6)
(3+7) (4+8)
Result:
6 8
10 12For incompatible dimensions, return new int[0][0] (an empty array).
Try it yourself
// Write your code only inside the class. Do not write main() or any code outside this class.
class SubMatrices {
public static int[][] subMatrices(int[][] matrix1, int[][] matrix2) {
// Write your code here
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap