Open In App

Program to multiply two matrices

Last Updated : 13 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two matrices, the task is to multiply them. Matrices can either be square or rectangular:

Examples: 

(Square Matrix Multiplication)

Input: m1[m][n] = { {1, 1}, {2, 2} }
m2[n][p] = { {1, 1}, {2, 2} }
Output: res[m][p] = { {3, 3}, {6, 6} }

(Rectangular Matrix Multiplication)

Input: m1[3][2] = { {1, 1}, {2, 2}, {3, 3} }
m2[2][3] = { {1, 1, 1}, {2, 2, 2} }
Output: res[3][3] = { {3, 3, 3}, {6, 6, 6}, {9, 9, 9} }

Multiplication of two Square or Rectangular Matrices

  • The number of columns in Matrix-1 must be equal to the number of rows in Matrix-2.
  • Output of multiplication of Matrix-1 and Matrix-2, results with equal to the number of rows of Matrix-1 and  the number of columns of Matrix-2 i.e. rslt[R1][C2]

Below is the implementation of the multiplication of two matrices:

C++
#include <iostream>
#include <vector>
using namespace std;

void mulMat(vector<vector<int>>& m1, vector<vector<int>>& m2, 
            vector<vector<int>>& res) {
    int r1 = m1.size();
    int c1 = m1[0].size();
    int r2 = m2.size();
    int c2 = m2[0].size();

    if (c1 != r2) {
        cout << "Invalid Input" << endl;
        exit(EXIT_FAILURE);
    }

    // Resize result matrix to fit the result dimensions
    res.resize(r1, vector<int>(c2, 0)); 
  
    for (int i = 0; i < r1; i++) {
        for (int j = 0; j < c2; j++) {
            for (int k = 0; k < c1; k++) {
                res[i][j] += m1[i][k] * m2[k][j];
            }
        }
    }
}

// Driver code
int main() {
    vector<vector<int>> m1 = { {1, 1}, {2, 2} };
    vector<vector<int>> m2 = { {1, 1}, {2, 2} };
    vector<vector<int>> res;

    mulMat(m1, m2, res);

    cout << "Multiplication of given two matrices is:\n";
    for (const auto& row : res) {
        for (int val : row) {
            cout << val << "\t";
        }
        cout << endl;
    }

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

#define R1 2 // number of rows in Matrix-1
#define C1 2 // number of columns in Matrix-1
#define R2 2 // number of rows in Matrix-2
#define C2 2 // number of columns in Matrix-2

void mulMat(int m1[][C1], int m2[][C2], int rslt[][C2]) {
    if (C1 != R2) {
       printf("Invalid Input");
       return;
    }  
  
    for (int i = 0; i < R1; i++) {
        for (int j = 0; j < C2; j++) {
            rslt[i][j] = 0;

            // Changed R2 to C1 for correct multiplication
            for (int k = 0; k < C1; k++) { 
                rslt[i][j] += m1[i][k] * m2[k][j];
            }
        }
    }
}

int main() {
    int m1[R1][C1] = { { 1, 1 },
                       { 2, 2 } };

    int m2[R2][C2] = { { 1, 1 },
                       { 2, 2 } };

    int rslt[R1][C2]; // Result matrix
  
    // Function call to multiply matrices
    mulMat(m1, m2, rslt);

    // Print the result matrix
    printf("Result matrix is:\n");
    for (int i = 0; i < R1; i++) {
        for (int j = 0; j < C2; j++) {
            printf("%d\t", rslt[i][j]);
        }
        printf("\n");
    }

    return 0;
}
Java
public class MatrixMultiplication {

    public static void mulMat(int[][] m1, int[][] m2, int[][] res) {
        int r1 = m1.length;
        int c1 = m1[0].length;
        int r2 = m2.length;
        int c2 = m2[0].length;

        if (c1 != r2) {
            System.out.println("Invalid Input");
            System.exit(1);
        }

        // Perform matrix multiplication
        for (int i = 0; i < r1; i++) {
            for (int j = 0; j < c2; j++) {
                res[i][j] = 0; // Initialize result cell
                for (int k = 0; k < c1; k++) {
                    res[i][j] += m1[i][k] * m2[k][j];
                }
            }
        }
    }

    public static void main(String[] args) {
        int[][] m1 = {
            {1, 1},
            {2, 2}
        };

        int[][] m2 = {
            {1, 1},
            {2, 2}
        };

        int r1 = m1.length;
        int c2 = m2[0].length;
        int[][] res = new int[r1][c2]; // Resultant matrix

        mulMat(m1, m2, res);

        System.out.println("Multiplication of given two matrices is:");
        for (int i = 0; i < r1; i++) {
            for (int j = 0; j < c2; j++) {
                System.out.print(res[i][j] + "\t");
            }
            System.out.println();
        }
    }
}
Python
def mulMat(m1, m2):
    r1 = len(m1)
    c1 = len(m1[0])
    r2 = len(m2)
    c2 = len(m2[0])

    if c1 != r2:
        print("Invalid Input")
        return None

    # Initialize the result matrix with zeros
    res = [[0] * c2 for _ in range(r1)]

    # Perform matrix multiplication
    for i in range(r1):
        for j in range(c2):
            for k in range(c1):
                res[i][j] += m1[i][k] * m2[k][j]

    return res

# Driver code
if __name__ == "__main__":
    m1 = [
        [1, 1],
        [2, 2]
    ]

    m2 = [
        [1, 1],
        [2, 2]
    ]

    result = mulMat(m1, m2)

    print("Multiplication of given two matrices is:")
    for row in result:
        print(" ".join(map(str, row)))
C#
using System;

class Program
{
    static int[,] MulMat(int[,] m1, int[,] m2)
    {
        int r1 = m1.GetLength(0);
        int c1 = m1.GetLength(1);
        int r2 = m2.GetLength(0);
        int c2 = m2.GetLength(1);

        if (c1 != r2)
        {
            Console.WriteLine("Invalid Input");
            return null;
        }

        // Initialize the result matrix
        int[,] res = new int[r1, c2];

        // Perform matrix multiplication
        for (int i = 0; i < r1; i++)
        {
            for (int j = 0; j < c2; j++)
            {
                for (int k = 0; k < c1; k++)
                {
                    res[i, j] += m1[i, k] * m2[k, j];
                }
            }
        }

        return res;
    }

    static void Main()
    {
        int[,] m1 = { { 1, 1 }, { 2, 2 } };
        int[,] m2 = { { 1, 1 }, { 2, 2 } };

        int[,] result = MulMat(m1, m2);

        if (result != null)
        {
            Console.WriteLine("Multiplication of given two matrices is:");
            for (int i = 0; i < result.GetLength(0); i++)
            {
                for (int j = 0; j < result.GetLength(1); j++)
                {
                    Console.Write(result[i, j] + "\t");
                }
                Console.WriteLine();
            }
        }
    }
}
JavaScript
function mulMat(m1, m2) {
    const r1 = m1.length;
    const c1 = m1[0].length;
    const r2 = m2.length;
    const c2 = m2[0].length;

    if (c1 !== r2) {
        console.log("Invalid Input");
        return null;
    }

    // Initialize the result matrix
    const res = Array.from({ length: r1 }, () => Array(c2).fill(0));

    // Perform matrix multiplication
    for (let i = 0; i < r1; i++) {
        for (let j = 0; j < c2; j++) {
            for (let k = 0; k < c1; k++) {
                res[i][j] += m1[i][k] * m2[k][j];
            }
        }
    }

    return res;
}

// Driver code
const m1 = [
    [1, 1],
    [2, 2]
];

const m2 = [
    [1, 1],
    [2, 2]
];

const result = mulMat(m1, m2);

if (result) {
    console.log("Multiplication of given two matrices is:");
    for (const row of result) {
        console.log(row.join(" "));
    }
}

Output
Multiplication of given two matrices is:
3    3    
6    6    

Time complexity: O(R1 * C2 * R2) for given matrices mat1[R1][C1] and mat2[R2][C2]
Auxiliary space: O(R1 * C2)

Multiplication of Rectangular Matrices using Pointers in C/C++:

To solve the problem follow the below idea:

We use pointers in C/C++ to multiply matrices

Prerequisite:  How to pass a 2D array as a parameter in C? 

Below is the implementation of the above approach:

C
#include <stdio.h>
#include <stdlib.h>

#define R1 2 // number of rows in Matrix-1
#define C1 2 // number of columns in Matrix-1
#define R2 2 // number of rows in Matrix-2
#define C2 2 // number of columns in Matrix-2

void mulMat(int (*m1)[C1], int (*m2)[C2], int (*rslt)[C2]) {
    if (C1 != R2) {
        printf("Invalid Input");
        return;
    }  
      
    for (int i = 0; i < R1; i++) {
        for (int j = 0; j < C2; j++) {
            rslt[i][j] = 0; // Initialize result matrix element

            for (int k = 0; k < C1; k++) { // Use C1 for multiplication
                rslt[i][j] += m1[i][k] * m2[k][j];
            }
        }
    }
}

int main() {
    int m1[R1][C1] = { { 1, 1 },
                       { 2, 2 } };

    int m2[R2][C2] = { { 1, 1 },
                       { 2, 2 } };

    int rslt[R1][C2]; // Result matrix

    // Function call to multiply matrices
    mulMat(m1, m2, rslt);

    // Print the result matrix
    printf("Result matrix is:\n");
    for (int i = 0; i < R1; i++) {
        for (int j = 0; j < C2; j++) {
            printf("%d\t", rslt[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Output
3 3 
6 6 


Related Article



Next Article

Similar Reads