
%% Random seed

randn('state',2010);
rand('state',2010);


%% Prepare data

n = 512;              % Size of the signal
m = 200;              % Number of samples
A = randn(m,n);

oversampling = 4
s = round(m/oversampling);     % 4 equations per degree of freedom
support = randsample(n,s);  
x0 = zeros(n,1); x0(support) = randn(s,1);
b = A*x0;


%% Solve l1 minimization

cvx_begin
    cvx_quiet(true) ;
    variable x(n);
    minimize(norm(x,1));
    subject to 
        A*x == b;
cvx_end

fprintf('The relative MSE is: %d \n', norm(x-x0)^2/norm(x0)^2)
figure, plot(1:n,x0,'b*',1:n,x,'ro'), legend('original','decoded')
title('ell1 minimization')

pause
%% Solve l2 problem

cvx_begin
    cvx_quiet(true) ;
    variable x2(n);
    minimize(norm(x2,2));
    subject to 
        A*x2 == b;
cvx_end

fprintf('The relative MSE is: %d \n', norm(x2-x0)^2/norm(x0)^2)
figure, plot(1:n,x0,'b*',1:n,x2,'ro'), legend('original','decoded')
title('ell2 minimization')


pause

%% Now try to recover a nearly-sparse signal
x0 = x0 + 0.01*randn(n,1) ;
b = A*x0;


%% Solve l1 minimization

cvx_begin
    cvx_quiet(true) ;
    variable x(n);
    minimize(norm(x,1));
    subject to 
        A*x == b;
cvx_end

fprintf('The relative MSE is: %d \n', norm(x-x0)^2/norm(x0)^2)
figure, plot(1:n,x0,'b*',1:n,x,'ro'), legend('original','decoded')
title('ell1 minimization')



