Linear index upper triangular matrix

后端 未结 4 1218
滥情空心
滥情空心 2020-12-07 11:30

If I have the upper triangular portion of a matrix, offset above the diagonal, stored as a linear array, how can the (i,j) indices of a matrix element be extrac

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 12:15

    The equations going from linear index to (i,j) index are

    i = n - 2 - floor(sqrt(-8*k + 4*n*(n-1)-7)/2.0 - 0.5)
    j = k + i + 1 - n*(n-1)/2 + (n-i)*((n-i)-1)/2
    

    The inverse operation, from (i,j) index to linear index is

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

    Verify in Python with:

    from numpy import triu_indices, sqrt
    n = 10
    for k in range(n*(n-1)/2):
        i = n - 2 - int(sqrt(-8*k + 4*n*(n-1)-7)/2.0 - 0.5)
        j = k + i + 1 - n*(n-1)/2 + (n-i)*((n-i)-1)/2
        assert np.triu_indices(n, k=1)[0][k] == i
        assert np.triu_indices(n, k=1)[1][k] == j
    
    for i in range(n):
        for j in range(i+1, n):
            k = (n*(n-1)/2) - (n-i)*((n-i)-1)/2 + j - i - 1
            assert triu_indices(n, k=1)[0][k] == i
            assert triu_indices(n, k=1)[1][k] == j
    

提交回复
热议问题