How to write code for matrix multiplication in C language?

Here is a simple code example for multiplying matrices in the C programming language.

#include <stdio.h>

#define SIZE 3

void multiplyMatrix(int mat1[][SIZE], int mat2[][SIZE], int result[][SIZE]) {
    int i, j, k;

    // 矩阵相乘
    for (i = 0; i < SIZE; i++) {
        for (j = 0; j < SIZE; j++) {
            result[i][j] = 0;
            for (k = 0; k < SIZE; k++) {
                result[i][j] += mat1[i][k] * mat2[k][j];
            }
        }
    }
}

void displayMatrix(int matrix[][SIZE]) {
    int i, j;

    // 打印矩阵
    for (i = 0; i < SIZE; i++) {
        for (j = 0; j < SIZE; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int mat1[SIZE][SIZE] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
    int mat2[SIZE][SIZE] = { {9, 8, 7}, {6, 5, 4}, {3, 2, 1} };
    int result[SIZE][SIZE];

    multiplyMatrix(mat1, mat2, result);
    displayMatrix(result);

    return 0;
}

In the code above, we have defined a function named multiplyMatrix that takes in two 2D arrays as parameters, representing two matrices, and a 2D array to store the result. The function uses three loops to calculate the multiplication of the matrices.

The displayMatrix function is used to print the resulting matrix.

In the main function, we define two matrices mat1 and mat2 and store the result in result, then call the multiplyMatrix function to calculate the result, and finally call the displayMatrix function to print the result.

The code above is just a simple example with a matrix size of 3×3 that you can change according to your needs.

bannerAds