Matrix Vector Multiplication

Hello I have Problem with matrix vector multiplication, where is my mistake in program..can you give me any idea?

void matrixVector ( const int n, const double* A, const double* x, double* y ){

//for(int i = 0; i < n; i++){
// y[i*n] = 0.0;
// }
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
y[i*n] += A[i*n+j]*x[j*n];
}
}

for(int i=0; i<n; i++){
cout<<y[i*n]<<" ";

}

cout<<"\n";

}

int main(){

int n;
n=7;

double* A = new double[n*n];
double* x = new double[n];
double* y = new double[n];

for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
A[i*n+j] = rand()% 100 + 1;
cout<<A[i*n+j]<<" ";
}
cout<<"\n";
}
cout<<"\n";

for(int i=0; i<n; i++){
x[i*n] = rand()%100+1;
cout<<x[i*n]<<" ";


}
cout<<"\n";


matrixVector(n,A,x,y);

delete[] A;
delete[] x;
delete[] y;


return 0;

}
The size of x and y is n.
So x[i*n] or y[i*n] is out of bounds as soon as i is > 1

I'd guess that x/y are just row/column of the matrix?
Last edited on
It seems that A is a square matrix, x is a column vector, and the matrixVector computes A*x:
http://en.wikipedia.org/wiki/Matrix_multiplication#Square_matrix_and_column_vector


There are couple obvious "style reasons" for the "out of bounds" logic errors:

One is the use of use of 1D array for the logical 2D matrix, which requires distracting index calculations.

The other is the use of 'i' and 'j'. Easy to write, but less expressive than for example 'row' and 'col'. The better the names show the purpose, the easier it is to spot logical errors.
Thank you, ı have do it.
Topic archived. No new replies allowed.