Linear indexing in symmetric matrices

前端 未结 8 1165
遇见更好的自我
遇见更好的自我 2021-01-05 04:09

We can access matrices using linear indexing, which follows this pattern

0 1 2

3 4 5

6 7 8

It\'s easy to get the i,j coordinates for this cas

8条回答
  •  孤街浪徒
    2021-01-05 04:17

    If you want to use the indexing that you used, and you want to avoid the loop you can invert the function for the indexing. I will use k to denote the linear index, and all indices are zero based. As you have noted

    k = j + n*i - i*(i-1) /2.

    Seeing as we are working with positive integers here, and the fact that all combinations (i,j) map onto a distinct k means that the function is invertible. The way in which I would do this is to note first of all that

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

    such that if you can find the row which you are on, the column is defined by the above equation. Now consider you want the row, which is defined as

    row = min{ i | k - ni + i(i-1)/2 >= 0 }.

    If you solve the quadratic equation k - ni + i(i-1)/2 = 0 and take the floor of the i, this gives you the row, i.e.

    row = floor( (2n+1 - sqrt( (2n+1)^2 - 8k ) ) / 2 )

    then

    j = k - row * n + row * (row-1)/2.

    In pseudocode this would be

    //Given linear index k, and n the size of nxn matrix
    i = floor( ( 2*n+1 - sqrt( (2n+1)*(2n+1) - 8*k ) ) / 2 ) ;
    j = k - n*i + i*(i-1)/2 ;
    

    This removes the need for the loop, and will be a lot quicker for large matrices

提交回复
热议问题