qcc101
qcc101

Reputation: 123

Symmetric matrix, value into c++ vector

I am trying to solve the following problem. Let's say I have a symmetric matrix with size n. I want to take all the "important values", and store them into a vector. Let me give an example to explain it better.

Let's say I have the following matrix A = [1, 2, 3 // 2, 5, 6 // 3, 6, 9]. I want to define vector of size n*(n+1)/2 such that:

V = [A(0,0), A(0,1), A(0,2), A(1,1), A(1,2), A(2,2) ] 

I want to find a function that receives as input two integer i and j, and outputs the corresponding value of the matrix. The catch is that I do not want to access the matrix directly, instead I want to access the vector.

This is my reasoning so far. If I have an input with j < i, I just swap them since the matrix is symmetric. If I have that i == 0, the position in the array is just j. If that is not the case, I think I need to do something like this. (n is the dimension of the matrix, and position is the integer that I need when for the array.)

int position = 0;
for(int k = 0; k < i; k++){
   position = position + (n-k);
}
position = position + j % i;

However, this code fails. I think I'm close to the solution but I am missing something. Any help?

Upvotes: 0

Views: 1011

Answers (2)

AlmuHS
AlmuHS

Reputation: 347

You can do simply this:

int myvector[matrix.size()];
int pos = 0;

for(int i = 0; i < matrix.size(); i++){
     for(int j = 0; j < matrix.size(); j++){
        if(j > i) myvector[pos++] = matrix[i][j];
        else myvector[pos++] = matrix[j][i];
     }
 }

Upvotes: 0

xskxzr
xskxzr

Reputation: 13040

The last j % i should be j - i.


In addition, the loop is essentially doing

position = n + (n - 1) + ... + (n - i + 1);

which can be simplified to

position = (n * 2 - i + 1) * i / 2;

So you can simply write

position = (n * 2 - i + 1) * i / 2 + j - i;

or

position = (n * 2 - i - 1) * i / 2 + j;

Upvotes: 1

Related Questions