C++

Matrix Multiplication in C++

We are familiar with matrix operations in mathematics. The elements in the matrix are grouped into rows and columns. In C++, the matrix is also called a 2D array with the β€œmxn” dimensions where β€œm” shows the number of rows in the 2D array and β€œn” shows the number of columns in that 2D array. Here, we will perform a matrix multiplication operation using a C++ script.

Constraints for Matrix Multiplication in C++

Before diving into the matrix multiplication examples in C++, we should have some constraints here:

  • If the rows and columns of one matrix are equal to those of the other matrix, the matrix multiplication is useful in C++. The prompt generates the error until the matrices have equal rows and columns.
  • Both the number of rows and columns from the first and second matrices should be present in the resulting matrix.

Let’s begin with implementing the matrix multiplication in C++ for a better comprehension.

Example 1: Multiplication of Matrices in C++

Here, we demonstrate the simple multiplication of two matrices by applying the nested loop algorithm. Let’s get into the implementation to see the outcome of the multiplication matrices.

#include <bits/stdc++.h>
using namespace std;
void multiply(int matrix1[][2],int matrix2[][2], int x1, int x2, int y1, int y2)
{
    int a, r, s;
    int result[x1][y2];
    for (r = 0; r < x1; r++) {
        for (s = 0; s < y2; s++) {
            result[r][s] = 0;
            for (a = 0; a < x2; a++) {
                *(*(result + r) + s) += *(*(matrix1 + r) + a)
                                    * *(*(matrix2 + a) + s);
            }
        }
    }
    for (r = 0; r < x1; r++) {
        for (s = 0; s < y2; s++) {
            cout << *(*(result + r) + s) << " ";
        }
        cout << "\n";
    }
}

int main()
{
    int matrix1[][2] = { { 4, 4 }, { 8, 8 } };
    int matrix2[][2] = { { 4, 4 }, { 8, 8 } };
    int x1 = 2, x2 = 2, y1 = 2, y2 = 2;

    multiply(matrix1, matrix2, x1,y1, y2, x2);
    return 0;
}

We set the iostream header file in the given code for standard input and output stream. Then, we use the β€œstd” namespace to declare the object, variable, and functions from the standard library. After that, we call our program’s main() function where we declare a few variables. The matrix1[3][3] variable represents the first matrix and the matrix3[3][3] variable represents the second matrix. The matrix3[3][3] variable holds the multiplication results of these two matrices. Next, we declare the β€œsum” variable that is initialized with β€œ0”. The total of the matrix multiplication process is obtained using the β€œsum” variable. Then comes the decoration of x, y, and z variables that are used in the loop for iteration purposes.

The variables are declared to be used in the matrix multiplication operation. We use the output command which asks the user to enter the elements for the first matrix. Then, the nested loop is called out to insert the matrix elements into the β€œmatrix1”. The same goes for β€œmatrix2”, the prompt asks the user to enter the matrix element. Then, iteration will occur to verify whether the matrix order is followed or not. If not, the prompt will ask you to enter the elements again via the β€œfor” loop method.

After getting the elements for the matrices, we perform the matrix multiplication on the two matrices, β€œmatrix1” and β€œmatrix2”, using the nested loop. Each row of β€œmatrix1” is multiplied by each column of β€œmatrix2” to get the dot product and the outcome is stored in β€œmatrix3”.

The output shows the matrix that is retrieved after performing the multiplication operation of the matrix[3][3] and matrix2[3][3]:

Example 2: Multiplication of Matrices Using the Pointers in C++

Moreover, we utilize the pointers in C++ to perform the matrix multiplication. The main advantage of using the pointer for matrix multiplication is that it saves the memory space and has faster execution time. Let’s look at how we perform the matrix multiplication in C++ using the pointers.

#include <bits/stdc++.h>
using namespace std;

void multiply(int matrix1[][2],int matrix2[][2], int x1, int x2, int y1, int y2)
{
    int a, r, s;
    int result[x1][y2];
    for (r = 0; r < x1; r++) {
        for (s = 0; s < y2; s++) {
            result[r][s] = 0;
            for (a = 0; a < x2; a++) {
                *(*(result + r) + s) += *(*(matrix1 + r) + a)
                                    * *(*(matrix2 + a) + s);
            }
        }
    }
    for (r = 0; r < x1; r++) {
        for (s = 0; s < y2; s++) {
            cout << *(*(result + r) + s) << " ";
        }
        cout << "\n";
    }
}

int main()
{
    int matrix1[][2] = { { 4, 4 }, { 8, 8 } };
    int matrix2[][2] = { { 4, 4 }, { 8, 8 } };
    int x1 = 2, x2 = 2, y1 = 2, y2 = 2;

    multiply(matrix1, matrix2, x1,y1, y2, x2);
    return 0;
}

In the given code, we first set the standard library of C++ and the namespace header. Then, we create the multiply() function where we pass the input parameters. The input parameter includes matrix1[] and matrix2[] that represent the matrix, whereas the x1, x2, y1, and y2 parameters are the dimensions of specified matrices. Next, we perform the nested β€œfor” loop algorithm on these matrices for multiplication and store the resultant matrix in the β€œresult” variable. Here, we use the pointers to access the elements within the matrices. In this line of code, β€œ*(*(result + r) + s) += *(*(matrix1 + r) + a) * *(*(matrix2 + a) + s);” the pointer β€œ*(result + r) + s) ” moves to the β€œrth” row of the matrix and the β€œsth” column of that row.

Similarly, the β€œ*(matrix1 + r) + a” and β€œ*(matrix2 + a) + s” pointers move the rows and columns of those rows for the β€œm1” and β€œm2” matrices, respectively. The values that are retrieved from the pointers are then multiplied and added to the resultant β€œresult” matrix via the β€œfor” loop method that uses pointers. Finally, we call the main() function where we assign the values to the matrices by initializing them and the value to the β€œx1, y1, y2, x2” dimensions. Lastly, we call the multiply() function by passing the matrices and the dimensions as arguments.

The resulting matrix is obtained in the following after performing the matrix multiplication with the access of the pointers:

Example 3: Multiplication of Matrices by Creating Functions in C++

We performed the matrix multiplication in C++ in the previous examples. Now, we use the functions to perform the multiplication of matrices, increasing its readability. Consider the implementation of code where matrices are multiplied using functions.

#include <iostream>
using namespace std;

void values(int M1[][10], int M2[][10], int R1, int C1, int R2, int C2);
void calculation(int M1[][10], int M2[][10], int Result[][10], int R1, int C1, int R2, int R3);
void show(int mult[][10], int R1, int R2);

int main()
{
    int M1[10][10], M2[10][10], Multiply[10][10], R1, C1, R2, C2, i, j, k;

    cout << "Enter rows and column for Matrix A: ";
    cin >> R1 >> C1;

    cout << "Enter rows and column for Matrix B: ";
    cin >> R2 >> C2;

   
    while (C1 != R2)
    {
        cout << "Error! Matrix A rows and Matrix B columns are not equal" << endl;
        cout << "Enter rows and column for Matrix A: ";
        cin >> R1 >> C1;
        cout << "Enter rows and column for Matrix B: ";
        cin >> R2 >> C2;
    }

        values(M1, M2, R1, C1, R2, C2);
        calculation(M1, M2, Multiply, R1, C1, R2, C2);
        show(Multiply, R1, C2);

    return 0;
}

void values(int M1[][10], int M2[][10], int R1, int C1, int R2, int C2)
{
    int i, j;
    cout << endl << "Enter elements of matrix A:" << endl;
    for(i = 0; i < R1; ++i)
    {
        for(j = 0; j < C1; ++j)
        {
            cout << "Enter elements A"<< i + 1 << j + 1 << ": ";
            cin >> M1[i][j];
        }
    }

    cout << endl << "Enter elements of matrix B:" << endl;
    for(i = 0; i < R2; ++i)
    {
        for(j = 0; j < C2; ++j)
        {
            cout << "Enter elements B" << i + 1 << j + 1 << ": ";
            cin >> M2[i][j];
        }
    }
}

void calculation(int M1[][10], int M2[][10], int Multiply[][10], int R1, int C1, int R2, int C2)
{
    int i, j, k;

    for(i = 0; i < R1; ++i)
    {
        for(j = 0; j < C2; ++j)
        {
            Multiply[i][j] = 0;
        }
    }

   
    for(i = 0; i < R1; ++i)
    {
        for(j = 0; j < C2; ++j)
        {
            for(k=0; k<C1; ++k)
            {
                Multiply[i][j] += M1[i][k] * M2[k][j];
            }
        }
    }
}

void show(int Multiply[][10], int R1, int C2)
{
    int i, j;

In the given code, we established the “values()”function and passed the “M1” and “M2” matrices into it. Then, we input the β€œR1”, β€œC1”, β€œR2” and β€œC2” dimensions which takes the matrices element from the user. After that, we define another function, β€œcalculation()”, which calculates the product of the β€œM1” and β€œM2” matrices and stores the results in the β€œRes” parameter. Next, we call another function which is β€œshow()” to display the matrix multiplication results. Here, we define the result matrix which is β€œMultiply” to display the result matrix elements and the number of rows of both β€œM1” and β€œM2” matrices.

Then, we set the main() function where the condition is applied that the input matrices should be of equal rows. Otherwise, the user will enter the size of the matrices again. After taking the elements from the user, we perform the multiplication of matrices using the nested β€œfor” loop.

The resultant matrices are shown on the following prompt:

Conclusion

In conclusion, we have gone through matrix multiplication in C++ which involves matching the elements of the matrix that must be multiplied and then summed to get the resultant matrix. We have various examples where this multiplication of matrix is implemented. It includes a simple nested β€œfor” loop method using pointers to get the multiplication matrix results, and the foremost method is creating functions to get the multiplication of matrix results.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content