Matrix Multiplication using Python-DecodingDevOps

Matrix Multiplication using Python

A Matrix is a rectangular array of the elements into rows and columns. Each element in a matrix array is referred to as a matrix element or entry. Matrix multiplication is a binary operation where we get a resultant matrix that is the product matrix from the product of the two matrices. we can multiply two matrices if and only if the number of columns in the first matrix is equal to the number of rows in the second matrix. we should multiply the elements of each row of the first matrix with the elements of each column of the second matrix and finally add the products.

first   = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

second  = [[10, 11, 12, 13],
     [14, 15, 16, 17],
     [18, 19, 20, 21]]

result  = [[0, 0, 0, 0],
     [0, 0, 0, 0],
     [0, 0, 0, 0]]
for i in range(len(first)):

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

        for k in range(len(second)):

            result[i][j] += first[i][k] * second[k][j]
  
for r in result:

    print(result)

STEP 1: In this step, first initialize the first matrix and initialize the second matrix by assigning some example elements and also assign a result matrix.

STEP 2: Iterate through the rows of the first matrix using the for loop by taking each element.

STEP 3: Iterate through the columns of the second matrix using the for loop by raking each element.

STEP 4:  Iterate through the rows of the second matrix using the for loop and under this loop multiply the two matrices using row and column operation.

STEP 5: Add the resultant matrix to the product matrix and print the result.

OUTPUT:

[92,98,104,110]
[218,233,248,263]
[344,368,392,416]

Leave a Reply

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