Write A Program For Matrix Multiplication In C Using Array
In this article, you will learn how to perform matrix multiplication in C using two-dimensional arrays, covering the mathematical rules and a practical implementation.
Problem Statement
Matrix multiplication is a fundamental operation in linear algebra where two matrices are combined to produce a third matrix. The challenge lies in correctly implementing the specific rules: to multiply two matrices A (of dimension m x n) and B (of dimension n x p), the number of columns in A must equal the number of rows in B. The resulting matrix C will have dimensions m x p, where each element C[i][j] is the sum of the products of elements from row i of A and column j of B. This operation is crucial in various computational fields.
Example
Consider two matrices, Matrix A (2x3) and Matrix B (3x2):
Matrix A:
1 2 3
4 5 6
Matrix B:
7 8
9 1
2 3
To find the element at result[0][0]:
(1 * 7) + (2 * 9) + (3 * 2) = 7 + 18 + 6 = 31
To find the element at result[0][1]:
(1 * 8) + (2 * 1) + (3 * 3) = 8 + 2 + 9 = 19
Following this pattern, the resulting 2x2 matrix would be:
31 19
85 55
Background & Knowledge Prerequisites
To understand and implement matrix multiplication in C, readers should be familiar with:
- C Language Basics: Fundamental syntax, data types, and basic input/output operations.
- Arrays: Declaring and using one-dimensional and two-dimensional arrays.
- Loops:
forloops for iteration and nested loops for array traversal. - Functions: (Optional, but good practice for larger programs) Defining and calling functions.
For the implementation, no special imports or complex setup are required beyond the standard input/output library (stdio.h).
Use Cases or Case Studies
Matrix multiplication is widely applied across many domains due to its ability to represent complex transformations and relationships.
- Computer Graphics: Used extensively for transformations like scaling, rotation, and translation of 3D objects in games and simulations.
- Image Processing: Operations such as blurring, sharpening, and edge detection often involve multiplying image matrices with specific filter kernels.
- Machine Learning & AI: Neural networks rely heavily on matrix multiplications for processing data, updating weights, and calculating outputs in layers.
- Data Analysis: In statistics and data science, it's used for covariance matrices, principal component analysis (PCA), and solving systems of linear equations.
- Physics and Engineering: Solving systems of linear equations, finite element analysis, and quantum mechanics calculations frequently involve matrix operations.
Solution Approaches
The most common and straightforward approach for matrix multiplication involves using nested loops.
Standard Iterative Matrix Multiplication
This approach directly implements the mathematical definition of matrix multiplication using three nested for loops.
One-line summary: Iterates through rows of the first matrix, columns of the second matrix, and then sums the products of corresponding elements.
// Matrix Multiplication using Arrays
#include <stdio.h>
#define MAX_SIZE 10 // Define a maximum size for demonstration purposes
int main() {
int r1, c1, r2, c2; // Variables for rows and columns of matrix1, matrix2
// Step 1: Get dimensions for the first matrix from the user
printf("Enter number of rows for first matrix: ");
scanf("%d", &r1);
printf("Enter number of columns for first matrix: ");
scanf("%d", &c1);
// Step 2: Get dimensions for the second matrix from the user
printf("Enter number of rows for second matrix: ");
scanf("%d", &r2);
printf("Enter number of columns for second matrix: ");
scanf("%d", &c2);
// Step 3: Check for compatibility before multiplication
// The number of columns in the first matrix must equal the number of rows in the second matrix.
if (c1 != r2) {
printf("\\nError: Number of columns of the first matrix must be equal to the number of rows of the second matrix.\\n");
printf("Matrix multiplication is not possible with these dimensions.\\n");
return 1; // Indicate an error
}
// Declare 2D arrays for matrices and the result
int matrix1[MAX_SIZE][MAX_SIZE];
int matrix2[MAX_SIZE][MAX_SIZE];
int result[MAX_SIZE][MAX_SIZE];
// Step 4: Get elements for the first matrix from the user
printf("\\nEnter elements of the first matrix:\\n");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c1; j++) {
printf("Enter element matrix1[%d][%d]: ", i, j);
scanf("%d", &matrix1[i][j]);
}
}
// Step 5: Get elements for the second matrix from the user
printf("\\nEnter elements of the second matrix:\\n");
for (int i = 0; i < r2; i++) {
for (int j = 0; j < c2; j++) {
printf("Enter element matrix2[%d][%d]: ", i, j);
scanf("%d", &matrix2[i][j]);
}
}
// Step 6: Initialize all elements of the result matrix to zero
// This is crucial because we will be accumulating sums into these elements.
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
result[i][j] = 0;
}
}
// Step 7: Perform matrix multiplication
// The core logic involves three nested loops:
// Outer loop (i): Iterates through rows of the first matrix (and result matrix).
// Middle loop (j): Iterates through columns of the second matrix (and result matrix).
// Inner loop (k): Iterates through columns of the first matrix (which must match rows of the second matrix).
// This loop calculates each element result[i][j] by summing products.
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) { // Or k < r2, since c1 == r2
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
// Step 8: Display the resultant matrix
printf("\\nResultant Matrix:\\n");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
printf("%d\\t", result[i][j]); // Print element followed by a tab
}
printf("\\n"); // Move to the next line after printing a row
}
return 0; // Indicate successful execution
}
Sample Output:
Enter number of rows for first matrix: 2
Enter number of columns for first matrix: 3
Enter number of rows for second matrix: 3
Enter number of columns for second matrix: 2
Enter elements of the first matrix:
Enter element matrix1[0][0]: 1
Enter element matrix1[0][1]: 2
Enter element matrix1[0][2]: 3
Enter element matrix1[1][0]: 4
Enter element matrix1[1][1]: 5
Enter element matrix1[1][2]: 6
Enter elements of the second matrix:
Enter element matrix2[0][0]: 7
Enter element matrix2[0][1]: 8
Enter element matrix2[1][0]: 9
Enter element matrix2[1][1]: 1
Enter element matrix2[2][0]: 2
Enter element matrix2[2][1]: 3
Resultant Matrix:
31 19
85 55
Stepwise Explanation:
- Get Dimensions: The program first prompts the user to enter the number of rows and columns for both matrices. This determines their sizes.
- Compatibility Check: A crucial validation step ensures that the number of columns of the first matrix matches the number of rows of the second matrix. If not, multiplication is impossible, and an error message is displayed.
- Declare Arrays: Three two-dimensional integer arrays (
matrix1,matrix2,result) are declared.MAX_SIZEis used to define a compile-time maximum dimension for simplicity; for very large matrices or unknown sizes at compile time, dynamic memory allocation with pointers would be used. - Populate Matrices: Using nested
forloops, the program prompts the user to enter each element formatrix1andmatrix2. - Initialize Result Matrix: Before performing multiplication, all elements of the
resultmatrix are initialized to0. This is vital because the multiplication process involves accumulating sums. - Perform Multiplication (Triple Nested Loop):
- The outermost loop (
i) iterates through each row of the first matrix (and consequently, each row of theresultmatrix).
- The outermost loop (
j) iterates through each column of the second matrix (and consequently, each column of the result matrix).k) performs the actual element-wise multiplication and summation. For each result[i][j], it iterates k from 0 up to c1-1 (or r2-1), calculating matrix1[i][k] * matrix2[k][j] and adding it to result[i][j].- Display Result: Finally, another pair of nested
forloops iterates through theresultmatrix and prints its elements in a formatted way.
Conclusion
Implementing matrix multiplication in C using arrays is a fundamental programming exercise that reinforces understanding of nested loops and array manipulation. By following the mathematical rules, a robust program can be created that takes user input for matrix dimensions and elements, performs the multiplication, and displays the resultant matrix, handling compatibility checks effectively.
Summary
- Matrix multiplication requires that the number of columns in the first matrix equals the number of rows in the second.
- The resulting matrix has dimensions of
rows_first_matrix x columns_second_matrix. - Each element
result[i][j]is calculated by summing the products of elements from rowiof the first matrix and columnjof the second matrix. - A triple-nested
forloop structure is commonly used to implement this operation in C. - The
resultmatrix elements must be initialized to zero before accumulation.