Skip to main content

Two Matrix Multiplication

Matrix multiplication is a fundamental operation in linear algebra and plays a crucial role in various fields such as computer graphics, engineering, physics, and more. It involves multiplying two matrices to produce a new matrix. Each element in the resulting matrix is obtained by taking the dot product of a row from the first matrix and a column from the second matrix.

matrix multiplication formula

Problem Statement

The problem is to perform matrix multiplication for two given matrices, matrix A and matrix B. The goal is to compute the resulting matrix C, where C[i][j] is the dot product of the i-th row of matrix A and the j-th column of matrix B.


Let's consider two matrices A and B:

Matrix A:

1  2  3
6  1  2
5  4  3

Matrix B:

3  1  3
1  1  2
2  2  3

The resulting matrix C, denoted as (A) x (B), is:

11  9  16
23  11 26
25  15 32

Idea to Solve the Problem

To perform matrix multiplication, we iterate through each element of the resulting matrix C and calculate its value using the dot product of corresponding rows and columns from matrices A and B. This involves three nested loops: one for rows of matrix A, one for columns of matrix B, and an inner loop for performing the dot product calculation.


function matrixMultiplication(A, B):
    initialize an empty matrix C with dimensions same as A
    for i from 0 to number of rows in A:
        for j from 0 to number of columns in B:
            initialize C[i][j] to 0
            for k from 0 to number of columns in A:
                C[i][j] += A[i][k] * B[k][j]
    return C

Algorithm Explanation

  1. We create an empty matrix C with the same dimensions as matrix A to store the result of multiplication.

  2. We iterate through each row of matrix A using the variable i.

  3. For each row, we iterate through each column of matrix B using the variable j.

  4. We initialize the value of C[i][j] to 0, which will be the value of the corresponding element in the resulting matrix.

  5. We then iterate through each column of matrix A using the variable k to perform the dot product calculation. For each k, we multiply A[i][k] with B[k][j] and add it to the current value of C[i][j].

  6. After all iterations are complete, matrix C will contain the result of matrix multiplication.

Here given code implementation process.

Time Complexity

The time complexity of matrix multiplication using the standard algorithm is O(n^3), where n is the number of rows (or columns) in the matrices. This is because for each element in the resulting matrix, we perform a dot product that involves iterating through a row and a column, each of size n.


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment