# Thread: multiplying a matrix and vector:

1. ## multiplying a matrix and vector:

the logic for multiplying a matrix: mat[row][col] and a vector : vec[row]

is the following?

Code:
```double *ans = malloc(rows * sizeof (double));
int i;
for (i=0; i<rows; rows++)
for (i=0; i<cols; cols++)
ans[rows] = ans[rows] + mat[rows][cols] * vec[rows];```
It does not give the right answer.. anyone know what is wrong?
I used this site for the formula: Matrix-Vector Algebra

2. Because you are using rows and cols instead of the entry indices.

3. oh thanks, well i changed to:
Code:
```#include <stdlib.h>
/* Multiply a matrix by a vector. */
double *matrix_vector_multiply(int rows, int cols,
double **mat, double *vec)
{

double *ans = malloc(rows * sizeof (double));

int i,j;
for (i=0; i<rows; rows++)
ans[i]=0;

for (i=0; i<rows; rows++){

for (j=0; j<cols; cols++)
{
ans[i] =  mat[i][j]*vec[i] + mat[i][j+1]*vec[i];
}
}
return ans;
}
```

why is it still not working?

4. Because you are not adding the right things. Look carefully at the article that you linked to, in particular the animated graphic that circles the terms that are multiplied and added.

5. for (i=0; i<rows; rows++){

for (j=0; j<cols; cols++)
{

ans[i] = ans[i] + mat[i][j] * vec[j];
}
}

still 0s

6. That looks more like it, though you still have to test to check

By the way, you did well to post in [code][/code] bbcode tags in your first post. Don't stop, and don't introduce special syntax highlighting beyond what the forum software provides to us.