Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
1.1.
Problem statement
1.2.
Examples
2.
Approach
2.1.
Pseudocode
2.2.
Java code
2.3.
C++ code
2.3.1.
Complexity analysis
3.
Frequently Asked Questions
3.1.
What is a rectangular matrix? 
3.2.
What is a horizontal matrix?
3.3.
What is the important condition to multiply the matrix?
4.
Conclusion
Last Updated: Mar 27, 2024
Easy

Multiplication of two matrices

Author Ashish Sharma
0 upvote

Introduction

In this article, we will understand the matrix multiplication with the example and find the multiplication of two matrices in Java and C++. Matrix multiplication is a binary operation that produces a matrix from two matrices. For matrix multiplication, the range of columns inside the first matrix must be identical to the wide variety of rows in the 2d matrix. The resulting matrix is ​​called a matrix product and has a variety of rows in the first matrix and a range of columns in the second matrix.        

                       

                                                                            Matrix multiplication

Recommended Topic: AngularJS

Problem statement

We are given two matrices with sizes of rows and columns. The task is to multiply both the matrices and print the resultant matrix.

Examples

Input

a[2][2] = { {1, 3}, {2, 4} }

   

   b[2][2] = { {3, 1} {4, 2} }

Output 

 result[2][2] = { {15, 7}, {22, 10} }

 

Input 

 a[3][2] = { {1, 3}, {2, 4},{5,6} }

   b[2][3] = { {3, 1,2} , {4,7,8} }

Output

 result[3][3] = { {15,22,26}, {22,30,36},{39,47,58} } 

Approach

For solving this problem, we will first input the two matrices from the user. Then we will check if the matrix can be multiplied or not by checking that the column of the first matrix should be equal to the row of the second matrix. If that condition satisfies then only the matrix will be multiplied. After that we will simply pass the 3 loops to multiply the two matrices by the formula c[i][j]+=a[i][k]*b[k][j]. In the end, we will print the resultant matrix.

Pseudocode

for(int i=0;i<row1;i++){
       for(int j=0;j<col2;j++){
           c[i][j]=0;
           for(int k=0;k<col1;k++){
               c[i][j]+=a[i][k]*b[k][j];
           }
       }
   }

Java code

// java program to find the matrix multiplication.
import java.util.*;
class matrixmuli
{
public
    static void main(String args[])
    {
        int[][] a = new int[10][10];
        int[][] b = new int[10][10];
        int[][] c = new int[10][10];
        int row1, col1, row2, col2;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the rows of first matrix");
        row1 = sc.nextInt();
        System.out.println("Enter the col of first matrix");
        col1 = sc.nextInt();
        System.out.println("Enter the rows of second matrix");
        row2 = sc.nextInt();
        System.out.println("Enter the col of second matrix");
        col2 = sc.nextInt();
        if (col1 != row2)
        {
            System.out.println(" -----please enter valid inputs----");
            // break;
        }
        else
        {
            // taking the elements of first matrix by user
            System.out.println("Enter the elements of first matrix ");
            for (int i = 0; i < row1; i++)
            {
                for (int j = 0; j < col1; j++)
                {
                    a[i][j] = sc.nextInt();
                }
            }
            // taking the elements of first matrix by user
            System.out.println("Enter the elements of second matrix ");
            for (int i = 0; i < row2; i++)
            {
                for (int j = 0; j < col2; j++)
                {
                    b[i][j] = sc.nextInt();
                }
            }
            // matrix multiplication code
            for (int i = 0; i < row1; i++)
            {
                for (int j = 0; j < col2; j++)
                {
                    // making third matrix element to 0 for avoiding garbage values
                    c[i][j] = 0;
                    for (int k = 0; k < col1; k++)
                    {
                        // code to multiply two matrices
                        c[i][j] += a[i][k] * b[k][j];
                    }
                }
            }
            // printing the multiplied matrix
            System.out.println("\nMatrix after multiplication");
            for (int i = 0; i < row1; i++)
            {
                for (int j = 0; j < col2; j++)
                {
                    System.out.print(c[i][j] + " ");
                }
                System.out.println("\n");
            }
        }
    }
}

 

Output

                                             

C++ code

// C++ program to find the matrix multiplication.
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int row1, col1, row2, col2;
    cout << "Enter the number of rows of first matrix ";
    cin >> row1;
    cout << "Enter the number of column of first matrix ";
    cin >> col1;
    cout << "Enter the number of rows of second matrix ";
    cin >> row2;
    cout << "Enter the number of column of second matrix ";
    cin >> col2;
    if (col1 != row2)
    {
        cout << " -----please enter valid inputs----";
    }
    else
    {

        int a[row1][col1], b[row2][col2], c[row1][col2];

        cout << "Enter the elements of first matrix\n";
        for (int i = 0; i < row1; i++)
        {
            for (int j = 0; j < col1; j++)
            {
                cin >> a[i][j];
            }
        }
        cout << "Enter the elements of second matrix\n";
        for (int i = 0; i < row2; i++)
        {
            for (int j = 0; j < col2; j++)
            {
                cin >> b[i][j];
            }
        }
        // matrix multiplication code
        for (int i = 0; i < row1; i++)
        {
            for (int j = 0; j < col2; j++)
            {
                // making third matrix element to 0 for avoiding garbage values
                c[i][j] = 0;
                for (int k = 0; k < col1; k++)
                {
                    // code to multiply two matrices
                    c[i][j] += a[i][k] * b[k][j];
                }
            }
        }

        cout << "\nMatrix after multiplication" << endl;
        for (int i = 0; i < row1; i++)
        {
            for (int j = 0; j < col2; j++)
            {
                cout << c[i][j] << " ";
            }
            cout << endl;
        }
    }
}

 

Output

                                      

 

Complexity analysis

Time complexity

Since we are using three loops to multiply the elements. Therefore the time complexity would be O(n1*m1*m2), where n1 is the size of the row of the first matrix and m1 is the size of the column of the first matrix and m2 is the size of the column of the second matrix. You can consider it approximately equal to O(n^3).

Space complexity

Since we are using a new matrix of the size of n3 and m3 to store the elements therefore the space complexity would be O(n3*m3), n is the size of the row of the new matrix and m is the size of the column of the new matrix. You can consider it approximately equal to O(n*m).

Also see,  Rabin Karp Algorithm

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Frequently Asked Questions

What is a rectangular matrix? 

The rectangular matrix is ​​a type of matrix. In this matrix, the elements are arranged in rows and columns. The placement of the elements in the matrix represents a rectangle. Therefore, it is called a rectangular matrix. For example,

                                             

What is a horizontal matrix?

A matrix of degree m × n is called a horizontal matrix if n> m, where m is equal to the number of rows and n is equal to the number of columns. 

Matrix example- { {1,2,3,4},

                               {2,5,1,1} } 

In the example matrix shown below, the number of rows (n) = 2 and the number of columns (m) = 4.

What is the important condition to multiply the matrix?

Two matrices can only be multiplied when the number of columns of the first matrix and the number of rows of the second matrix are the same. For example, the 3*4 and 4*3 matrix is possible to multiply but the 2*3 and 2*4 matrix is not possible to multiply.

Conclusion

In this article, we have discussed the matrix multiplication with the example,  we have seen the implementation of the matrix multiplication program in O(n^3) time complexity, and  O(n^2) space complexity in java and C++.

After reading about matrix multiplication, are you not feeling excited to read/explore more articles on the topic of file systems? Don't worry; Coding Ninjas has you covered. if you want to practice questions on matrix then you must follow these links Matrix flip bitShortest path in a binary matrixMatrix is symmetricSummed matrix.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But suppose you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass