CC-4 : Add 2 matrices.
Description:
Given 2 matrices: mat1 and mat2, add the individual elements of the matrix and return a matrix with the sum of individual elements.
Test cases and expected outputs:
| Input1 | Input2 | Expected outputs |
|---|---|---|
| mat = { {1,1,4,1}, {9,9,3,0}, {2,1,4,3}} |
mat = { {1,1,1,1}, {2,2,2,2}, {3,3,3,3}} |
2,2,5,2, 11,11,5,2, 5,4,7,6, |
| mat= { {-1,-1,}, {4,5}, {3,1}} |
mat= { {1,7}, {8,2}, {6,4}} |
0,6, 12,7, 9,5, |
Pseudocode:
| The java method should accept following input parameters: mat1 (integer matrix), mat2 (integer matrix). |
| Initialise a matrix retMat for storing the matrix with sum of respective elements of the input matrices. |
| Iterate through mat1 using a for loop, using variable rIdx as loop counter. Loop variable rIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till rIdx < mat1.length:
Iterate through mat1 using a for loop, using variable cIdx as loop counter. Loop variable cIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till cIdx < mat1[0].length:
Set retMat[rIdx][cIdx]=mat1[rIdx][cIdx]+mat2[rIdx][cIdx].
|
| Once above loops are completed, return retMat as it contains sum of individual elements of mat1 and mat2. |
Code:
public int[][] matArrayAddition(int[][] mat1, int[][] mat2) throws Exception{
int[][] retMat=new int[mat1.length][mat1[0].length];
for (int oIdx=0; oIdx < mat1.length; oIdx++) {
for (int iIdx=0; iIdx < mat1[0].length; iIdx++) {
retMat[oIdx][iIdx]=mat1[oIdx][iIdx]+mat2[oIdx][iIdx];
}
}
return retMat;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |