对 CVXPY 中的所有(编号)对角线施加约束

Imposing constraints on all (numbered) diagonals in CVXPY

我希望使用 CVXPY 对矩阵的所有对角线的优化实施约束。 CVXPY 中的 diag 函数仅 returns 主对角线。有没有一种简单的方法可以使用 CVXPY 变量在 numpy 中实现编号对角线函数,以便遍历所有对角线并为每个对角线添加约束?

我最终使用了(虽然最终结果在不同的函数中使用了这段代码内联)以下内容:

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]
"""