# How to do Matrix Multiplication in Python – Codewars

You may have Multiplied matrix in your linear algebra class but you know how to multiply to the matrix in python. In Today’s post, we will go through the process of How to do Matrix Multiplication in Python from scratch.

Codewars Python in its 5kyu Kata has given us a problem to Multiply two Matrix.

#### Question

The Question is Available HERE I have copied the question below too.

Write a function that accepts two square (NxN) matrices (two-dimensional arrays), and returns the product of the two. Only square matrices will be given.

How to do Matrix Multiplication in Python:

We are given two matrices, A and B, of size 2×2 (note: tests are not limited to 2×2). Matrix C, the solution, will be equal to the product of A and B. To fill in cell [0][0] of matrix C, you need to compute: A[0][0] * B[0][0] + A[0][1] * B[1][0].

More general: To fill in the cell [n][m] of matrix C, you need to first multiply the elements in the nth row of matrix A by the elements in the mth column of matrix B, then take the sum of all those products. This will give you the value for cell [m][n] in matrix C.

#### Example

A B C
|1 2| x |3 2| = | 5 4|
|3 2| |1 1| |11 8|
﻿

Detailed calculation:

C[0][0] = A[0][0] * B[0][0] + A[0][1] * B[1][0] = 13 + 21 = 5
C[0][1] = A[0][0] * B[0][1] + A[0][1] * B[1][1] = 12 + 21 = 4
C[1][0] = A[1][0] * B[0][0] + A[1][1] * B[1][0] = 33 + 21 = 11
C[1][1] = A[1][0] * B[0][1] + A[1][1] * B[1][1] = 32 + 21 = 8

# include

using namespace std;

std::vector> matrix_multiplication(std::vector> &a, std::vector> &b, size_t n){
// TODO: Return the result of A × B in the form of an n × n matrix
// NOTE: Please allocate and return matrix C
vector> temp;
vector t;
for(int i = 0; i < n; i++){
t.push_back(0);
}
for(int j =0; j < n; j++){
temp.push_back(t);
}
for(int k =0; k < n; k++){
for(int i = 0; i < n; i++){
for(int j =0; j < n; j++){
temp[k][i] += a[k][j] * b[j][i];
}
}
}
return temp;
}

#### READ MORE

Python-related posts Visit HERE

C++ related posts Visit HERE

Databases related posts Visit HERE

Data Structures related posts visit HERE

Algorithms related posts visit HERE

Data Science related posts visit HERE