How to Sum up Two Matrices in Python


In this example we will show how to use loops to add two 3×3 matrices and return the sum matrix with Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

# Define two matrix
X = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]
Y = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

# Initialize sum matrix
sum = [[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]]

# loop through rows
for i in range(len(X)):
    # loop through column
    for j in range(len(X[0])):
        sum[i][j] = X[i][j] + Y[i][j]

# print out results
print('Sum of X and Y:')
for r in sum:
    print(r)

Output:

Sum of X and Y:
[2, 4, 6]
[8, 10, 12]
[14, 16, 18]
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments