Matrix Multiplication in C

Matrix Multiplication in C

Vikram Singh
Assistant Manager - Content
Updated on Apr 12, 2024 10:45 IST

A matrix is a collection of numbers organized in rows and columns. Matrices can be manipulated using operations like Addition, Subtraction, and Multiplication. Multiplying two matrices is only possible when the number of columns in the first matrix matches the number of rows in the second matrix.

The result of two matrix multiplication in C is obtained by calculating the dot product of each row of the first matrix with each column of the second matrix.

To better understand this article, it is recommended that you have prior knowledge of the following C Programming topics:

Today, we will be covering the following sections:

Introduction to Matrix Multiplication

Matrix multiplication is a fundamental operation in linear algebra, used in many applications such as computer graphics, physics, economics, and engineering. It involves multiplying two matrices to obtain a new matrix that represents the composition of the two original matrices.

To perform matrix multiplication, we need to follow a specific rule: the number of columns in the first matrix must be equal to the number of rows in the second matrix. If this condition is met, the resulting matrix will have the same number of rows as the first matrix and the same number of columns as the second matrix.

The process of matrix multiplication involves multiplying each element of a row in the first matrix with the corresponding element in a column of the second matrix, and then adding the products together. This operation is repeated for every row and column pair until all elements in the resulting matrix are computed.

Matrix multiplication is not commutative, which means that the order of the matrices matters. In other words, multiplying matrix A by matrix B may produce a different result than multiplying matrix B by matrix A.

We recommend you to check out this Beginner’s Guide to Understand and Implement Matrix Multiplication to have a more thorough knowledge of this topic.

You can also explore: Building Better Code with Enum in C: Best Practices and Examples

Matrix Multiplication in C

There are mainly two types of matrices:

• Square matrix
• Rectangle matrix

Let’s look at the multiplication of both of these matrices in C:

Square Matrix Multiplication in C

A square matrix is defined as a matrix with the same number of rows and columns. The multiplication of two square matrices of the same order is only possible if both matrices have the same order.

To compute the product of two matrices, we multiply the corresponding elements of the matrices and sum up the products. Let us see how this is achieved using C programming:

`#include <stdio.h> #define N 3 // Size of square matrices int main() { int matrix1[N][N] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int matrix2[N][N] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}}; int result[N][N]; int i, j, k; // Multiply the two matrices for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { int sum = 0; for (k = 0; k < N; k++) { sum += matrix1[i][k] * matrix2[k][j]; } result[i][j] = sum; } } // Print the resulting matrix printf("Result Matrix:\n"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { printf("%d ", result[i][j]); } printf("\n"); } return 0; }Copy code`

Output:

In this example, we have two 3×3 square matrices: matrix1 and matrix2. We declare a new matrix result to store the result of the multiplication.

We then use three nested loops to multiply the two matrices: the outermost loop iterates over the rows of the first matrix, the middle loop iterates over the columns of the second matrix, and the innermost loop iterates over the elements in the rows and columns.

The product of each corresponding element in the row of the first matrix and column of the second matrix is calculated and summed up to obtain the resulting element in the result matrix.

Finally, we print the resulting matrix to the console.

You can also explore: Switch Case in C Programming: A Comprehensive Guide

Rectangle Matrix Multiplication in C

A rectangular matrix is a matrix that has a different number of rows and columns.

The rules for determining if two rectangular matrices can be multiplied remain the same as those for square matrices. Specifically, the number of columns in the first matrix must be equal to the number of rows in the second matrix.

Below is a code example that demonstrates how to find the product of two rectangular matrices:

`#include <stdio.h> #define ROWS_A 2 #define COLS_A 3 #define ROWS_B 3 #define COLS_B 4 int main() { int matrix_a[ROWS_A][COLS_A] = {{1, 2, 3}, {4, 5, 6}}; int matrix_b[ROWS_B][COLS_B] = {{7, 8, 9, 10}, {11, 12, 13, 14}, {15, 16, 17, 18}}; int result[ROWS_A][COLS_B]; int i, j, k; // Multiply the two matrices for (i = 0; i < ROWS_A; i++) { for (j = 0; j < COLS_B; j++) { int sum = 0; for (k = 0; k < ROWS_B; k++) { sum += matrix_a[i][k] * matrix_b[k][j]; } result[i][j] = sum; } } // Print the resulting matrix printf("Result Matrix:\n"); for (i = 0; i < ROWS_A; i++) { for (j = 0; j < COLS_B; j++) { printf("%d ", result[i][j]); } printf("\n"); } return 0; }Copy code`

Output:

In this example, we have two rectangular matrices: matrix_a, which is a 2×3 matrix, and matrix_b, which is a 3×4 matrix. We declare a new matrix result to store the result of the multiplication.

We then use three nested loops to multiply the two matrices: the outermost loop iterates over the rows of the first matrix, the middle loop iterates over the columns of the second matrix, and the innermost loop iterates over the elements in the rows and columns.

The product of each corresponding element in the row of the first matrix and column of the second matrix is calculated and summed up to obtain the resulting element in the result matrix.

Finally, we print the resulting matrix to the console.

You can also explore: Variables in C Programming: Types, Scope, and Lifetime

Matrix Multiplication by Passing it to a Function in C

In C, you can also multiply matrices by passing them to a function. Here’s an example of multiplying two matrices by passing them to a function in C:

`#include <stdio.h> #define ROWS_A 2 #define COLS_A 3 #define ROWS_B 3 #define COLS_B 4 void multiply_matrices(int matrix_a[][COLS_A], int matrix_b[][COLS_B], int result[][COLS_B], int rows_a, int cols_a, int cols_b) { int i, j, k; // Multiply the two matrices for (i = 0; i < rows_a; i++) { for (j = 0; j < cols_b; j++) { int sum = 0; for (k = 0; k < ROWS_B; k++) { sum += matrix_a[i][k] * matrix_b[k][j]; } result[i][j] = sum; } } } int main() { int matrix_a[ROWS_A][COLS_A] = {{1, 2, 3}, {4, 5, 6}}; int matrix_b[ROWS_B][COLS_B] = {{7, 8, 9, 10}, {11, 12, 13, 14}, {15, 16, 17, 18}}; int result[ROWS_A][COLS_B]; // Multiply the matrices by passing them to a function multiply_matrices(matrix_a, matrix_b, result, ROWS_A, COLS_A, COLS_B); // Print the resulting matrix printf("Result Matrix:\n"); for (int i = 0; i < ROWS_A; i++) { for (int j = 0; j < COLS_B; j++) { printf("%d ", result[i][j]); } printf("\n"); } return 0; }Copy code`

In this example, we define a function multiply_matrices that takes in two matrices (matrix_a and matrix_b). As well as their dimensions (rows_a, cols_a, and cols_b) and a matrix to store the result (result). Inside the function, we use the same nested loops as before to perform the matrix multiplication and store the result in result.

In the main function, we declare the matrices matrix_a, matrix_b, and result, and pass them to the multiply_matrices function along with their dimensions.

The resulting matrix is then printed to the console using the same loop structure as before.

The output of this code will be the same as before:

This approach allows you to reuse the matrix multiplication code more easily and make your main function more readable.

You can also explore: Header Files in C Programming Language

Endnotes

A skew-symmetric matrix is a square matrix whose transpose is equal to its negative. In other words, it is a matrix that satisfies the condition A^T = -A. This type...read more

A matrix is a rectangular arrangement of numbers (real or complex) or symbols arranged in rows and columns. The number in the matrix are called the elements, and if the...read more

Matrix Multiplication in C
A matrix is a collection of numbers organized in rows and columns. Matrices can be manipulated using operations like Addition, Subtraction, and Multiplication. Multiplying two matrices is only possible when...read more

Types of Matrix
In Linear Algebra, Matrices are one of the most important topics of mathematics. The application of matrix is not just limited to mathematical solving problems; it has its applications across...read more

An Adjacency Matrix is a method of representing graphs in matrix form. The adjacency matrix plays a vital role in describing finite graphs, making them easier to understand and compact...read more

Lower Triangular Matrix: Definition, Example, and Properties
Discover the essentials of lower triangular matrices in linear algebra. Explore their unique properties, practical applications in solving linear systems, and their significance in mathematical computations. Perfect for students and...read more

Transpose of a Matrix
Transpose of a matrix is a matrix flipped over its main diagonal, switching the matrix’s rows and column indices. In this article, we will briefly discuss what transpose of a...read more

Confusion Matrix in Machine Learning
Are you tired of your AI models getting confused? Untangle their mysteries with the Confusion Matrix, your secret weapon for accuracy! Decode True Positives, False Negatives, and more to uncover...read more

Diagonal Matrix: Definition, Example, and Properties
A diagonal matrix is a special type of square matrix in which all non-diagonal entries are equal to zero, but all diagonal entries can either be zero or non-zero. This...read more

Identity Matrix: Definition, Examples, and Properties
A square matrix of order n x n with ones on the main diagonal and zeros elsewhere is known as an Identity Matrix. From solving a system of linear equations...read more

Why, How, and When to Adopt a Matrix Organizational Structure

Matrix Multiplication: A Beginner’s Guide to Understand and Implement
Matrix multiplication is a binary operation whose output is also a binary operation. If A and B are two matrices of order m x n and n x p, then the order of the output matrix will...read more

Upper Triangular Matrix: Definition, Example, and Properties
Explore the world of upper triangular matrices in our comprehensive guide. Understand their definition, properties, and practical applications in solving linear equations and beyond. Dive into the role of these...read more

How to Calculate the Determinant of a Matrix?
The determinant of a matrix is a scalar value that is calculated from the elements of the Square matrix. It is used to determine whether a given matrix is invertible...read more