HomePythonPython Program to Add Two Matrices Using Multi-dimensional Arrays

Python Program to Add Two Matrices Using Multi-dimensional Arrays

In this python tutorial, you will learn how to Add Two Matrices Using Multi-dimensional Arrays with for loop of the python programming language.

How to Add Two Matrices Using Multi-dimensional Arrays?

Let’s take a look at the source code,  here the values are assigned in the code, the for loop carry out the function.

RUN CODE SNIPPET
#Python Program to Add Two Matrices Using Multi-dimensional Arrays

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

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

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:

[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
  1. At first, we enter the values of two matrices with three rows and three columns. We assign those values to the variables X and Y. The values are enclosed within square brackets and closed on the whole with the same.
  2. Then we declare the variable result with the condition [X[i][j] + Y[i][j]  after which we declare an for loop where the range for the variable i is (len(X[0]))
  3. We declare another for loop where the range for the variable j is (len(X)), this whole statement in enclosed in a square braces.
  4. We declare a final for loop where the result is the variable j, following that we give a print function which will display the values stored in the variable r

NOTE:

  • The print function is used to display the value, it prints the specified message to the screen
  •  The For loops are used to loop through an iterable object and perform the same action for each entry.
  • The len() is a built function  used to calculate the length of any iterable object

Leave a Reply

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...