Reputation: 23
(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");
}
Upvotes: 2
Views: 1020
Reputation: 46
I guess that this could help you to solve your problem:
c[i][j]+=a[i][k]*b[k][j];
Upvotes: 2
Reputation: 7100
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
}
}
}
Upvotes: 3
Reputation: 66371
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];
Upvotes: 3