Related Tags

matrix
data structures
communitycreator
java

# How to add two matrices

abhilash

### Problem statement

In this shot I will explain what to do if you are given two matrices and must add the two matrices. The resulting matrix should have the sum of the corresponding elements of the two matrices.

### Example

• Matrix 1
[[1, 2, 3],
[4, 5, 6]
[7, 8, 9]]

• Matrix 2
[[10, 20, 30],
[40, 50, 60]
[70, 80, 90]]


### Result

Matrix 1 + Matrix 2 =

[[11, 22, 33],
[44, 55, 66]
[77, 88, 99]]


### Algorithm

The mandatory condition for adding two matrices is that the dimension of the two matrices should be the same.

Adding two matrices means adding their corresponding elements. We can use a for loop where we access the corresponding elements of the matrices and place the sum of the elements at the relevant positions in the new resultant matrix.

The Pseudo-Code of the algorithm is as follows:

for i from 0 to numRows:
for j from 0 to numCols:
sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j]

1 of 10

### Code

import java.util.Arrays;

public class Main {

private static int[][] add(int numRows, int numCols, int[][] matrix1, int[][] matrix2) {
int[][] sumMatrix = new int[numRows][numCols];
for(int i=0;i < numRows; i++){
for(int j=0; j < numCols; j++) sumMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
return sumMatrix;
}

private static void printMatrix(int[][] matrix){
for(int[] row: matrix)
System.out.println(Arrays.toString(row));
}

public static void main(String[] args) {
int[][] matrix1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

int[][] matrix2 = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};

int numRows = 3;
int numCols = 3;

int[][] result = add(numRows, numCols, matrix1, matrix2);
System.out.println("Sum Matrix is: ");
printMatrix(result);

}
}

RELATED TAGS

matrix
data structures
communitycreator
java

CONTRIBUTOR

abhilash
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time