Add Two Matrices in Python

(Last Updated On: 26/09/2023)

Matrix addition is a fundamental operation in linear algebra and plays a crucial role in various mathematical and computational tasks. We can easily add two matrices in Python using for loops and nested lists. This blog will guide you through the step-by-step process, using a simple and concise Python program.

We will examine the logic and operations behind the code, providing a clear understanding of how matrix addition works. Additionally, we will discuss the benefits and limitations of using for loops for matrix addition, as well as alternative approaches.

Whether you are new to matrices or seeking a refresher, this tutorial will equip you with the knowledge and practical implementation of matrix addition. So, let’s dive in and write a Python program to add two matrices using for loop.

Python Program to Add Two Matrices Using for Loop

# Python Program to Add Two Matrices Using for Loop

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

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

res = [[0, 0, 0],
          [0, 0, 0],
          [0, 0, 0]]

# rows iteration
for i in range(len(X)):
    # columns iteration
   for j in range(len(X[0])):
       res[i][j] = X[i][j] + Y[i][j]

for i in res:
   print(i)

Code Explanation

  • Initialising the Matrices

First, we create two matrices, X and Y, represented as nested lists, with their respective values. We also create a result matrix, res, filled with zeros to store the sum of the matrices.

  • Performing Matrix addition

We use nested for loops to iterate over the rows and columns of the matrices. The outer loop iterates over the rows of the matrices, accessed using the range(len(X)) expression, while the inner loop iterates over the columns of the matrices, accessed using the range(len(X[0])) expression.

During each iteration, the code accesses the elements of matrix X and Y at the current row and column indices and adds them together. This sum is stored in the corresponding position of the result matrix, res, using the assignment statement res[i][j] = X[i][j] + Y[i][j].

  • Printing the result

After the matrix addition is complete, we iterate over the rows of the result matrix using a for loop. During each iteration, the print(I) statement, where i represents the current row, is used to display the elements of the current row.

Output:

This output represents the resulting matrix after adding the corresponding elements from matrices X and Y. The result is:

[9, 9, 9]
[9, 9, 9]
[9, 9, 9]

Multiple Ways to Achieve Matrix Addition

In Python, there are multiple ways to achieve matrix addition. These alternatives are:

  • List Comprehension: It provides a concise and elegant way to perform matrix addition using a single line of code.
  • Numpy Library: It is a powerful library for numerical computing which provides efficient and optimized functions for matrix operations, including matrix addition.

The for-loop method shown above is a simple and beginner-friendly approach that provides a clear and step-by-step implementation that is easy to debug. This method does not require any external libraries, at the same time allows you to have more control over the iteration process, making it easier to implement additional logic or conditions if needed.

In this Python code, we understood how to add two matrices using a for loop. By iterating over the rows and columns of the matrices using nested for loops, the elements of each matrix were added together, and stored in a result matrix. Finally, the code prints the resulting matrix, which represents the sum of the original matrices.

The use of a for loop provides a simple and efficient approach to performing matrix addition. This concept is fundamental in various applications, such as mathematical calculations, data manipulation, and image processing.

Some FAQs Based on the Above Matrix Addition Program

Why do we use nested for loops?

Nested for loops are used to iterate over both the rows and columns of the matrices simultaneously. The outer loop iterates over the rows, while the inner loop iterates over the columns. This allows us to access and operate on each element of the matrices.

What does the expression range(len(X)) do?

The expression range(len(X)) generates a sequence of numbers from 0 to the number of rows in the matrix X. It determines the number of iterations for the outer loop, ensuring that we iterate over all the rows of the matrices.

Why do we initialize the result matrix with zeros?

Initializing the result matrix with zeros ensures that we start with a clean slate, as we want to compute the sum of the matrices. By setting all values to zero, we avoid any potential interference from previous calculations.

What happens if the matrices have different dimensions?

Matrix addition is only defined for matrices of the same dimensions. If the matrices have different dimensions, the addition operation cannot be performed, and an error may occur.

How can I modify the code to handle matrices of different dimensions?

To handle matrices of different dimensions, you would need to add additional checks before performing the addition. These checks would ensure that the matrices have the same number of rows and columns.

About The Author

Leave a Reply