%% GLRT Optimization problem
%The sparsity constraint of L_0 norm is relaxed by a heuristic L_1
% Norm, therefore it is required to solve the optimization multiple times
% untill the specified sparsity is achieved
%%
function [a,Co_z,Co_x,Co_e]= GLRT(k,z,SNR,H,x)
m=length(z);
n=length(x);
% Set data for GLRT
e=randn(size(z)); % measurement noise
%Covariance matrix of x, as defined in Journal paper [2]
Co_x=eye(n)*var(x);

%Covariance matrix of e, as defined in Journal paper [2]
var_e=var(x)*10^(-SNR/10);
Co_e=eye(m)* var_e;

%Covariance of z
Co_z = H*Co_x*H' + Co_e;
invCo_z = inv(Co_z);

mu=zeros(m,1);
z=mvnrnd(mu,Co_z,1)';

%initial value of sparsity of a
sparsity =m;
%constat v is used adjust the sparsity of a
v=0;
dv=0.1; % step of change to adjust v

while (sparsity ~= k)
    cvx_begin
    variable a(m,1);
    minimize ((a-2*z)' * (invCo_z*a))
    
    subject to
    norm(a,1) <= v
    
    cvx_end
    
    v=v+dv;
    sparsity=length(find(abs(a)> 10e-5))
    
    % In case sparisty exceeds desired k, reset v to zero and decrease dv
    if sparsity >k
        v=0; dv=dv/2;
    end
end

end