简体   繁体   中英

Matrix Multiplication in C language

I am trying to multiply 2 dimensional matrices in C language. I have furnished below the code for your reference. When I try to print 'myC', I keep getting zeros out. 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. 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). the above statement has to be kept inside 3 nested for loops. 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.

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

It should be in a triple-loop, where you set ij and k appropriately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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