Multiplication of two Matrices in Single line using Numpy in Python


Matrix multiplication is a lengthy process where each element from each row and column of the matrixes are to be multiplied and added in a certain way. For matrix multiplication, the number of columns in the first matrix must be equal to the number of rows in the second matrix. The result matrix has the number of rows of the first and the number of columns of the second matrix.

For smaller matrices we may design nested for loops and find the result. For bigger matrices we need some built in functionality in python to tackle this. We will see both approaches below.

Using for Loop

We take two matrices of dimension 2x3 and 3x2 (rows x columns). The result of matrix multiplication is a 2x2 matrix. We have a nested for loop designed to go through the columns of A and rows of B and add the products of the values in those rows and columns.

Example

 Live Demo

#matrix A with 2 rows
A = ([5,10,15],[20,25,30])

#matrix B with 2 columns
B = ([4,8],[12,10],[14,16])

result = [[0 for x in range(2)] for y in range(2)]

for i in range(len(A)):
   # iterate through columns of A
   for j in range(len(B[0])):
      # iterate through rows of B
      for k in range(len(B)):
         result[i][j] += A[i][k] * B[k][j]
for r in result:
   print(r)

Output

Running the above code gives us the following result:

[350, 380]
[800, 890]

Using Numpy

Numpy has a in-built function named dot, that carries out the matrix multiplication. Our number of lines of program becomes very less and the syntax is also very simple.

Example

 Live Demo

import numpy as np

#matrix A
matrix_A = ([5,10,15],[20,25,30])

#matrix B
matrix_B = ([4,8],[12,10],[14,16])
result = np.dot(matrix_A,matrix_B)

# Result
print(result)

Output

Running the above code gives us the following result:

[[350 380]
[800 890]]

Updated on: 07-Jan-2020

512 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements