Python Program for Multiplication of Matrices

Sreemeenakshi V
3 min readJun 7, 2021

--

Language used: Python

Matrix Multiplication:

So what exactly is Matrix Multiplication?

This is basically how a matrix is multiplied.

  1. Order Matters: The order in which the two matrices are given as input affects or alters the output.
  2. Two matrices can be multiplied only when the number of columns of the first matrix is equal to the number of rows of the second matrix. The resultant matrix is in the order of number of rows of first matrix and number of columns of second matrix.
  3. It is the dot product of rows and columns. Rows of the 1st matrix with columns of the 2nd.

For Loop

In Python, the for loop is used to iterate over a sequence that can be list, tuple, string or any other iterable objects. Iterating over a sequence is called traversal.

Syntax of for loop:

for variablename in sequence:
statement(s)

Here the variablename takes the value of the item inside the sequence on each iteration. The loop continues until we reach the last item in the sequence.

Flowchart

List

A list is a set of elements that are separated by commas and enclosed within square brackets.

It can have any number of items and they may be of different types like integer, float, string etc. A list can also contain another list inside it which is referred to as a nested list.

Index operator [] is used to access an item in a list. In Python, indices start at 0.

Syntax

# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed data types
my_list = [1, "Hello", 7.7]

Description:

In Python we can implement a matrix as nested list i.e., list inside a list.

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

For example X = [[1, 2], [7, 8], [2, 4]] 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].

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).

Source Code:

Method 1:

Output 1:

[9, 12, 15]
[19, 26, 33]
[24, 33, 42]

Method 2:

Output 2:

[114, 160, 60, 27][74, 97, 73, 14][119, 157, 112, 23]

Here initially two matrices are given, X and Y which when multiplied will result in a 3*4 matrix. So a matrix named result is declared and its values are initialized as 0.

For loop is used to iterate over the conditions. First it is iterated through rows of X and then through columns of Y and finally through rows of Y. Now the values get stored in the result matrix and is displayed using print statement.

Comment lines are used in each step for easy understanding.

For any Educational Assistance, check out GUVI.

Refer: https://www.guvi.in/

--

--

No responses yet