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.

A_{mxn }x B_{pxq }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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
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**

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 ??

I have the same problem

but change the python format

to print in same line