Matrix multiplication is an important operation in linear algebra and has several applications in computer science, physics, and engineering. In this article, we will discuss how to multiply two matrices in C language.
To multiply two matrices, we need to ensure that the number
of columns in the first matrix is equal to the number of rows in the second
matrix. Let A be a matrix of size m x n and B be a matrix of size n x p. The
resulting matrix C will be of size m x p.
The matrix multiplication algorithm can be performed using
nested loops. The outer loop iterates over the rows of the first matrix, and
the inner loop iterates over the columns of the second matrix. For each element
of the resulting matrix C, we multiply the corresponding row of matrix A with
the corresponding column of matrix B, and then sum the products.
Here is the C program to multiply two matrices using nested
loops:
#include <stdio.h>
#define ROW 3
#define COL 3
void matrix_multiply(int A[][COL], int B[][COL], int
C[][COL])
{
int i, j, k;
for (i = 0; i <
ROW; i++) {
for (j = 0; j
< COL; j++) {
C[i][j] =
0;
for (k =
0; k < COL; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
}
void print_matrix(int M[][COL])
{
int i, j;
for (i = 0; i <
ROW; i++) {
for (j = 0; j
< COL; j++) {
printf("%d ", M[i][j]);
}
printf("\n");
}
}
int main()
{
int A[ROW][COL] =
{{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int B[ROW][COL] =
{{10, 11, 12},
{13, 14, 15},
{16, 17, 18}};
int C[ROW][COL];
matrix_multiply(A,
B, C);
printf("Matrix A:\n");
print_matrix(A);
printf("Matrix B:\n");
print_matrix(B);
printf("Resulting Matrix C:\n");
print_matrix(C);
return 0;
}
In this program, we define three matrices A, B, and C. We
then call the matrix_multiply function to perform the multiplication of
matrices A and B, and store the result in matrix C. Finally, we print the
matrices A, B, and C using the print_matrix function.
The output of the above program is:
Matrix A:
1 2 3
4 5 6
7 8 9
Matrix B:
10 11 12
13 14 15
16 17 18
Resulting Matrix C:
84 90 96
201 216 231
318 342 366
Thus, we can see that the program has correctly multiplied
the two matrices and stored the result in matrix C.
In conclusion, matrix multiplication is a fundamental
operation in linear algebra and has several applications in computer science.
We can implement matrix multiplication in C language using nested loops and the
algorithm described above.
No comments: