numpy 在CVXPY中形成块矩阵时出错

ekqde3dh  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(89)

我试图解决一个优化问题,使用CVXPY,我需要形成一个块矩阵作为约束。块矩阵由下式给出:

$$M = \开始{bmatrix} Q & \mathbf {b} \ \mathbf{b}^T & 1 \end{bmatrix}$$
其中Q是表示对称矩阵的CVXPY变量,h是NumPy数组,1是标量。我尝试使用CVXPY中的cp.bmat函数来形成这个分块矩阵,如下所示:

block_matrix = cp.bmat([[Q, h.reshape(-1, 1)], [h, 1]])

但是,我得到以下错误:
除轴0外的所有输入尺寸必须完全匹配。
我已经使用reshape(-1, 1)h整形为列向量,因为CVXPY需要2D数组进行矩阵运算。我不知道为什么我得到这个错误,以及如何修复它。任何帮助将不胜感激。
下面是完整的相关代码供参考:

import cvxpy as cp
import numpy as np

# Define the size of the matrix Q
n = 21

# Define the variables
Q = cp.Variable((n, n), symmetric=True)

# Define the h vector
h = np.array([0.01 * k**2 for k in range(-10, 11)])

# Form the block matrix
block_matrix = cp.bmat([[Q, h.reshape(-1, 1)], [h, 1]])
cotxawn7

cotxawn71#

如果这还不够明显的话

# Form the block matrix
block_matrix = cp.bmat([[Q, h.reshape(-1, 1)], [h.reshape(1, -1), np.ones((1,1))]])

相关问题