C Program For Matrix Multiplication Using Arrays
Matrices are fundamental mathematical structures used across various fields, and their multiplication is a core operation. In this article, you will learn how to implement matrix multiplication using arrays in the C programming language.
Problem Statement
Matrix multiplication is a binary operation that produces a matrix from two matrices. Unlike element-wise multiplication, it involves a more complex calculation where elements of rows from the first matrix are multiplied by corresponding elements of columns from the second matrix and then summed. This operation is only defined if the number of columns in the first matrix equals the number of rows in the second matrix. The resulting matrix will have the number of rows of the first matrix and the number of columns of the second.
For example, if matrix A is an M x N matrix and matrix B is an N x P matrix, their product C will be an M x P matrix. Each element C[i][j] is calculated as the sum of A[i][k] * B[k][j] for k from 0 to N-1. Implementing this accurately and efficiently in C requires careful management of array indexing and nested loops.
Example
Consider two matrices, A and B:
Matrix A (2x3):
1 2 3
4 5 6
Matrix B (3x2):
7 8
9 10
11 12
Their product, Matrix C (2x2), would be:
(1*7 + 2*9 + 3*11) (1*8 + 2*10 + 3*12)
(4*7 + 5*9 + 6*11) (4*8 + 5*10 + 6*12)
Which simplifies to:
(7 + 18 + 33) (8 + 20 + 36)
(28 + 45 + 66) (32 + 50 + 72)
Result Matrix C (2x2):
58 64
139 154
Background & Knowledge Prerequisites
To understand and implement matrix multiplication in C, readers should be familiar with:
- C Basics: Fundamental syntax, data types, and variable declarations.
- Arrays: Declaring and accessing elements in one-dimensional and multi-dimensional arrays (especially 2D arrays).
- Loops: Using
forloops, including nested loops, to iterate over array elements. - Input/Output: Basic
printfandscanffunctions for displaying and reading data.
Use Cases or Case Studies
Matrix multiplication is a fundamental operation with wide-ranging applications:
- Computer Graphics: Used for 2D and 3D transformations such as translation, scaling, rotation, and projection of objects in game engines and CAD software.
- Image Processing: Applied in filters (e.g., convolution kernels for blurring, sharpening, edge detection), image compression, and transformations.
- Machine Learning and Deep Learning: Core operation in neural networks for calculations within layers, particularly in dot products and convolutions.
- Physics and Engineering: Solving systems of linear equations, simulating physical systems, and analyzing structural integrity.
- Data Science and Statistics: Performing principal component analysis (PCA), regression analysis, and other statistical computations involving large datasets.
Solution Approaches
The most common and straightforward approach for matrix multiplication involves using three nested for loops.
Standard Iterative Matrix Multiplication
This approach directly implements the mathematical definition of matrix multiplication by iterating through each element of the resulting matrix and calculating its value.
Code Example:
// Matrix Multiplication
#include <stdio.h>
#define ROW1 2 // Rows of first matrix
#define COL1 3 // Columns of first matrix
#define ROW2 3 // Rows of second matrix
#define COL2 2 // Columns of second matrix
int main() {
// Step 1: Declare matrices and result matrix
int matrixA[ROW1][COL1] = {
{1, 2, 3},
{4, 5, 6}
};
int matrixB[ROW2][COL2] = {
{7, 8},
{9, 10},
{11, 12}
};
int resultMatrix[ROW1][COL2]; // Resulting matrix dimensions: ROW1 x COL2
// Check if multiplication is possible
if (COL1 != ROW2) {
printf("Error: Matrix multiplication not possible. Number of columns in Matrix A must be equal to number of rows in Matrix B.\\n");
return 1; // Indicate an error
}
// Step 2: Initialize result matrix elements to 0
for (int i = 0; i < ROW1; i++) {
for (int j = 0; j < COL2; j++) {
resultMatrix[i][j] = 0;
}
}
// Step 3: Perform matrix multiplication
// i iterates through rows of matrixA (and resultMatrix)
for (int i = 0; i < ROW1; i++) {
// j iterates through columns of matrixB (and resultMatrix)
for (int j = 0; j < COL2; j++) {
// k iterates through columns of matrixA (and rows of matrixB)
for (int k = 0; k < COL1; k++) { // Or ROW2, they must be equal
resultMatrix[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
// Step 4: Display the result matrix
printf("Resultant Matrix C (A * B):\\n");
for (int i = 0; i < ROW1; i++) {
for (int j = 0; j < COL2; j++) {
printf("%d\\t", resultMatrix[i][j]);
}
printf("\\n");
}
return 0;
}
Sample Output:
Resultant Matrix C (A * B):
58 64
139 154
Stepwise Explanation:
- Declare Matrices: Define
matrixA,matrixB, andresultMatrixusing 2D arrays. Macro definitions (ROW1,COL1, etc.) are used for clarity and easy modification of matrix dimensions. A crucial checkCOL1 != ROW2is included to ensure that matrix multiplication is mathematically valid. - Initialize Result Matrix: Before starting the multiplication, all elements of
resultMatrixare initialized to zero. This is essential because the calculation involves summing products. - Perform Multiplication with Nested Loops:
- The outermost loop (
for int i) iterates through the rows of the first matrix (matrixA) and consequently, the rows of theresultMatrix.
- The outermost loop (
for int j) iterates through the columns of the second matrix (matrixB) and the columns of the resultMatrix.for int k) performs the actual multiplication and summation. For each element resultMatrix[i][j], it sums the products of elements from the i-th row of matrixA and the j-th column of matrixB. The k index moves along the column of matrixA and the row of matrixB.- Display Result: After all calculations are complete, another set of nested loops is used to print the elements of the
resultMatrixin a formatted way.
Conclusion
Implementing matrix multiplication in C using arrays is a fundamental programming exercise that demonstrates the power of nested loops for complex mathematical operations. While the standard iterative approach is simple and effective for smaller matrices, understanding its underlying mechanism is crucial for working with more advanced linear algebra concepts or optimizing performance for larger datasets.
Summary
- Matrix multiplication requires the number of columns in the first matrix to equal the number of rows in the second.
- The resulting matrix has dimensions of
rows_Axcols_B. - A three-nested
forloop structure is commonly used: - Outer loop for
resultMatrixrows (i). - Middle loop for
resultMatrixcolumns (j). - Inner loop for summation of products (
k). - The formula for each element
C[i][j]issum(A[i][k] * B[k][j]). - Matrix multiplication is vital in fields like graphics, machine learning, and scientific computing.