'Imposing constraints on all (numbered) diagonals in CVXPY

I am looking to implement a constraint on an optimization on all diagonals of a matrix using CVXPY. The diag function in CVXPY only returns the main diagonal. Is there a simple way to implement the numbered diagonal function in numpy using a CVXPY variable, in order to iterate over all diagonals adding a constraint for each?



Solution 1:[1]

I wound up using (though the final result used this code inline in a different function) the following:

def diagat(mat, n, i, j):
    """ return the diagonal containing mat[i][j] (mat is a square matrix of dimension n)"""
    return [mat[i + k][j + k] for k in range(-n, n) if 0 <= i + k < n and 0 <= j + k < n]

def diag90at(mat, n, i, j):
    """ return the diagonal orthogonal to the regular diagonal containing mat[i][j] """
    return [mat[i - k][j + k] for k in range(-n, n) if 0 <= i - k < n and 0 <= j + k < n]

A = [[ 1, 2, 3, 4],
     [ 5, 6, 7, 8],
     [ 9,10,11,12],
     [13,14,15,16]]

print(diagat(A, 4, 0, 1))
print(diagat(A, 4, 2, 2))
print(diagat(A, 4, 3, 0))

print(diag90at(A, 4, 0, 1))
print(diag90at(A, 4, 2, 2))
print(diag90at(A, 4, 3, 0))

"""
[2, 7, 12]
[1, 6, 11, 16]
[13]
[5, 2]
[14, 11, 8]
[13, 10, 7, 4]
"""

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1