Matrix Multiplication in python

              Matrix multiplication can be done by multiplying each row with each column. It can be done when the rows of first matrix and column of second matrix should be equal.

Let us implement the matrix multiplication as follows.

This can be done by two ways.

  • Using Numpy
  • Using Lists

Using Numpy:

              This program uses Numpy functions dot(),@ to generate matrix multiplication.

Code:

import numpy as np1

# Define two matrices

X = np1.array([[2, 3],

              [4, 1]])

Y = np1.array([[8, 6],

              [7, 5]])

# Matrix multiplication

Z = np1.dot(X, Y)   # Method 1

A = X @ Y          # Method 2 (Python 3.5+)

print("Matrix Multiplication Using np.dot:\n", Z)

print("Matrix Multiplication Using @ operator:\n", A)

Output:

Matrix Multiplication Using np.dot:

 [[37 27]

 [39 29]]

Matrix Multiplication Using @ operator:

 [[37 27]

 [39 29]]

Using Lists:

              This program uses loops to generate the matrix multiplication.

# Delare 2 matrix with values

X = [[2,  4],

     [1, 3]]

Y = [[6, 5],

     [8, 7]]

# Make the result matrix with values as 0

result = [[0, 0],

          [0, 0]]

# Process of Matrix multiplication

for i in range(len(X)):

    for j in range(len(Y[0])):

        for k in range(len(Y)):

            result[i][j] += X[i][k] * Y[k][j]

print("Here is the Matrix Multiplication:\n", result)

Output:

Here is the Matrix Multiplication:

 [[44, 38], [30, 26]]

Hope, these Python programs to implement Matrix Multiplication was useful to you.Keep Coding!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

Employee record management in C

Java script – conditional statement