Multiply matrices using Python

VIGNESWARAN.S
3 min readJun 5, 2021

If you are a bio maths student,don’t worry.This blog will help you .It is useful for all the students.I have used simple ENGLISH for your understand purpose.I have given clear information about MULTIPLY MATRICES.This program is in first year lab exercise for ENGINEERING students.

Aim for this program

The aim of the program to perform matrix multiplication in python.

Concepts involved

  1. Python-for loop
  2. Python-list

In python we can implement a matrix as nested list (list inside list).

we can treat each element as a row of the matrix.

For example:

X = [[1, 2], [4, 5], [3, 6]] would represent a 3x2 matrix. First row can be selected as X[0] and the element in first row, first column can be selected as X[0][0].

What is a for loop in Python?

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. …

What is a nested for loop in Python?

Loops can be nested in Python, as they can with other programming languages. A nested loop is a loop that occurs within another loop, structurally similar to nested if statements.

Algorithm for matrix multiplication

Step1:Start

Step2: input two matrix.

Step 3: nested for loops to iterate through each row and each column.

Step 4: take one resultant matrix which is initially contains all 0.

Step5:Then we multiply each row elements of first matrix with each elements of second matrix, then add all multiplied value

Step6:Stop

Flowchart

Explanation

Multiplication of two matrices X and Y is defined only if the number of columns in X is equal to the number of rows Y.

If X is a n x m matrix and Y is a m x l matrix then, XY is defined and has the dimension n x l (but YX is not defined).

# 3x3 matrix

#giving inputs for two matrix

X = [[12,7,3],

[4 ,5,6],

[7 ,8,9]]

# 3x4 matrix

Y = [[5,8,1,2],

[6,7,3,0],

[4,5,9,1]]

# result is 3x4

result = [[0,0,0,0],

[0,0,0,0],

[0,0,0,0]]

# iterate through rows of X

#using nested for loop

for i in range(len(X)):

# iterate through columns of Y

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

# iterate through rows of Y

for k in range(len(Y)):

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

for r in result:

print(r)

sample Output:

[114, 160, 60, 27]

[74, 97, 73, 14]

[119, 157, 112, 23]

Program/Source Code:

OUTPUT

FOR REFERENCE

Learn courses from GUVI in online.

here the link,

--

--