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:
- See connected wifi passwords using Python
- Simple Text-To-Speech In Python
- GUI Calculator Using Python tkinter
- Password Generator Application
- Creating User-defined Entry Widgets
- GUI Stone Paper Scissor Game: Python
- Displaying Images in Tkinter
- GUI Age Calculator
- Changing Screen Size: Tkinter
- Simple Music Player Using Python
- Auto-Login with Python