Adding three matrices in Python

Adding three matrices

In python, it’s very easy to deal with matrices due to its simple syntax and we create matrices using nested lists in python.

We simply create matrices by creating lists inside lists as follows

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

As you can see we created lists inside a list and it seems to be the same as we saw in normal mathematics.

So, now let’s take three matrices and we will add them using a simple python program

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

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

Z = [[5, 5, 5],
     [5, 5, 5],
     [5, 5, 5]]

To store the result we will use another matrix whose elements will be initialized with 0

result = [[0, 0, 0],
          [0, 0, 0],
          [0, 0, 0]]

Logic

Now let’s take a look at the logic to add the matrices which is common to add any number of matrices

# iterate through rows
for i in range(len(X)):
    # iterate through columns
    for j in range(len(X[0])):
        result[i][j] = X[i][j] + Y[i][j] + Z[i][j]
To print the result
for r in result:
    print(r)

So, the logic is to add the elements of different matrices which are having the same position in different matrices, for example, the elements in X, Y, and Z in the first row and first column are 1, 9, and 5 so these elements will be first added and will be stored at the same place inside the result matrix

Hence, the elements which we want to add should be having the same row and column in different matrices and the result will be stored in the place which has the same row and same column

Code

# Program to add three matrices using nested loop
# defining matrices using list
X = [[1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]]
Y = [[9, 8, 7],
    [6, 5, 4],
    [3, 2, 1]]
Z = [[5, 5, 5],
    [5, 5, 5],
    [5, 5, 5]]
result = [[0, 0, 0],
         [0, 0, 0],
         [0, 0, 0]]
# iterate through rows
for i in range(len(X)):
    # iterate through columns
    for j in range(len(X[0])):
        result[i][j] = X[i][j] + Y[i][j] + Z[i][j]
# printing result
for r in result:
    print(r)

Thanks for reading

Just comment if you want a post on any topic


Also read:

Share:

Author: Harry

Hello friends, thanks for visiting my website. I am a Python programmer. I, with some other members, write blogs on this website based on Python and Programming. We are still in the growing phase that's why the website design is not so good and there are many other things that need to be corrected in this website but I hope all these things will happen someday. But, till then we will not stop ourselves from uploading more amazing articles. If you want to join us or have any queries, you can mail me at admin@violet-cat-415996.hostingersite.com Thank you