0
$\begingroup$

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 Answers 1

2

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).

  • 0
    Could you explain how this formula is derived?2017-02-08
  • 1
    Mostly by playing around until I got it to work right. $j$ was obviously just going to be added to some expression for $i$. That expression needed to be the sum of all values between $i$ and $N - 1$. The formula for the sum of all numbers up to a value $k$ is well-known ($k(k+1)/2$), So I needed the difference between $k = N-1$ and $k = i -1$2017-02-08
  • 0
    @Petahanks - though your post has been deleted (since it was a question and should have been asked as a question, not an answer), and I was unaware of it until now, I'll still address your concern. Note the last sentence in my answer. Your "wrong" values had $j < i$, but the formula is for $j \ge i$. So of course you got the wrong answer.2018-06-11