Related Tags

matrix
data structures
communitycreator

# How to subtract matrices

abhilash

### Problem overview

Given two matrices, subtract the two matrices from one another. The resulting matrix should have the difference 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 2 - Matrix 1 =

[[9, 18, 27],
[36, 45, 54]
[63, 72, 81]]


### Algorithm

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

Subtracting two matrices is taking the difference of the corresponding elements of the two matrices. We can use a loop to access the corresponding elements of the matrices and place the difference of the elements at the relevant positions in the new result matrix.

The pseudo-code of the algorithm is as follows:

for i from 0 to numRows:
for j from 0 to numCols:
diffMatrix[i][j] = matrix2[i][j] - matrix1[i][j]


Notations:

• numRows - number of rows
• numCols - number of columns
• diffMatrix - resultant matrix that holds the difference between the two matrices

The algorithm is explained for 2x2 dimension matrices in the slides below.

20 - 2 = 18
1 of 4

### Code

import java.util.Arrays;

public class Main {

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

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 = subtract(numRows, numCols, matrix1, matrix2);
System.out.println("Matrix 1:");
printMatrix(matrix1);
System.out.println("Matrix 2:");
printMatrix(matrix2);
System.out.println("The difference between above matrices is: ");
printMatrix(result);

}
}

RELATED TAGS

matrix
data structures
communitycreator

CONTRIBUTOR

abhilash
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time 