请求将Matlab CVX凸优化代码转换为Python CVX代码
将Matlab CVX凸优化代码转换为Python CVX代码
转换后的Python CVXPY代码
import cvxpy as cp import numpy as np eps = 0.1 A = np.array([ [-1, 1, 0, 0, 0, 0, 0, 0, -1], [1, 0, -1, 0, 0, 0, 0, -1, 0], [0, 1, 1, -1, 0, 0, 0, 0, 0], [0, 0, 0, 1, -1, -1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 0, 1, -1, 1, 0] ]) s = np.array([1, 0, 0, 0, -1, 0]).reshape(-1, 1) t = np.array([0, 1, 0, 0, 0, -1]).reshape(-1, 1) n = A.shape[1] # 对应Matlab中的n,A有9列,故n=9 # 定义优化变量 x_star = cp.Variable(n) y_star = cp.Variable(n) # 定义目标函数 objective = cp.Minimize( cp.sum_squares(x_star + y_star) + eps * (cp.sum_squares(x_star) + cp.sum_squares(y_star)) ) # 定义约束条件 constraints = [ A @ x_star + s.flatten() == 0, A @ y_star + t.flatten() == 0, x_star >= 0, y_star >= 0 ] # 构建并求解问题 prob = cp.Problem(objective, constraints) prob.solve() # 获取结果 f_min = prob.value mu_star = constraints[0].dual_value nu_star = constraints[1].dual_value
关键差异说明
- 依赖库:Python使用
cvxpy实现凸优化,需提前通过pip install cvxpy安装,同时用numpy处理矩阵数据。 - 变量声明:直接通过
cp.Variable()定义优化变量,无需Matlab式的维度前置声明。 - 目标函数:Matlab中
sum((x+y).^2)对应CVXPY的cp.sum_squares(x+y),语法更贴合凸优化库的规范。 - 矩阵运算:用
@表示矩阵乘法替代Matlab的*;将列向量s、t展平为一维数组,适配CVXPY的运算逻辑。 - 对偶变量:CVXPY无需提前声明对偶变量,求解后通过约束对象的
.dual_value属性直接获取对应值。 - 结果提取:最优值通过
prob.value获取,替代Matlab的cvx_optval。
内容的提问来源于stack exchange,提问作者omid74
相关产品推荐
相关产品推荐

