c-plus-plus
  1. c-plus-plus-matrix-multiplication

C++ Programs: Matrix Multiplication

Matrix multiplication refers to the process of multiplying two matrices and returning a new matrix as a result. In C++, we can perform matrix multiplication using nested loops to iterate through the rows and columns of the matrices.

Syntax

void matrixMultiply(int m1[][], int m2[][], int result[][], int r1, int c1, int r2, int c2)
  • m1: First matrix to be multiplied
  • m2: Second matrix to be multiplied
  • result: Matrix where result of multiplication will be stored
  • r1: Number of rows in first matrix
  • c1: Number of columns in first matrix
  • r2: Number of rows in second matrix
  • c2: Number of columns in second matrix

Example

#include <iostream>
using namespace std;

void matrixMultiply(int m1[][3], int m2[][2], int result[][2], int r1, int c1, int r2, int c2) {
    for(int i=0; i<r1; i++) {
        for(int j=0; j<c2; j++) {
            result[i][j] = 0;
            for(int k=0; k<r2; k++) {
                result[i][j] += m1][k] * m2[k][j];
            }
        }
    }
}

int main() {
    int m1[2][3] = {{1,2,3}, {4,5,6}};
    int m2[3][2] = {{1,2}, {3,4}, {5,6}};
    int result[2][2];

    matrixMultiply(m1, m2, result, 2, 3, 3, 2);

    for(int i=0; i<2; i++) {
        for(int j=0; j<2; j++) {
            cout << result[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

Output

22 28
49 64

Explanation

In the above example, we have two matrices of dimensions 2x3 and 3x2. We perform matrix multiplication using a nested loop to iterate through the rows and columns of the matrices. The result of multiplication is stored in a new 2x2 matrix.

Use

Matrix multiplication is used in various applications, including computer graphics, artificial intelligence, and scientific computing. It is especially useful in linear algebra where it is used to solve systems of linear equations.

Important Points

  • Matrix multiplication can only be performed if the number of columns in the first matrix is equal to the number of rows in the second matrix.
  • The dimensions of the result matrix are determined by the number of rows in the first matrix and the number of columns in the second matrix.
  • Nested loops are used to iterate through the rows and columns of the matrices and perform multiplication.

Summary

In summary, matrix multiplication is an important operation in linear algebra and is used in various applications. In C++, we can perform matrix multiplication using nested loops to iterate through the rows and columns of the matrices. The result of multiplication is stored in a new matrix with dimensions determined by the number of rows in the first matrix and the number of columns in the second matrix.

Published on: