C中的矩阵乘法

我正在尝试用C解决矩阵乘法问题。问题(2×2)中给出的矩阵大小我编写了这段代码,但它没有像我期望的那样打印结果。 我想我对C的规则缺少一点。

我在这段代码中的错误是什么?

#include  int main() { int matA[2][2]={0,1,2,3}; int matB[2][2]={0,1,2,3}; int matC[2][2]; int i, j, k; for (i = 0; i < 2; i++) { for(j = 0; j < 2; j++) { for(k = 0; k < 2; k++) { matC[i][j] += matA[i][k] * matB[k][j]; } printf("%d\n",matC[i][j]); } } } 

打印结果:

 2 3 4195350 11 

问题是在线

 matC[i][j] += matA[i][k] * matB[k][j]; 

你正在向matC添加东西,但是当你创建它时,你没有初始化它,所以它有垃圾。

你可以这样做:

int matC[2][2] = {0} ,它将使用0初始化所有矩阵

这是我使用的矩阵乘法代码:

 for(i=0;i 

重要的是将答案矩阵设置为零(正如其他人所说的没有代码)。

matC最初包含一些垃圾值。 将martix初始化为全零。 这可能会解决您的问题

您可以通过以下方式使用任何给定大小的矩阵乘法:

 #include void main() { int r1, c1, r2, c2; printf("Enter number of rows and columns for matrix A : "); scanf("%d %d",&r1,&c1); printf("Enter number of rows and columns for matrix B : "); scanf("%d %d",&r2,&c2); int a[r1][c1], b[r2][c2], ab[r1][c2], ba[r2][c1],i,j,k,temp; if(c1==r2 && r1==c2) { printf("\nEnter element in matrix A : "); for(i=0;i 

您必须首先将C元素初始化为零。

您应该将matC初始化为全零。

如果大小和依赖关系无关紧要,我建议使用GNU科学库。 请参阅此处了解function: http : //en.wikipedia.org/wiki/GNU_Scientific_Library

它包含用于数学计算的优化例程,并且在一些编译器优化方面非常快。

已经成功用于3D开发中的矩阵操作。

您可能希望为结果矩阵动态分配内存。 如果是这样,请使用calloc()来分配和清除元素。 printMatrix()来打印结果,但这里没有定义。

 /* matrix1: [rows1 x cols1]; matrix2: [rows2 x cols2]; product is matrix3: [rows1 x cols2] if (cols1 == rows2) is true. calloc to allocate / clear memory for matrix3. Algorithm is O(n^3) */ float ** matrix3; if (cols1 == rows2) { // product matrix can be calculated // calloc product matrix3 matrix3 = (float **)calloc(rows1, sizeof(float *)); for (int i = 0; i < rows1; i++) matrix3[i] = (float *)calloc(cols2, sizeof(float)); int i, j, k; float tmp; for (i = 0; i < rows1; i++) { for (j = 0; j < cols2; j++) { tmp = 0.0; for (k = 0; k < rows2; k++) tmp += matrix1[i][k] * matrix2[k][j]; matrix3[i][j] = tmp; } } printMatrix(matrix3, rows1, cols2, 3); free(matrix3); } else { // cols1 != rows2 puts("dimensional mismatch; can't multiply matrices"); }