pyCthon
pyCthon

Reputation: 12361

setting a vector to a matrix algorithm help in C++

I have a array X that has M*N elements, I'm trying to create a matrix A of size M x N with this same data. I'm using gsl for the matrix and X is declared as an array. I'm having trouble and I keep getting overlap in the matrix.

Here is an example of what I am trying to do:

Vector X[4*2]
1,2,3,4,5,6,7,8

Matrix A 4X2
1, 2 
3, 4
5, 6
7, 8

//heres one of my many fail attempts as an example
//creation of array X here
X[n*m] = someCbasedformulafromtheweb(n, m);
//gsl matrix allocation for matrix A N x M
gsl_matrix * A = gsl_matrix_alloc(n, m);
for(int i=0; i<n; i++) { 
    for(int j=0; j<m; j++) { 
        // setting the x[i*j] entry to gsl_matrix A at positions i , j
        gsl_matrix_set (A,i,j, x[i*j]);
    }
}

Upvotes: 0

Views: 880

Answers (2)

Dan
Dan

Reputation: 10786

Your problem is at this line:

gsl_matrix_set (A,i,j, x[i*j]);

Here is the table of things:

i | j | x[i*j]
0 | 0 | x[0]
0 | 1 | x[0]
1 | 0 | x[0]
1 | 1 | x[1]
2 | 0 | x[0]
2 | 1 | x[2]
3 | 0 | x[0]
3 | 1 | x[3]

Instead you need to use:

gsl_matrix_set (A,i,j, x[2*i+j]);

i | j | x[2*i+j]
0 | 0 | x[0]
0 | 1 | x[1]
1 | 0 | x[2]
1 | 1 | x[3]
2 | 0 | x[4]
2 | 1 | x[5]
3 | 0 | x[6]
3 | 1 | x[7]

Upvotes: 1

Beta
Beta

Reputation: 99144

I don't have gsl to play with, but wouldn't this work?

for (i=0 ; i<4 ; ++i)
  for (j=0 ; j<2 ; ++j)
    X[2*i + j] = gsl_matrix_get (&A, i, j));

Upvotes: 2

Related Questions