Here you may get the program for python matrix operation.
If we would like to multiply 2 matrices then it ought to satisfy one condition.
we’d like to see this condition whereas implementing code while not ignoring.
Amxn x Bpxq then n would be adequate p. Then solely we will multiply matrices. currently we are going to see the way to multiply 2 matrices mistreatment python nested list matrix illustration.
Python Matrix Multiplication Program
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()
Upper is the python program to multiply 2 matrices.
Output
enter first matrix rows2
enter first matrix columns2
enter second matrix rows2
enter second matrix columns2
enter first matrix elements:
enter elementl
enter element2
enter element3
enter element4
enter second matrix elements:
enter elementl
enter element2
enter element3
enter element4
first matrix 1 2
3 4
second matrix 1 2 3 4 multiplication of two matrices:
7 10
15 22