Matrix Multiplication in C

Get Certified in C Programming for Free and Take Your Skills to the Next Level

Matrix multiplication is a crucial operation in linear algebra and has widespread applications in fields like machine learning, computer graphics, physics simulations, and more.

The aim of this article is to explain matrix multiplication in detail and provide step-by-step code examples for implementing it in the C programming language.

Understanding Matrices

An organised collection of numbers or functions in a rectangular shape is referred to as a matrix and normally has m rows and n columns. It is important to remember while talking about matrix multiplication that the number of columns in the first matrix must equal the number of rows in the second matrix in order for the two matrices to be multiplied together. The number of rows from the first matrix and the number of columns from the second matrix will define the dimensions of the final product matrix.

Calculating the total of the products obtained by multiplying the corresponding components from the rows and columns of the first and second matrices is known as matrix multiplication. Simply said, each element in the final product matrix is created by taking the dot product of the first row of the first matrix and the first column of the second matrix.

Let’s have two 3×3 matrices:

A = [1 2 3]
[4 5 6]
[7 8 9]

B = [9 8 7]
[6 5 4]
[3 2 1]

To multiply these two matrices:

The number of columns in the first matrix (A) must equal the number of rows in the second matrix (B). Here, A has 3 columns, and B has 3 rows, so we can multiply them.

To find the element C11, we take the dot product of the first row of A with the first column of B: C11 = A11B11 + A12B21 + A13B31 C11 = 19 + 26 + 33 = 36

To find the element C12, we take the dot product of the first row of A with the second column of B: C12 = A11B12 + A12B22 + A13B32 C12 = 18 + 25 + 32 = 25

We follow this pattern and take dot products of each row of A with each column of B to populate the entire matrix C.

C = [36 25 14]
[81 69 57]
[126 113 100]

So, in summary, we take dot products of the rows of A with the columns of B to calculate each element of C. The matrices must have compatible dimensions, with the number of A columns equaling the number of B rows.

Algorithm for Multiplication of Matrix in C

When multiplying matrices, each element of the first matrix is multiplied by the corresponding row of the second matrix.

Let’s examine the sequential algorithm:

  • Input the dimensions (number of rows and columns) of the two matrices to be multiplied. Let the first matrix be A[m][n] and the second matrix be B[p][q].
  • Allocate memory for the two input matrices, A and B, as per their dimensions.
  • Input elements into A and B row-wise using nested loops.
  • Verify that the number of rows in B equals the number of columns in A. If not, give a message of error and leave.
  • Declare a result matrix C of size m x q to store the product.
  • Initialize a loop from i = 0 to i = m.
  • Inside this loop, initialize another loop from j = 0 to j = q.
  • Set C[i][j] to 0
  • Inside the ij loop, initialize another loop k = 0 to k = p.
  • Update C[i][j] by adding the product of A[i][k] * B[k][j].
  • Print the result matrix C.

Here is the pseudocode implementation:

1. Input m, n, p, q
2. Allocate A[m][n], B[p][q], C[m][q]
3. Read A and B
4. If n != p
Print “Multiplication not possible”
Exit
5. For i = 0 to m
For j = 0 to q
C[i][j] = 0
For k = 0 to p
C[i][j] += A[i][k] * B[k][j]
6. Print C

Algorithm for Multiplication of Matrix

Implementing Matrix Multiplication in C

#include <stdio.h>

// Function to perform matrix multiplication
void matrixMultiply(int m, int n, int p, int A[][n], int B[][p], int C[][p]) {
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < p; j++) {
            C[i][j] = 0;
            for (int k = 0; k < n; k++) {
                C[i][j] += A[i][k] * B[k][j];
            }
        }
    }
}

// Function to print a matrix
void printMatrix(int rows, int cols, int mat[][cols]) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d\t", mat[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int m = 3, n = 3, p = 3;
    int A[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int B[][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
    int C[3][3];

    // Perform matrix multiplication
    matrixMultiply(m, n, p, A, B, C);

    printf("Matrix A:\n");
    printMatrix(m, n, A);

    printf("\nMatrix B:\n");
    printMatrix(n, p, B);

    printf("\nMatrix C (Result of A * B):\n");
    printMatrix(m, p, C);

    return 0;
}

Time Complexity: O(m * n * p)
Space Complexity: O(m * p)

  • “m” is the number of rows in the first matrix.
  • “n” is the number of columns in the first matrix (and also the number of rows in the second matrix).
  • “p” is the number of columns in the second matrix.

Output:

Matrix A:
1 2 3
4 5 6
7 8 9

Matrix B:
9 8 7
6 5 4
3 2 1

Matrix C (Result of A * B):
30 20 10
84 56 28
138 92 46

Multiplying Matrices in C

There are two primary types of matrices in mathematics: square matrices and rectangular matrices.

Multiplying Matrices in C

Let’s begin by discussing the multiplication of square matrices.

Multiplying Square Matrices

A square matrix is one where the number of rows is equal to the number of columns. To multiply two square matrices of the same order, they must have the same dimensions. The multiplication process involves multiplying corresponding elements and summing up the products.

Here is a C program to calculate the product of two square matrices:

#include <stdio.h>

int main() {
    int a[10][10], b[10][10], c[10][10], n, i, j, k;

    printf("Enter the size of N (N <= 10): ");
    scanf("%d", &n);
    printf("Enter the elements of Matrix-A:\n");

    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            scanf("%d", &a[i][j]);
        }
    }

    printf("Enter the elements of Matrix-B:\n");

    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            scanf("%d", &b[i][j]);
        }
    }

    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            c[i][j] = 0;
            for (k = 0; k < n; k++) {
                c[i][j] += a[i][k] * b[k][j];
            }
        }
    }

    printf("The product of the two matrices is:\n");
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            printf("%d\t", c[i][j]);
        }
        printf("\n");
    }
    return 0;
}

In the program above, we ask the user to enter the matrix size (N) once because only matrices of the same order can be multiplied.

Input:
Enter the value of N (N <= 10): 2
Enter the elements of Matrix-A:
2 2
2 2
Enter the elements of Matrix-B:
2 2
2 2

Output:
The product of the two matrices is:
8 8
8 8

Multiplying Rectangular Matrices

There are several combinations of rows and columns in rectangular matrices. The number of columns in the first matrix must equal the number of rows in the second matrix in order to multiply two rectangular matrices.

Here is a C program to calculate the product of two rectangular matrices:

#include <stdio.h>

int main() {
    int m, n, p, q, i, j, k;
    int a[10][10], b[10][10], res[10][10];

    printf("Enter the dimensions of the first matrix:\n");
    scanf("%d%d", &m, &n);
    printf("Enter the dimensions of the second matrix:\n");
    scanf("%d%d", &p, &q);

    if (n != p) {
        printf("Matrix is incompatible for multiplication\n");
    } else {
        printf("Enter the elements of Matrix-A:\n");
        for (i = 0; i < m; i++) {
            for (j = 0; j < n; j++) {
                scanf("%d", &a[i][j]);
            }
        }

        printf("Enter the elements of Matrix-B:\n");
        for (i = 0; i < p; i++) {
            for (j = 0; j < q; j++) {
                scanf("%d", &b[i][j]);
            }
        }

        for (i = 0; i < m; i++) {
            for (j = 0; j < q; j++) {
                res[i][j] = 0;
                for (k = 0; k < p; k++) {
                    res[i][j] += a[i][k] * b[k][j];
                }
            }
        }

        printf("The product of the two matrices is:\n");

        for (i = 0; i < m; i++) {
            for (j = 0; j < q; j++) {
                printf("%d\t", res[i][j]);
            }
            printf("\n");
        }
    }

    return 0;
}

In this program, we ensure that the dimensions of the matrices are compatible with multiplication before performing the calculation.

Input:
Enter the order of the first matrix:
2 3
Enter the order of the second matrix:
3 2
Enter the elements of Matrix-A:
1 2
1 2
1 2
Enter the elements of Matrix-B:
1 2
3 2

Output:
The product of the two matrices is:
7 6
7 6

Matrix Multiplication in C Using Functions

In the realm of matrix multiplication in C, we encounter scenarios where we need to multiply matrices repeatedly. However, rewriting the same code for each multiplication can lead to a larger, more complex program and make debugging a daunting task. To overcome this challenge, we can harness the power of functions.

#include <stdio.h>

// Function to input matrix elements entered by the user
void userInputMatrix(int inputMatrix[][10], int rows, int columns) {
    printf("\nEnter matrix elements:\n");
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < columns; ++j) {
            printf("Please enter an element for row %d, column %d: ", i + 1, j + 1);
            scanf("%d", &inputMatrix[i][j]);
        }
    }
}

// Function to multiply two matrices
void multiplyTwoMatrices(int firstMatrix[][10], int secondMatrix[][10], int resultMatrix[][10], int r1, int c1, int r2, int c2) {
    // Initializing elements of the result matrix to 0.
    for (int i = 0; i < r1; ++i) {
        for (int j = 0; j < c2; ++j) {
            resultMatrix[i][j] = 0;
        }
    }

    // Multiplying the first and second matrices and storing the result in the result matrix
    for (int i = 0; i < r1; ++i) {
        for (int j = 0; j < c2; ++j) {
            for (int k = 0; k < c1; ++k) {
                resultMatrix[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
            }
        }
    }
}

// Function to display the result matrix
void displayResultMatrix(int resultMatrix[][10], int rows, int columns) {
    printf("\nResult Matrix:\n");
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < columns; ++j) {
            printf("%d  ", resultMatrix[i][j]);
            if (j == columns - 1) {
                printf("\n");
            }
        }
    }
}

int main() {
    int matrixA[10][10], matrixB[10][10], resultMatrix[10][10], rowsA, columnsA, rowsB, columnsB;

    printf("Please provide the number of rows and columns for the first matrix: ");
    scanf("%d %d", &rowsA, &columnsA);

    printf("Please provide the number of rows and columns for the second matrix: ");
    scanf("%d %d", &rowsB, &columnsB);

    while (columnsA != rowsB) {
        printf("The number of columns in the first matrix must be equal to the number of rows in the second matrix.\n");
        printf("Please re-enter the number of rows and columns for the first matrix: ");
        scanf("%d %d", &rowsA, &columnsA);

        printf("Please re-enter the number of rows and columns for the second matrix: ");
        scanf("%d %d", &rowsB, &columnsB);
    }

    // Input elements of the first matrix
    userInputMatrix(matrixA, rowsA, columnsA);

    // Input elements of the second matrix
    userInputMatrix(matrixB, rowsB, columnsB);

    // Multiply two matrices
    multiplyTwoMatrices(matrixA, matrixB, resultMatrix, rowsA, columnsA, rowsB, columnsB);

    // Display the result matrix
    displayResultMatrix(resultMatrix, rowsA, columnsB);

    return 0;
}

By employing these functions, you can streamline your code, enhance readability, and efficiently perform matrix multiplication as needed within your program.

Real-World Applications

Some examples of matrix multiplication in action:

  • Computer Graphics: Transformations like rotation, scaling, and translation of images and shapes involve matrix multiplications.
  • Machine Learning: Matrix multiplication is used in various machine learning algorithms like neural networks.
  • Physics Engines: Simulating physics for animations and games requires matrix math for 3D rotations and coordinate transformations.

Conclusion

Matrix multiplication in C is a fundamental linear algebra operation with applications across science and engineering domains. This article provided an overview of matrix multiplication, a step-by-step algorithm, and sample C code to implement it for two matrices. Mastering matrix operations like multiplication in C is essential for fields like graphics, simulation, and data science.

Your opinion matters
Please write your valuable feedback about DataFlair on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *