Euclidean projection on a rectangle
cvx_quiet(true);
randn('seed',0);
n = 10;
l = -rand(n,1);
u = rand(n,1);
x0 = randn(n,1);
fprintf(1,'Computing the analytical solution ...');
pc_x0 = x0;
pc_x0(find(x0<=l)) = l(find(x0<=l));
pc_x0(find(x0>=u)) = u(find(x0>=u));
fprintf(1,'Done! \n');
fprintf(1,'Computing the optimal solution by solving a QP ...');
cvx_begin
variable x(n)
minimize ( norm(x-x0) )
x <= u;
x >= l;
cvx_end
fprintf(1,'Done! \n');
disp('-----------------------------------------------------------------');
disp('Verifying that the analytical solution and the solution obtained via QP are equal: ');
[pc_x0 x]
Computing the analytical solution ...Done!
Computing the optimal solution by solving a QP ...Done!
-----------------------------------------------------------------
Verifying that the analytical solution and the solution obtained via QP are equal:
ans =
0.4186 0.4186
0.6268 0.6268
0.0751 0.0750
0.2026 0.2026
-0.1988 -0.1988
0.8381 0.8381
0.0196 0.0196
0.6813 0.6813
0.2641 0.2639
0.8318 0.8318