How do I translate my matlab code to python cvx?

81 Views Asked by At

I need to translate my code from matlab cvx to python one , I would be happy if there is any help for me. `

eps = .1;

A = [-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 = [1;0;0;0;-1;0];
t = [0;1;0;0;0;-1];

cvx_begin
    variables x_star(n) y_star(n)
    dual variables mu_star nu_star
    minimize(sum((x_star+y_star).^2)+eps*(sum(x_star.^2+y_star.^2)))
    subject to
        mu_star: A*x_star+s==0;
        nu_star: A*y_star+t==0;
        x_star >= 0;
        y_star >= 0;
cvx_end
f_min = cvx_optval;

`

A translation from cvx to python cvx.

1

There are 1 best solutions below

0
On

A translation from cvx to python cvx.py would be:

import cvxpy as cp

eps = .1
A = [[-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 = [1, 0, 0, 0, -1, 0]
t = [0, 1, 0, 0, 0, -1]

x_star = cp.Variable(len(A[0]))
y_star = cp.Variable(len(A[0]))
mu_star = cp.Variable(len(s))
nu_star = cp.Variable(len(t))

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 == 0, A * y_star + t == 0, x_star >= 0, y_star >= 0]

prob = cp.Problem(objective, constraints)
prob.solve()

f_min = prob.value