简体   繁体   English

C语言矩阵乘法

[英]Matrix Multiplication in C language

I am trying to multiply 2 dimensional matrices in C language. 我正在尝试在C语言中乘以二维矩阵。 I have furnished below the code for your reference. 我在下面提供了代码,供您参考。 When I try to print 'myC', I keep getting zeros out. 当我尝试打印'myC'时,我总是得到零。 Where am i going wrong ? 我要去哪里错了? I've tried multiple things and still can not figure this out. 我已经尝试了多种方法,但仍然无法解决。 Has anyone got ideas, that would be greatly appreciated. 有没有人有想法,将不胜感激。

#include <stdio.h> 
#define mysize 4 

int myA[mysize][mysize];
int myC[mysize][mysize];
int i,k;
int j,l;
int total;
int iLimit;
int jLimit;

void printMatrix(int iLimit,int jLimit,int myA[iLimit][jLimit]){
    i=0;
    while (i<iLimit){
        j=0;
        while (j<jLimit){
            printf ("%7d", myA[i][j]);
            j=j+1;
        }
        printf ("\n");
        i=i+1;}
}

int main(void){
    iLimit=mysize;
    jLimit=mysize;
    k=0;
    while (k < iLimit){
        l=0;
        while (l < jLimit) {
            scanf ("%d",&myA[k][l]);
            l=l+1;
        }
        k=k+1;
    }

    printMatrix(mysize,mysize,myA);
    myC[i][j]=myA[i][k]*myA[k][j];
    printf("\n");
    printMatrix(mysize,mysize,myC);
    return 0;
}

the multiplication of the matrices has to be done for all the elements. 必须对所有元素进行矩阵相乘。 so it should be in a nested for loop. 因此它应该在嵌套的for循环中。 what you are doing in your code 您在代码中正在做什么

myC[i][j]=myA[i][k]*myA[k][j];

this statement would multiply only one element of the matrix that is represented by the index i,j,k (out of bound in your code). 该语句将只乘以索引i,j,k表示的矩阵的一个元素(在代码中超出范围)。 the above statement has to be kept inside 3 nested for loops. 上面的语句必须保留在3个嵌套的for循环内。 something like this.. 像这样

for (i=0;i<m;i++)
{
   for(j=0;j<q;j++)
   {
       myC[i][j]=0;
       for(k=0;k<n;k++)
           myC[i][j]+= myA[i][k]*myA[k][j];
   }
}

This only multiplies two elements, where ij and k are all out of bounds. 这仅乘以两个元素,其中ij和k都超出范围。

 myC[i][j]=myA[i][k]*myA[k][j];

It should be in a triple-loop, where you set ij and k appropriately. 它应该处于三重循环中,您可以在其中适当地设置ij和k。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM