# Thread: Matrix vector multiplication using function

1. ## Matrix vector multiplication using function

Hi everybody,
What is wrong with the program below? it is supposed to multiply a matrix by vector.

Code:
```
#include <iostream>

using namespace std;

void matris_muller(double a[], double x,double *b);

int main(){

double a_cap[] = {1,0,0,0,2,0,0,0,3};
double x = {1,1,1};
double *b1;
matris_muller(a_cap , x , b1);

for (int i = 0 ; i <= 2; ++i)
cout<<"  "<<b1[i]<<endl;

}

void matirs_muller(double a[], double x,double *b){

for(int i = 0 ; i <= 2 ; ++i){
for(int j = 0 ; j <=  2; ++j){

b[j] += a[i][j] * x[j];
}
}

}``` 2. Try it with
Code:
`double b1 = { 0, 0, 0 };`
You need to make sure you're pointing at valid memory.

Just declaring a variable of the same type as the parameter isn't enough.

FWIW, all these are equivalent.
Code:
```void foo ( int arr );
void foo ( int arr[] );
void foo ( int *arr );```
The left-most size is ignored by the compiler, so people often omit it (as you have done above).

2D arrays are a little more complicated.

For example, this is equivalent to your declaration above.
Code:
`void matris_muller(double (*a), double *x, double *b);` 3. Your code, corrected and commented (with a bit of "optimizations"):
Code:
```#include <iostream>

// It helps (in terms of optimization to declare immutable
// arguments as 'const'. And, since the first array is incomplete,
// I've declared all of them incomplete... They must have 3 elements.
// Again, 'static' here is for the compiler benefict.
static void matris_muller ( const double a[], const double x[], double b[] );

int main()
{
// Just to be sure I divided the values in groups of 3.
// Nothing wrong not doing this, but, to me, is clearer.
//
// And... just for optimization sake, declaring as 'static const' will make
// the compiler put those arrays in .rodata section in compile time.
static const double a_cap[] = { { 1, 0, 0 }, { 0, 2, 0 }, { 0, 0, 3 } };
static const double x = { 1, 1, 1 };

double b1;   // FIXED: We have to allocate all 3 doubles! This time, in the stack.

matris_muller ( a_cap, x, b1 );

for ( int i = 0 ; i < 3; ++i )
std::cout << b1[i] << '\n';   // std::endl is used to flush the stream.
// for std::cout, '\n' will do the same, but cheaper.
}

// FIXED: The name of the function was wrong!
void matris_muller ( const double a[], const double x[], double b[] )
{
for ( int i = 0 ; i < 3 ; ++i )
for ( int j = 0 ; j < 3; ++j )
b[j] += a[i][j] * x[j];
}``` Popular pages Recent additions a_cap[], double, int, matrix, vector 