# How to form the following constraint in cvx?

The optimization problem is
$$\min_{x\in K} \|h - x\|_2$$ where $$K = \{v\in R^n : \exists \lambda \geq 0\ v_1=v_2=\ldots=v_k=\lambda \ \text{and} \ |v_i| \leq \lambda \ \text{for} \ i=k+1,\ldots,n \}$$ , where $$h, k, n$$ are all known.

Could someone tell me how to write down this constraint in cvx? I couldn't think of a convenient way of specifying the constraints which define the convex set $$K$$.

• Is $k$ a known constant? Or in the definition of $K$ does it mean “there exists a $k$ for which this holds?” – cdipaolo Feb 11 '20 at 7:58
• @cdipaolo Oh I should have mentioned that $h$, $k$, $n$ are all known. – Bihu Duo Feb 11 '20 at 8:00

Is it what you need? (λ is unknown)

# INPUT
N,K = 5,3
h=[1.1,1.2,1.7,0.5,0.3]

Xk = cp.Variable()# unknown Lambda
Xn = [cp.Variable() for i in range(N-K)]
constraints = []
for x in Xn:
constraints.append(cp.abs(x)<=Xk)

X = [Xk]*K+Xn
obj = cp.Minimize(cp.sum([(h[i]-X[i])**2 for i in range(N)]))
prob = cp.Problem(obj, constraints)
rez = prob.solve()

for i in range(K):
print("{:.1f}".format(Xk.value))
for i in range(N-K):
print("{:.1f}".format(Xn[i].value))

print("Objective function : {:.1f}".format(rez))


Result: 1.3 1.3 1.3 0.5 0.3 Objective function : 0.2

• It looks like $\lambda$ is not known from the original post. – cdipaolo Feb 11 '20 at 17:03
• @cdipaolo in second part of the solution λ is not known. I think it make sense remove solution with known λ – Sergey Feb 11 '20 at 17:18
• @cdipaolo Thank you so much! The $\lambda$ isn't known so this is exactly what I hoped for. – Bihu Duo Feb 11 '20 at 18:46