C 语言中的矩阵乘法

CCBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,我们将使用 C 语言编写一个矩阵乘法程序。我们将学习如何创建矩阵、执行矩阵操作,并讨论矩阵乘法的标准算法。我们将创建一个 C 程序来对两个矩阵进行乘法运算,并打印结果矩阵。

注意:你需要自己创建文件 ~/project/main.c 来练习编码,并学习如何使用 gcc 编译和运行它。

cd ~/project
## 创建 main.c
touch main.c
## 编译 main.c
gcc main.c -o main
## 运行 main
./main

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c/BasicsGroup -.-> c/variables("`Variables`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/CompoundTypesGroup -.-> c/arrays("`Arrays`") c/UserInteractionGroup -.-> c/user_input("`User Input`") subgraph Lab Skills c/variables -.-> lab-123281{{"`C 语言中的矩阵乘法`"}} c/for_loop -.-> lab-123281{{"`C 语言中的矩阵乘法`"}} c/arrays -.-> lab-123281{{"`C 语言中的矩阵乘法`"}} c/user_input -.-> lab-123281{{"`C 语言中的矩阵乘法`"}} end

创建矩阵

首先,让我们学习如何创建矩阵。矩阵是一个二维数组。以下是一个在 C 语言中声明并初始化一个 2x2 矩阵的示例:

int matrix[2][2] = {{1, 2}, {3, 4}};

我们可以使用两个索引来访问矩阵中的特定元素,如下例所示:

int element = matrix[1][0];

矩阵与标量值的乘法

矩阵与单个值的乘法非常简单,具体实现如下:

int arr[2][2], n;
// 输入标量值
scanf("%d", &n);

// 输入矩阵元素
for(int i = 0; i < 2; i++) {
    for(int j = 0; j < 2; j++){
        scanf("%d", &arr[i][j]);
    }
}
// 将矩阵的每个元素与标量值相乘
for(int i = 0; i < 2; i++) {
    for(int j = 0; j < 2; j++){
        arr[i][j] = arr[i][j] * n;
    }
}

// 打印更新后的矩阵元素
for(int i = 0; i < 2; i++) {
    for(int j = 0; j < 2; j++){
        printf("%d ", arr[i][j]);
    }
    printf("\n");
}

该程序将矩阵的每个元素与用户输入的标量值相乘,然后打印更新后的矩阵。

两个矩阵的乘法

要对两个矩阵进行乘法运算,你需要遵循一定的规则。首先,第一个矩阵的列数必须等于第二个矩阵的行数。其次,结果矩阵的行数与第一个矩阵相同,列数与第二个矩阵相同。

假设我们有两个矩阵:

A = {{1, 3, 5},
     {4, 2, 6}};

B = {{7, 4},
     {3, 1},
     {6, 9}};

要对这两个矩阵进行乘法运算,我们需要对它们的行和列执行点积运算。矩阵元素的乘法使用以下公式:

result[row][col] = matrix1[row][0] * matrix2[0][col]
                  + matrix1[row][1] * matrix2[1][col]
                  + matrix1[row][2] * matrix2[2][col]
                  + ...;

以下是一个关于矩阵乘法的 C 程序:

#include <stdio.h>

int main()
{
  int m, n, p, q, c, d, k, sum = 0;

  // 定义两个矩阵
  int first[10][10], second[10][10], result[10][10];

  // 输入第一个矩阵的行数和列数
  printf("Enter the number of rows and columns of the first matrix:\n");
  scanf("%d %d", &m, &n);

  // 输入第一个矩阵的元素
  printf("Enter the %d elements of the first matrix:\n", m * n);
  for (c = 0; c < m; c++) {
    for (d = 0; d < n; d++) {
      scanf("%d", &first[c][d]);
    }
  }

  // 输入第二个矩阵的行数和列数
  printf("Enter the number of rows and columns of the second matrix:\n");
  scanf("%d %d", &p, &q);

  // 输入第二个矩阵的元素
  printf("Enter the %d elements of the second matrix:\n", p * q);
  for (c = 0; c < p; c++) {
    for (d = 0; d < q; d++) {
      scanf("%d", &second[c][d]);
    }
  }

  // 检查矩阵是否可以相乘
  if (n != p) {
    printf("Matrices cannot be multiplied with each other.\n");
  } else {
    // 矩阵相乘
    for (c = 0; c < m; c++) {
      for (d = 0; d < q; d++) {
        for (k = 0; k < p; k++) {
          sum = sum + first[c][k] * second[k][d];
        }
        result[c][d] = sum;
        sum = 0;
      }
    }

    // 打印结果矩阵
    printf("The resulting matrix is:\n");
    for (c = 0; c < m; c++) {
      for (d = 0; d < q; d++) {
        printf("%d\t", result[c][d]);
      }
      printf("\n");
    }
  }

  return 0;
}

该程序会要求用户输入两个矩阵的元素,检查它们是否可以相乘,如果可以则进行乘法运算,并打印结果矩阵。

完整程序

以下是结合所有步骤的完整程序:

#include<stdio.h>

int main()
{
    int n, m, c, d, p, q, k, first[10][10], second[10][10], pro[10][10], sum = 0;

    printf("\nEnter the number of rows and columns of the first matrix: \n\n");
    scanf("%d%d", &m, &n);

    printf("\nEnter the %d elements of the first matrix: \n\n", m*n);
    for(c = 0; c < m; c++) {
        for(d = 0; d < n; d++) {
            scanf("%d", &first[c][d]);
        }
    }

    printf("\nEnter the number of rows and columns of the first matrix: \n\n");
    scanf("%d%d", &p, &q);

    if(n != p)
        printf("Matrices with the given order cannot be multiplied with each other.\n\n");

    else {
        printf("\nEnter the %d elements of the second matrix: \n\n",m*n);

        for(c = 0; c < p; c++) {
            for(d = 0; d < q; d++) {
                scanf("%d", &second[c][d]);
            }
        }

        printf("\n\nThe first matrix is: \n\n");
        for(c = 0; c < m; c++) {
            for(d = 0; d < n; d++) {
                printf("%d\t", first[c][d]);
            }
            printf("\n");
        }

        printf("\n\nThe second matrix is: \n\n");
        for(c = 0; c < p; c++) {
            for(d = 0; d < q; d++){
                printf("%d\t", second[c][d]);
            }
            printf("\n");
        }

        for(c = 0; c < m; c++) {
            for(d = 0; d < q; d++) {
                for(k = 0; k < p; k++) {
                    sum = sum + first[c][k] * second[k][d];
                }
                pro[c][d] = sum;
                sum = 0;
            }
        }

        printf("\n\nThe multiplication of the two entered matrices is: \n\n");
        for(c = 0; c < m; c++) {
            for(d = 0; d < q; d++) {
                printf("%d\t", pro[c][d]);
            }
            printf("\n");
        }
    }
    printf("\n\n\t\t\tCoding is Fun !\n\n\n");
    return 0;
}

总结

在本实验中,我们学习了如何在 C 语言中创建矩阵,以及可以执行的不同类型的矩阵乘法操作。我们创建了一个程序来计算两个矩阵的乘法,并讨论了矩阵乘法的标准算法。

您可能感兴趣的其他 C 教程