how to subtract two matrices in python

Solutions on MaxInterview for how to subtract two matrices in python by the best coders in the world

showing results for - "how to subtract two matrices in python"
Sakina
06 Feb 2018
1matrix1 = [[0, 1, 2], 
2           [3, 5, 5], 
3           [6, 7, 8]]
4
5matrix2 = [[1, 2, 3], 
6           [4, 5, 6], 
7           [7, 8, 9]]
8
9#output = [[-1, -1, -1], 
10		# [-1, 0, -1], 
11        # [-1, -1, -1]]
12
13def subtractTheMatrix(matrix1, matrix2):
14    matrix1Rows = len(matrix1)
15    matrix2Rows = len(matrix2)
16    matrix1Col = len(matrix1[0])
17    matrix2Col = len(matrix2[0])
18
19    #base case
20    if(matrix1Rows != matrix2Rows or matrix1Col != matrix2Col):
21        return "ERROR: dimensions of the two arrays must be the same"
22
23    #make a matrix of the same size as matrix 1 and matrix 2
24    matrix = []
25    rows = []
26
27    for i in range(0, matrix1Rows):
28        for j in range(0, matrix2Col):
29            rows.append(0)
30        matrix.append(rows.copy())
31        rows = []
32
33    #loop through the two matricies and the subtraction should be placed in the
34    #matrix
35    for i in range(0, matrix1Rows):
36        for j in range(0, matrix2Col):
37            matrix[i][j] = matrix1[i][j] - matrix2[i][j]
38            
39    return matrix
40
41
42
43print(subtractTheMatrix(matrix1, matrix2))
44