GoCoding.org

Program to multiply two matrices and print the result using Python

by | Mar 26, 2021 | Python Programs

Introduction

In this section of programming, our task is to perform the multiplication of two matrices and print the resultant. Remember the multiplication of (n x m) and (m x l) matrix will produce the matrix of size (n x l).

Program to multiply two matrices and print the result

Program

import numpy as nump
X = [ [0,1,0], [1,2,7], [3,4,5] ]
Y = [ [9,4,2], [0,0,1], [8,6,0] ]
result1 = [ [0,0,0], [0,0,0], [0,0,0] ]
result2 = [ [0,0,0], [0,0,0], [0,0,0] ]
# Using loop
for i in range(len(X)):
    for j in range(len(Y[0])):
        for l in range(len(Y)):
            result1[i][j] += X[i][j] * Y[l][j]
print("Multiplication using loop:")
for val in result1:
    print(val)


# Using vector method
result2 = nump.dot(X,Y)
print("Multiplication using vector method:")
for val1 in result2:
    print(val1)

 

Output

Program to multiply two matrices and print the result using Python

Explanation

In the above python code, we have used nested for loop and vector method to find the multiplication of two matrices.

The nested loop will iterate over each row and column of the matrix and perform the corresponding multiplication. Whereas, the numpy has in-built dot() function which directly computes the dot product of the matrix and produces the result.

0 Comments

Submit a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.