A Python Program To Add and Multiply Two Matrices


Python Program To Add and Multiply Two Matrices


In this python tutorial, we will learn how to make a program to add and multiply two matrices. First we will learn about How to add Matrices. we will create Two-dimensional list (arrays) for matrices.

let's start with adding two matrices.


Matrix Addition

First, we initialize two matrices A and B. Then, we create a third matrix (result) which will store the result of the addition of the two matrices. To do additions we have to run for loop.

First of all, for loop has to be run inside the row. Then irritate inside all the columns. So for this, we are going to use the length len() function here.

So now we have to put some elements inside both the Matrices. Because these elements are inside the list, we need to separate them with commas. Now both of our Matrices are ready. Now we have to get their additions.

To get the result we will create a variable named result. And inside this variable, we'll set all the values to zero for now. Then, we add the corresponding elements in the two matrices and store it in the result matrix. In the last we print the result.

A = [[1,5,8],
     [4,6,7],
     [7,2,3]]
B = [[5,8,6],
     [9,8,6],
     [4,8,9]]
result = [[0,0,0],
          [0,0,0],
          [0,0,0]]

for i in range(len(A)):
	for j in range(len(A[0])):
		result[i][j] = A[i][j] + B[i][j]

for r in result:
	print (r)

Output

[6, 13, 14]
[13, 14, 13]
[11, 10, 12]

Matrix Multiplication

our first matrix will be of 3 × 3 and our second matrix will be of 3 × 4. In this also we will keep the elements in the form of list.

In this, we have to remember that the number of columns in the first matrix should be equal to the number of rows in the second matrix. And now we will put for loop in this also.

Fetch/Retrieve data and records From MySQL Database in Laravel 9

Then, we add the elements that we got from the matrix multiplication to the result matrix. If we print it directly, then in that case we will only get the result in plain list but the elements will be solved.

A = [[9,5,7],
     [2,8,7],
     [7,2,7]]
B = [[5,6,6,8],
     [2,4,6,4],
     [8,5,9,7]]
result = [[0,0,0,0],
          [0,0,0,0],
          [0,0,0,0]]
for i in range (len(A)):
	for j in range(len(B[0])):
		for k in range (len(B)):
			result[i][j] += A[i][k] * B[k][j]

for i in result:
	print (i)

Output

[111, 109, 147, 141]
[82, 79, 123, 97]
[95, 85, 117, 113]

Thank you for taking your valuable time to read this article. we hope you enjoyed it.

Connect With Us

we would like to keep in touch with you..... Register Here.

JOIN US JOIN TELEGRAM