Formula for converting a linear index to its mirrored counterpart on the other side of the diagonal in a symmetric matrix

438 Views Asked by At

I’m looking for a formula which given a column-major linear index to an element in a symmetric $n \times n$ matrix returns an index pointing to the corresponding location on the opposite side of the diagonal of the same matrix. Say for example I have a matrix: $$ A = \begin{bmatrix} 0 & 1 &2 \\ 1 & 0 & 2 \\ 2 & 2 & 0 \end{bmatrix} $$ And I enter $0$ into the formula, I would need it to return $0$ (since index $0$ is on the diagonal).

If I enter $1$ to the formula, I would need it to return $3$, since index $3$ points to the same location but mirrored to the opposite side of the diagonal.

If I enter $2$, it should return $6$. And so on...

This exact question has been asked before, but with row-major indexing instead of column-major. However, as far as I can tell, the accepted and upvoted answer on that tread is completely wrong so it offers little help.

Does anyone know how to solve this?

1

There are 1 best solutions below

3
On BEST ANSWER

I take two steps to solve the problem:

1) Find the matrix index in the form of $(i, j)$ corresponding to the number entered

2) swap $(i, j)$ to $(j, i)$, which is for "mirroring". Find the index of the vector form of the column based matrix.

The solution works for $1$ based, but can be converted easily to $0$ based since their difference for the same location is $1$.

notation

$\left\lfloor \frac{l}{n} \right\rfloor = l // n$

Let $(i_l, j_l)$ be a mapping: \begin{equation} \label{vecmap} \begin{split} & (i_l, j_l): \{1, \ldots, n^2\} \to \{1, \ldots, n\}\times \{1, \ldots, n\}\\ & l \to (i_l, j_l)\\ & i_l = l - n(j_l-1) \\ & j_l = \left\lfloor \frac{l}{n} \right\rfloor \\ \end{split} \end{equation}

For exmaple: $$ \begin{split} &l = 1, (i_1, j_1) = (1, 1)\\ &l = n, (i_l, j_l) = (n, 1)\\ &l = n+1, (i_l, j_l) = (1, 2)\\ &l = n^2, (i_l, j_l) = (n, n)\\ \end{split} $$

We want the "$l_*$" of $(j_l, i_l)$, which is $l_* = n(i_l - 1) + j_l$.

Explanation Enter $i = 2$, the corresponding $l=3$ because I assume the starting index of series is 1 rather than 0. In your example, n = 3. Hence $i_l = 3, j_l = 1$, this gives $l_* = 3(3- 1) + 1 = 7$. Again because starting index is 1, converting by minus 1 you get 6.