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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x