Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matrix Multiplication using C++

Tags:

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");
}     
like image 227
Pranav Avatar asked Apr 29 '26 14:04

Pranav


1 Answers

You are doing math incorrectly.

According to mat multiplication,

enter image description here

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 
        }
    }
}
like image 85
asmmo Avatar answered May 02 '26 03:05

asmmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!