How does k works in the code below?
# include <stdio.h>
# define R 2
# define C 2
int main(void)
{
int a[R][C], b[R][C], mul[R][C], i, j, k;
for (i = 0; i < R; i)
for (j = 0; j < C; j)
{
scanf_s("%d", &a[i][j]);
}
for (i = 0; i < R; i)
for (j = 0; j < C; j)
{
scanf_s("%d", &b[i][j]);
}
for (i = 0; i < R; i)
for (j = 0; j < C; j)
{
mul[i][j] = 0;
for (k = 0; k < C; k)
{
mul[i][j] = a[i][k] * b[k][j];
}
printf("%d", mul[i][j]);
if (j == 0)
{
printf(" ");
}
else if (i == 0 && j == 1)
{
printf("\n");
}
}
return 0;
}
For matrix addition, I know that in math sum[0][0] = a[0][0] b[0][0] and in code also be like this.
For matrix multiplication, it is mul[0][0] = a[0][0] x b[0][0] a[0][0] x b[1][0] in math.
However in code, [ ] is not only come from i and j but also k.
scanf_s("%d", &a[i][j]);
and scanf_s("%d", &b[i][j]);
has shown that %d are saved in memory a[i][j] and b[i][j].
So, what did k be read in mul[i][j] = a[i][k] * b[k][j];
?
CodePudding user response:
Your misunderstanding starts here:
For matrix multiplication, it is
mul[0][0] = a[0][0] x b[0][0] a[0][0] x b[1][0]
in math.
That's not how matrix multiplication works.
If you look at this code for i == 0
and j == 0
and C == 2
mul[i][j] = 0;
for (k = 0; k < C; k)
{
mul[i][j] = a[i][k] * b[k][j];
}
it becomes
mul[0][0] = 0;
for (k = 0; k < 2; k)
{
mul[0][0] = a[0][k] * b[k][0];
}
Since k
will take the values 0
and 1
it results in
mul[0][0] = a[0][0] * b[0][0] a[0][1] * b[1][0];
^ ^ ^ ^
k = 0 k = 1
As you can see this is different from what you expected. And it's the correct way to do it for multiplication in case of 2X2 matrix.
Had it been 3X3 matrix, it would be:
mul[0][0] = a[0][0] * b[0][0] a[0][1] * b[1][0] a[0][2] * b[2][0];
^ ^ ^ ^ ^ ^
k = 0 k = 1 k = 2
So the the loop using k
as index, takes care of multiplying a row from a
with a column of b
.