简体   繁体   中英

Matrix Multiplication using C++

(r1,c1) and (r2,c2) are number of Rows and columns of matrix a[][] and matrix b[][] matrix c[][] is the matrix multiplication of a[][] and b[][] The user enters the number of rows and columns of a[][] and b[][] and enters elements of both.

this is the output given by the complete program for specific a[][], b[][]

the expected output of the program for the same a[][] and b[][] is: c[2][2]={{7,14},{17,34}}

However, I cant seem to find the error in the logic.

the following part of the code is the logic to carry out the matrix multiplication

for (i = 0; i < r1; i++) {
  for (j = 0; j < c2; j++) {
    c[i][j] = 0;
    for (k = 0; k < c1; k++) {
      c[i][j] += a[i][j] * b[k][j];
    }
  }
}
for (i = 0; i < r1; i++) {
  for (j = 0; j < c2; j++) {
    printf("%d ", c[i][j]);
  }
  printf("\n");
}     

You are doing math incorrectly.

According to mat multiplication,

在此处输入图片说明

for(i=0 ; i<r1 ; i++)
{
    for(j=0 ; j<c2 ; j++) 
    {

        c[i][j]=0; 
        for(k=0 ; k<c1 ; k++)  
        {
            c[i][j]+=a[i][j]*b[k][j];
                      //--^-- should be k 
        }
    }
}

Some strategic renaming gives

for(int row = 0; row < r1; row++)
{
    for(int column = 0; column < c2; column++) 
    {       
        c[row][column] = 0; 
        for(int element = 0; element < c1 ; element++)  
        {
            c[row][column] += a[row][column] * b[element][column]; 
        }
    }
}

where you can see more clearly that the multiplication is wrong - you're multiplying with the same element from a in every step.

It should be

c[row][column] += a[row][element] * b[element][column]; 

我想这可以帮助您解决问题:

c[i][j]+=a[i][k]*b[k][j]; 

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