Conversion of upper triangle linear index from index on symmetrical array

3.9k Views Asked by At

Say we have a symmetrical matrix of the following form:

A = [[0,1,2],
     [1,0,2],
     [2,2,0]]

If we take the upper triangle of A and flatten it we get:

B = [0,1,2,0,2,0]

Is there a known formula that could take an index for A in the form of (i,j) and convert it to a value k that corresponds to the location in B for that index. For example:

A[0,1] = B[1] = 1 
A[1,0] = B[1] = 1
A[2,0] = B[2] = 2
A[2,1] = B[4] = 2

In addition what is the method for deriving this formula? Perhaps my brain just isn't working today, but I can't seem to remember how to go about doing this.

I have found something similar here, but that is for the triangle with an offset of 1 and I would like to include the diagonal in my conversion.

1

There are 1 best solutions below

6
On BEST ANSWER

If the dimension is $N$, then $$n = \frac{N(N-1)}2 - \frac{(N-i)(N-i-1)}2 +j$$ works.

Specifically, if $N = 3$ as in your example, then $$n = 3 - \frac{(3 - i)(2-i)}2 + j$$

This assumes that $j \ge i$. If $j < i$, then reverse the roles of $i$ and $j$ in the formula (which works since $A$ is symmetric).