C Program For Matrix Multiplication Using 2d Array
Matrix multiplication is a fundamental operation in linear algebra with widespread applications across various fields. Understanding how to perform this operation programmatically is crucial for many computing tasks.
In this article, you will learn how to implement matrix multiplication using 2D arrays in C.
Problem Statement
The core problem is to multiply two given matrices, say matrix A and matrix B, to produce a result matrix C. For two matrices A (with dimensions M x N) and B (with dimensions N x P) to be multiplied, the number of columns in A must be equal to the number of rows in B. The resulting matrix C will have dimensions M x P.
Each element C<sub>ij</sub> of the product matrix C is calculated as the dot product of the i-th row of matrix A and the j-th column of matrix B. That is, C<sub>ij</sub> = Σ (A<sub>ik</sub> * B<sub>kj</sub>) for k from 0 to N-1.
Example
Consider two matrices:
Matrix A (2x3):
1 2 3
4 5 6
Matrix B (3x2):
7 8
9 1
2 3
The resulting matrix C (2x2) would be:
C[0][0] = (1*7) + (2*9) + (3*2) = 7 + 18 + 6 = 31
C[0][1] = (1*8) + (2*1) + (3*3) = 8 + 2 + 9 = 19
C[1][0] = (4*7) + (5*9) + (6*2) = 28 + 45 + 12 = 85
C[1][1] = (4*8) + (5*1) + (6*3) = 32 + 5 + 18 = 55
Resulting Matrix C (2x2):
31 19
85 55
Background & Knowledge Prerequisites
To understand matrix multiplication in C using 2D arrays, you should have a basic understanding of:
- C Language Basics: Variables, data types, operators, and fundamental control structures like
forloops. - Arrays in C: How to declare, initialize, and access elements of one-dimensional arrays.
- 2D Arrays in C: Understanding how 2D arrays are stored in memory and how to access elements using
array[row][column]syntax. - Basic Linear Algebra: Concepts of matrices, rows, columns, and the definition of matrix multiplication.
Use Cases or Case Studies
Matrix multiplication is a cornerstone operation in many fields:
- Computer Graphics: Used extensively for transformations (translation, scaling, rotation) of 3D objects and camera views.
- Machine Learning and Deep Learning: Essential for operations within neural networks, such as calculating weighted sums in layers and performing transformations on data.
- Image Processing: Applied in various image filters (e.g., blurring, sharpening, edge detection) where filter kernels are convolved with image regions.
- Physics and Engineering: Solving systems of linear equations, simulating complex systems, and analyzing data in fields like structural analysis and quantum mechanics.
- Data Analysis: Used in statistical models, principal component analysis (PCA), and other data manipulation tasks.
Solution Approaches
The fundamental algorithm for matrix multiplication involves three nested loops. We'll explore two approaches: one with fixed-size matrices for clarity and another with user-defined matrices for flexibility.
Approach 1: Matrix Multiplication with Fixed-Size Matrices
This approach demonstrates the core logic of matrix multiplication using pre-defined matrices.
- One-line summary: Implements the standard matrix multiplication algorithm using three nested loops for fixed-size 2D arrays.
// Matrix Multiplication Fixed Size
#include <stdio.h>
#define ROW1 2
#define COL1 3
#define ROW2 3
#define COL2 2
int main() {
// Step 1: Declare and initialize matrices
int matrix1[ROW1][COL1] = {{1, 2, 3}, {4, 5, 6}};
int matrix2[ROW2][COL2] = {{7, 8}, {9, 1}, {2, 3}};
int result[ROW1][COL2]; // Result matrix dimensions: ROW1 x COL2
// Step 2: Check for valid multiplication dimensions
// For multiplication, COL1 must be equal to ROW2
if (COL1 != ROW2) {
printf("Error: Matrices cannot be multiplied. Number of columns in Matrix1 must equal number of rows in Matrix2.\\n");
return 1; // Indicate an error
}
// Step 3: Initialize the result matrix with zeros
for (int i = 0; i < ROW1; i++) {
for (int j = 0; j < COL2; j++) {
result[i][j] = 0;
}
}
// Step 4: Perform matrix multiplication
// Outer loops iterate through rows of matrix1 (i) and columns of matrix2 (j)
for (int i = 0; i < ROW1; i++) {
for (int j = 0; j < COL2; j++) {
// Inner loop calculates the dot product
for (int k = 0; k < COL1; k++) { // Or k < ROW2, since COL1 == ROW2
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
// Step 5: Print the result matrix
printf("Resultant Matrix C (%dx%d):\\n", ROW1, COL2);
for (int i = 0; i < ROW1; i++) {
for (int j = 0; j < COL2; j++) {
printf("%d\\t", result[i][j]);
}
printf("\\n");
}
return 0;
}
- Sample Output:
Resultant Matrix C (2x2):
31 19
85 55
- Stepwise Explanation:
- Define Dimensions and Matrices: We use preprocessor directives (
#define) for matrix dimensions and initialize two 2D integer arrays (matrix1,matrix2) with example values. Aresultmatrix is declared to store the product. - Dimension Check: An
ifstatement validates if the number of columns inmatrix1(COL1) equals the number of rows inmatrix2(ROW2). If not, multiplication is impossible, and an error message is displayed. - Initialize Result Matrix: The
resultmatrix is initialized with zeros. This is important because the multiplication logic involves accumulating sums. - Perform Multiplication:
- The outermost loop (
for i) iterates through the rows ofmatrix1.
- The outermost loop (
for j) iterates through the columns of matrix2.for k) performs the dot product. It multiplies elements from the i-th row of matrix1 and the j-th column of matrix2, summing them up into result[i][j].- Print Result: Finally, the elements of the
resultmatrix are printed in a formatted way.
Approach 2: Matrix Multiplication with User-Defined Matrices
This approach extends the previous one by allowing the user to input the dimensions and elements of the matrices.
- One-line summary: Enables interactive input of matrix dimensions and elements before performing the standard matrix multiplication.
// Matrix Multiplication User Input
#include <stdio.h>
#define MAX_SIZE 10 // Maximum size for matrix dimensions
int main() {
int row1, col1, row2, col2;
int matrix1[MAX_SIZE][MAX_SIZE];
int matrix2[MAX_SIZE][MAX_SIZE];
int result[MAX_SIZE][MAX_SIZE];
// Step 1: Get dimensions for Matrix 1 from user
printf("Enter dimensions for Matrix 1 (rows columns): ");
scanf("%d %d", &row1, &col1);
// Step 2: Get dimensions for Matrix 2 from user
printf("Enter dimensions for Matrix 2 (rows columns): ");
scanf("%d %d", &row2, &col2);
// Step 3: Check for valid multiplication dimensions
if (col1 != row2) {
printf("Error: Matrices cannot be multiplied. Number of columns in Matrix1 must equal number of rows in Matrix2.\\n");
return 1;
}
// Step 4: Get elements for Matrix 1 from user
printf("Enter elements for Matrix 1 (%dx%d):\\n", row1, col1);
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col1; j++) {
printf("Enter element matrix1[%d][%d]: ", i, j);
scanf("%d", &matrix1[i][j]);
}
}
// Step 5: Get elements for Matrix 2 from user
printf("Enter elements for Matrix 2 (%dx%d):\\n", row2, col2);
for (int i = 0; i < row2; i++) {
for (int j = 0; j < col2; j++) {
printf("Enter element matrix2[%d][%d]: ", i, j);
scanf("%d", &matrix2[i][j]);
}
}
// Step 6: Initialize the result matrix with zeros
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
result[i][j] = 0;
}
}
// Step 7: Perform matrix multiplication (same logic as Approach 1)
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
for (int k = 0; k < col1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
// Step 8: Print the result matrix
printf("\\nResultant Matrix C (%dx%d):\\n", row1, col2);
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
printf("%d\\t", result[i][j]);
}
printf("\\n");
}
return 0;
}
- Sample Output (using the example matrices):
Enter dimensions for Matrix 1 (rows columns): 2 3
Enter dimensions for Matrix 2 (rows columns): 3 2
Enter elements for Matrix 1 (2x3):
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 for Matrix 2 (3x2):
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 C (2x2):
31 19
85 55
- Stepwise Explanation:
- Declare Variables:
row1,col1,row2,col2are declared to store user-defined dimensions. Matrices are declared with aMAX_SIZEto handle various inputs. - Get Dimensions: The program prompts the user to enter the number of rows and columns for both matrices using
scanf. - Dimension Check: The same dimension compatibility check (
col1 != row2) is performed. - Get Elements: Nested loops are used to prompt the user to enter each element of
matrix1andmatrix2sequentially. - Initialize Result: The
resultmatrix is initialized with zeros, just like in Approach 1. - Perform Multiplication: The core triple-nested loop logic remains identical to Approach 1, operating on the user-provided matrices.
- Print Result: The final product matrix is printed.
Conclusion
Implementing matrix multiplication in C using 2D arrays relies on a straightforward triple-nested loop structure. The outer two loops determine the position in the result matrix, while the innermost loop calculates the dot product of the corresponding row and column. Always remember to check for dimension compatibility before attempting multiplication, as it's a critical prerequisite for the operation.
Summary
- Matrix multiplication involves multiplying elements of rows from the first matrix with elements of columns from the second matrix and summing the products.
- A key condition for matrix multiplication is that the number of columns in the first matrix must equal the number of rows in the second matrix.
- The resulting matrix will have dimensions (rows of first matrix) x (columns of second matrix).
- The standard implementation uses three nested
forloops to iterate through rows, columns, and the summation index. - Matrix multiplication has broad applications in computer graphics, machine learning, image processing, and scientific computing.