Ethan Lee Ethan Lee - 2 months ago 18
C Question

C:Matrix times vector output

I tried to create a matrix times vector program, but when i run the program, i found that the output is a little bit weird

Here's my code

#include <stdio.h>

main()
{
int i, j, n, a[3][3], b[3], c[3];

n = 3;

printf("Matrix A\n");
for (i = 0; i < n; ++i) {
for (j = 0; j < n; ++j) {
a[i][j] = 10;
printf("%d ", a[i][j]);
}
printf("\n");
}

printf("\nMatrix B\n");
for (i = 0; i < n; ++i) {
b[i] = 5;
printf("%d\n", b[i]);
}

printf("\nA * B\n");

for (i = 0; i < n; ++i) {
for (j = 0; j < n; ++j) {
c[i] += a[j][i] * b[j];
}
}

for (i = 0; i < n; ++i) {
printf("%d\n", c[i]);
}
}


The result should be C = {150,150,150}. The problem seems only in c[0] and c[2]

Answer

The problem is that C does not initialise variables to 0, you must do it yourself.

Change the for loop calculating c as follows:

for (i = 0; i < n; ++i) {
    c[i]=0;      // Add this line so that c[i] can be used in: c[i] += ....
    for (j = 0; j < n; ++j) {
         c[i] += a[j][i] * b[j];
    }
}