How can C language implement matrix multiplication?
In C language, nested loops can be used to multiply two matrices. The specific steps are as follows:
- Firstly, define two matrices, A and B, and determine their rows and columns.
- Create a result matrix C with the same number of rows as A and the same number of columns as B.
- Traverse the rows of matrix A and the columns of matrix B using nested loops.
- In a nested loop, calculate the value of each element in matrix C by multiplying and adding each element in the current row of matrix A with each element in the current column of matrix B.
- Assign the calculated result to the corresponding element of matrix C.
Here is an example code:
#include <stdio.h>
#define ROW_A 2 // A矩阵的行数
#define COL_A 3 // A矩阵的列数
#define ROW_B 3 // B矩阵的行数
#define COL_B 2 // B矩阵的列数
void multiplyMatrix(int A[][COL_A], int B[][COL_B], int C[][COL_B]) {
int i, j, k;
for (i = 0; i < ROW_A; i++) {
for (j = 0; j < COL_B; j++) {
C[i][j] = 0;
for (k = 0; k < COL_A; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
}
void printMatrix(int matrix[][COL_B], int row, int col) {
int i, j;
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int A[ROW_A][COL_A] = { {1, 2, 3}, {4, 5, 6} };
int B[ROW_B][COL_B] = { {7, 8}, {9, 10}, {11, 12} };
int C[ROW_A][COL_B];
multiplyMatrix(A, B, C);
printMatrix(C, ROW_A, COL_B);
return 0;
}
In the above code, the function multiplyMatrix is used to calculate matrix multiplication, and the function printMatrix is used to print the matrix. In the main function, we define two matrices, A and B, then call the multiplyMatrix function to calculate their product, and use the printMatrix function to print the result matrix C.