Python program for matrix addition

Matrix addition is a way of adding two matrices (a rectangular array of numbers) together. The matrices need to be of the same size, which means they must have the same number of rows and columns.

To add matrices together, you simply add the corresponding elements in each matrix. For example, if we have two matrices A and B:

A = [ [2, 3], [4, 5] ] B = [ [1, 1], [2, 2] ]

We can add them together by adding the corresponding elements:

A + B = [ [2+1, 3+1], [4+2, 5+2] ] = [ [3, 4], [6, 7] ]

So, the formula for adding two matrices is:

A + B = [ [a11+b11, a12+b12], [a21+b21, a22+b22] ]

where A and B are the two matrices, a11, a12, a21, a22 are the elements of matrix A, b11, b12, b21, b22 are the elements of matrix B, and the “+” sign represents the addition operation.

Method 1: Matrix addition using List comprehension

In the List comprehension method, We create a new matrix by iterating over the corresponding elements of two matrices and adding them in a single line.

# Program to add two matrices using list comprehension

X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]

Y = [[5,8,1],
    [6,7,3],
    [4,5,9]]

# List comprhension
result = [[X[i][j] + Y[i][j] for j in range(len(X[0]))] for i in range(len(X))]

for r in result:
    print(r)

Output

[17, 15, 4]
[10, 12, 9]
[11, 13, 18]

Method 2: Using Nested Loop

In the nested loops method, we have two for loops outer and inner loops. We add the corresponding elements of the matrices using the index position and store the results in a new matrix.

# Program to add two matrices using nested loop

# Define matrices
matrix1 = [    [12, 7, 3],
    [4, 5, 6],
    [7, 8, 9]
]

matrix2 = [    [5, 8, 1],
    [6, 7, 3],
    [4, 5, 9]
]

# Initialize the result matrix with zeros
result_matrix = [    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0]
]

# iterate through rows
for i in range(len(matrix1)):
   # iterate through columns
   for j in range(len(matrix1[0])):
       result_matrix[i][j] = matrix1[i][j] + matrix2[i][j]

# Print the result matrix
print("Result Matrix: ")
for row in result_matrix:
   print(row)

Output

Result Matrix: 
[17, 15, 4]
[10, 12, 9]
[11, 13, 18]
> 

Method 3: Using Numpy Library

In this example, we use a library called NumPy to add matrices. We create NumPy arrays from the given matrices and then add them using the “+” operator. This method is faster and more efficient than the other two methods.

# Program to add two matrices using numpy library

import numpy as np

X = np.array([[12,7,3],
              [4 ,5,6],
              [7 ,8,9]])

Y = np.array([[5,8,1],
              [6,7,3],
              [4,5,9]])

result = X + Y

print(result)

Output

[[17 15  4]
 [10 12  9]
 [11 13 18]]> 

Conclusion

Adding matrices is a process of adding the corresponding elements of two matrices. There are different methods to add matrices like nested loops, List comprehension, and NumPy method.

Leave a Comment