Search code examples
arrayscmultiplication

My matrix vector multiplication returns an incorrect vector value in c


I have a two dimension vector in my code that has elements in the following format

91 86 94
12 54 88
79 58 66

and a vector which contains elements in the following format

14
20
22

The code I developed in c for multipying the two returns the first two rows of the resultant(3x1) correctly but the third element is incorrect, I need help to revise my the multiplication loop so I get the correct values for all the resultant row members.. My code returns the following as the members of the result vector

5062
3184
10096598

When you calculate, you can see that the last value is incorrect, Arrays have been quite challenging to me in c, especially 2d arrays. Below is my code, you can create two csv files of your own and use this code to multiply the marix with the vector and see what you get and suggest changes


Solution

  • Your out_vec initialization is wrong: sizeof(out_vec) will only return the pointer size, 8 I guess, whereas your array weights 12.

    You wrote:

    int* out_vec = malloc(V_ROWS*sizeof(int));
    memset(out_vec, 0, sizeof(out_vec));
    

    It should have been :

    int* out_vec = malloc(V_ROWS*sizeof(int));
    memset(out_vec, 0, V_ROWS*sizeof(int));
    

    or better:

    int * out_vec = calloc(V_ROWS, sizeof(int));