Write a Program in python to multiply two matrices.

Example:

A matrix in python can be represented using a nested list. For example m1 = [[8,1], [2,1]] is matrix with 2 rows and 2 columns. The value of len(m1) is the number of rows and len(m1[0]) is the number of columns.

In the nested list the value at m1[i][j] represents an element at the ith row and jth column.

Also, the important point to note before starting the multiplication is that matrix multiplication is only possible when the number of columns of the first matrix is equal to the number of rows of the second matrix and the order of the resultant matrix is the number of rows of the first matrix and number of columns of the second matrix.

Matrix multiplication in C

Knowing all these let’s write the code in python to multiply matrices implementing the standard rule in methematics.

Method 1: Matrix multiplication using Nested Loop

Recommended:

Output

Method 2: Matrix Multiplication using List Comprehension

This method is the modified form of the above program. The only difference is that the nested loop is replaced by the list comprehension technique in python.

Output

The use of list comprehension may be a little difficult to understand but if looked carefully you will notice that it is the simplified version of nested ‘for loop’.

If you have any doubts or suggestions then please comment below.

Leave a Reply