Matrix Multiplication in C

Matrix Multiplication is a fundamental operation in computer science and numerical analysis. It involves calculating the product of two matrices, and it is essential in various fields, including graphics, scientific computing, and machine learning. This guide will explore three distinct methods for performing the Multiplication of Two Matrix in C, complete with code examples, explanations, and output.

Learn C Program for Multiplication of Two Matrices

Matrix Multiplication in C

Multiplication of Two Matrices involves multiplying rows of the first matrix by columns of the second matrix. For two matrices A (of size m x n) and B (of size n x p) to be multiplied, the number of columns in A must equal the number of rows in B. The result is a new matrix C of size m x p, where each element is computed as the dot product of a row in A and a column in B.

Method 1) Multiply Two Matrices using Basic Matrix Multiplication

Code Example

#include <stdio.h>

#define MAX 10

void multiplyMatrices(int mat1[MAX][MAX], int mat2[MAX][MAX], int res[MAX][MAX], int row1, int col1, int row2, int col2) {
    if (col1 != row2) {
        printf("Matrix multiplication not possible.\n");
        return;
    }

    for (int i = 0; i < row1; i++) {
        for (int j = 0; j < col2; j++) {
            res[i][j] = 0;
            for (int k = 0; k < col1; k++) {
                res[i][j] += mat1[i][k] * mat2[k][j];
            }
        }
    }
}

void printMatrix(int mat[MAX][MAX], int row, int col) {
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            printf("%d ", mat[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int mat1[2][3] = {{1, 2, 3}, {4, 5, 6}};
    int mat2[3][2] = {{7, 8}, {9, 10}, {11, 12}};
    int res[2][2];
    
    multiplyMatrices(mat1, mat2, res, 2, 3, 3, 2);
    printf("Resultant Matrix:\n");
    printMatrix(res, 2, 2);

    return 0;
}

Explanation of the Code

  • Function multiplyMatrices: Takes two matrices and their dimensions as input and performs multiplication. It checks if multiplication is possible (i.e., the first matrix’s columns should match the second matrix’s rows).
  • Function printMatrix: Displays the matrix in a readable format.

Output

Resultant Matrix:
58 64
139 154

Method 2) Multiply Two Matrices using Dynamic Memory Allocation

Code Example

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

void multiplyMatrices(int **mat1, int **mat2, int **res, int row1, int col1, int row2, int col2) {
    if (col1 != row2) {
        printf("Matrix multiplication not possible.\n");
        return;
    }

    for (int i = 0; i < row1; i++) {
        for (int j = 0; j < col2; j++) {
            res[i][j] = 0;
            for (int k = 0; k < col1; k++) {
                res[i][j] += mat1[i][k] * mat2[k][j];
            }
        }
    }
}

void printMatrix(int **mat, int row, int col) {
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            printf("%d ", mat[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int row1 = 2, col1 = 3, row2 = 3, col2 = 2;
    int **mat1 = (int **)malloc(row1 * sizeof(int *));
    int **mat2 = (int **)malloc(row2 * sizeof(int *));
    int **res = (int **)malloc(row1 * sizeof(int *));

    for (int i = 0; i < row1; i++) {
        mat1[i] = (int *)malloc(col1 * sizeof(int));
    }
    for (int i = 0; i < row2; i++) {
        mat2[i] = (int *)malloc(col2 * sizeof(int));
    }
    for (int i = 0; i < row1; i++) {
        res[i] = (int *)malloc(col2 * sizeof(int));
    }

    // Initialize matrices
    mat1[0][0] = 1; mat1[0][1] = 2; mat1[0][2] = 3;
    mat1[1][0] = 4; mat1[1][1] = 5; mat1[1][2] = 6;
    mat2[0][0] = 7; mat2[0][1] = 8;
    mat2[1][0] = 9; mat2[1][1] = 10;
    mat2[2][0] = 11; mat2[2][1] = 12;

    multiplyMatrices(mat1, mat2, res, row1, col1, row2, col2);

    printf("Resultant Matrix:\n");
    printMatrix(res, row1, col2);

    // Free memory
    for (int i = 0; i < row1; i++) free(mat1[i]);
    for (int i = 0; i < row2; i++) free(mat2[i]);
    for (int i = 0; i < row1; i++) free(res[i]);
    free(mat1);
    free(mat2);
    free(res);

    return 0;
}

Explanation of the Code

  • Dynamic Memory Allocation: This method uses pointers and dynamic memory allocation to handle matrices of arbitrary sizes. It provides more flexibility compared to static allocation.
  • Memory Management: Ensures that memory is allocated and freed properly to avoid memory leaks.

Output

Resultant Matrix:
58 64
139 154

Method 3) Multiply Two Matrices Using a Function to Calculate Element by Element

Code Example

#include <stdio.h>

void elementWiseMultiplication(int mat1[][3], int mat2[][2], int res[][2], int row1, int col1, int row2, int col2) {
    if (col1 != row2) {
        printf("Matrix multiplication not possible.\n");
        return;
    }

    for (int i = 0; i < row1; i++) {
        for (int j = 0; j < col2; j++) {
            int sum = 0;
            for (int k = 0; k < col1; k++) {
                sum += mat1[i][k] * mat2[k][j];
            }
            res[i][j] = sum;
        }
    }
}

void printMatrix(int mat[][2], int row, int col) {
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            printf("%d ", mat[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int mat1[2][3] = {{1, 2, 3}, {4, 5, 6}};
    int mat2[3][2] = {{7, 8}, {9, 10}, {11, 12}};
    int res[2][2];

    elementWiseMultiplication(mat1, mat2, res, 2, 3, 3, 2);
    printf("Resultant Matrix:\n");
    printMatrix(res, 2, 2);

    return 0;
}

Explanation of the Code

  • Element-wise Function: This method provides a more modular approach by separating the matrix multiplication logic into a dedicated function.
  • Code Simplicity: This approach simplifies the matrix multiplication by keeping the multiplication logic self-contained.

Output

Resultant Matrix:
58 64
139 154

Matrix multiplication is a crucial operation in many computational tasks. The methods discussed in this guide—basic multiplication, dynamic memory allocation, and element-wise functions—offer different approaches to implement this operation in C. By understanding and applying these techniques, you can efficiently handle matrix operations in your applications.

For optimal performance and flexibility, choose the method that best fits your needs. Whether you are working with static matrices or require dynamic allocation, these examples provide a solid foundation for implementing matrix multiplication in C.

You can also refer following C pograms:

Categories C

Leave a Comment