Another example of practicing nested loops is a python program to add two matrices.
Here, I’ll show the code and explain how to implement such a program.
A general approach to adding two matrices
When you add two matrices, you must add the numbers in the same position of each matrix, and that gives you the value of the resulting matrix. See an example below. Notice that the matrices must have the same dimension.
Also, in Python, we can model a matrix as an array of arrays. Each array (or row) is an array that can have a different size. Notice that in a matrix, all rows must have the same size or number of elements.
What we should do is create a nested loop, so we can go through all the elements of each matrix.
The first loop will go through the rows and the second one through the columns.
Once we have access to the specific elements of each matrix, we add them.
That’s it.
Python program for adding matrices
First, we are going to create a function that initializes a matrix.
def initialize_matrix(rows, cols):
m = [[0 for _ in range(cols)] for _ in range(rows)]
return m
Notice that there are several ways of initializing a matrix. However, in all cases, you need to go through each element of the matrix. Can you see the nested loops?
Now, let’s implement the function that will add the matrices.
def add_matrices(m1, m2):
rows = len(m1)
cols = len(m1[0])
result = initialize_matrix(rows, cols)
for row in range (rows):
for col in range(cols):
result[row][col] = m1[row][col] + m2[row][col]
return result
As you can see, the implementation is straightforward.
As for all operations in a matrix that you need to consider all the elements, you must use nested loops.
We first calculate the rows and columns. Remember here we are assuming all columns have the same number of elements, otherwise, it won’t be a matrix.
Then, we initialize the matrix that will have the results.
Inside the nested loops, we just update the value of each element in the matrix by summing the values in the same position on both matrices.
An extra step we can do, is to create a function that will print the matrix.
def print_matrix(m):
rows = len(m)
cols = len(m[0])
for row in range (rows):
for col in range(cols):
print (m[row][col], end=' ')
print()
Again, this can be done in different ways. You can play with the code below to make the printed matrix looks nicer.
I always like to have a specific function that prints the results. In this case, is useful, because you can even print the two matrices that you added. So, the user can not only see the result but the input.
Also, below is the code of the main program that you can use to test my implementation.
if __name__=='__main__':
print('Python console program to add two matrices')
matrix1 = [
[1,2,3],
[4,5,6],
[7,8,9]
]
matrix2 = [
[1,2,3],
[4,5,6],
[7,8,9]
]
result = add_matrices(matrix1, matrix2)
print_matrix(result)
H@ppy coding!
Related posts: