Python Matrix Multiplication

Here you will get program for python matrix multiplication.

If we want to multiple two matrices then it should satisfy one condition. We need to check this condition while implementing code without ignoring.

Amxn x Bpxq then n should be equal to p. Then only we can multiply matrices. Now we will see how to multiply two matrices using python nested list matrix representation.

Python Matrix Multiplication

Below is python program to multiply two matrices.

def print_matrix(matrix):
	for i in range(len(matrix)):
		for j in range(len(matrix[0])):
			print("\t",matrix[i][j],end=" ")
		print("\n")

def main():
	m = int( input("enter first matrix rows"));
	n = int( input("enter first matrix columns"));
	p = int( input("enter second matrix rows"));
	q = int( input("enter second matrix columns"));
	if( n != p):
		print ("matrice multipilication not possible...");
		exit();
	
#declaration of arrays
	array1=[[0 for j in range  (0 , n)] for i in range (0 , m)]
	array2=[[0 for j in range  (0 , q)] for i in range (0 , p)]
	result=[[0 for j in range  (0 , q)] for i in range (0 , m)]

#taking input from user
	print ("enter first matrix elements:" )
	for i in range(0 , m):
		for j in range(0 , n):
			array1[i][j]=int (input("enter element"))
	print ("enter second matrix elements:")
	for i in range(0 , p):
		for j in range(0 , q):
			array2[i][j]=int(input("enter element"))
	print ("first matrix")
	print_matrix(array1)
	print ("second matrix")
	print_matrix(array2)
	
#for multiplication
    # i will run throgh each row of matrix1
	for i in range(0 , m):
	# j will run through each column of matrix 2
		for j in range(0 , q):
		# k will run throguh each row of matrix 2
			for k in range(0 , n):
				result[i][j] += array1[i][k] * array2[k][j]
				
				
#printing result
	print ( "multiplication of two matrices:" )
	print_matrix(result)
	
main()

Output

Python Matrix Multiplication

8 thoughts on “Python Matrix Multiplication”

  1. Senthil Selvan

    Hi. I am new to python and i don’t understand why you have used end=” ” in this line
    print(“\t”,matrix[i][j],end=” “)

    also i tried the same prgm and without the end ” ” [because i got an error saying that end is not declared] and my o/p is always printed 1 element per line and not in matrix format. So what should i do ??

  2. URVASHI U Dhoot

    This code does not check if 2 matrices can even be multiplied in the first place.
    They can be multiplied only when No of Rows of 1st matirx == Columns of 2nd matrix

Leave a Comment

Your email address will not be published. Required fields are marked *