- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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.

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

Running the above code gives us the following result:

[350, 380] [800, 890]

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.

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)

Running the above code gives us the following result:

[[350 380] [800 890]]

- Related Questions & Answers
- Multiplication of two Matrices using Numpy in Python
- Multiplication of two Matrices using Java
- How to Multiply Two Matrices using Python?
- How to Add Two Matrices using Python?
- Python program multiplication of two matrix.
- Python program to multiply two matrices
- Swap two variables in one line in using Python?
- Python Pandas and Numpy - Concatenate multiindex into single index
- How to multiply two matrices using pointers in C?
- Compare two int arrays in a single line in Java
- Compare two short arrays in a single line in Java
- Compare two double arrays in a single line in Java
- Compare two long arrays in a single line in Java
- Compare two float arrays in a single line in Java
- Compare two char arrays in a single line in Java

Advertisements