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