# How to Add Two Matrices in Python

The following program demonstrates how two matrices can be added in python using the list data structure. Matrix addition works by adding corresponding entries in the matrices based on their position. The following sample program adds two 3×3 matrices, but the program can be easily modified for any size matrix. You just need to change the input data,

# matrixadd.py - Matrix addition in python # The following example adds two 3x3 matrices m1 = [ [9, 2, 2], [2, 4, 2], [9, 9, 9] ] m2 = [ [10,1,2], [4,2,1], [9,3,4] ] result = [] # start with outer list for i in range(len(m1)): result.append([]) # add the inner list for j in range(len(m1[0])): result[i].append(m1[i][j] + m2[i][j]) print(result)

Here is a step by step explanation of the program,

- Matrices are stored in two dimensional list variables.
- We create a simple empty list for the result.
- We then iterate through the matrix values. The outer loop iterates through the number of rows. The inner loop iterates through the number of columns.
- For each row iterated, we add an empty inner list for values in the result variable.
- We finally compute the sum for each corresponding elements in matrices and then append it to the inner list for each row of the result.

Following is the output from the above program,

python3 matrixadd.py

[[19, 3, 4], [6, 6, 3], [18, 12, 13]]

[[19, 3, 4], [6, 6, 3], [18, 12, 13]]