clc
clear
N=10;                         % Number of the Antennas
KK=6;                         % Number of Orthogonal Signals
M=100;                        % Number of the directions
Pt=1;                         % Transmit Power of each Antenna
P=ones(N,1)*Pt;               % Transmit Power of each Antenna
Pd=ones(M,1)*(0);             % Desired pattern
Pd(40:60)=100;                
teta=-pi/2+pi/M:pi/M:pi/2;


cvx_begin sdp

variable X1(N,N) hermitian;
variable z
minimize (z)
subject to
for i=1:M
   -trace(matA(teta(i),N,1)*X1)*KK-z <= -Pd(i);
    trace(matA(teta(i),N,1)*X1)*KK-z <= Pd(i);
end
for i=1:N
    trace(matB(i,N,1)*X1)== Pt/KK;
end

trace(X1) == Pt*N/KK;
X1  >= 0
cvx_end

%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
% Randomization for recovery


[u,v]=eig(X1);
root_mat=u*v.^(.5);
for shomara=1:1000
    disp(shomara)
    Candidate1=[];
    for lll=1:KK
        ran_vec=randn(N,1)+j*randn(N,1);
        ran_vec=ran_vec./abs(ran_vec);
        Candidatetemp=root_mat*ran_vec;
        Candidate1=[Candidate1;Candidatetemp];
    end



    for iter=1:200

        for l1=1:N
            S=0;
            for l2=0:KK-1
                S=S+abs(Candidate1(l1+l2*N))^2;
            end

            for l2=0:KK-1
                Candidate1(l1+l2*N)=Candidate1(l1+l2*N)/(sqrt(S))*sqrt(Pt);
            end
        end


        for l1=0:KK-1
            S=0;
            for l2=1:N
                S=S+abs(Candidate1(l2+l1*N))^2;
            end

            for l2=1:N
                Candidate1(l2+l1*N)=Candidate1(l2+l1*N)/(sqrt(S))*sqrt(Pt*N/KK);
            end
        end

    end




    for ind1=1:M
        temp(ind1)=abs(Candidate1'*matA(teta(ind1),N,KK)*Candidate1-Pd(ind1));
    end
    Val1=max(temp);
    if (shomara ==1)
        Val=Val1;
        Candidate=Candidate1;
    else
        if ( abs(Val)- abs(Val1) > 0  )
            Val=Val1;
            Candidate=Candidate1;
        end
    end
end

%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------
% Plot of the Patterns
counter=0;
for teta1=-pi/2:.01:pi/2
    counter=counter+1;
    teyf(counter)=trace(matA(teta1,N,1)*X1)*KK;
end
semilogy(sin(-pi/2:.01:pi/2),abs(teyf),'b')

hold on
counter=0;
for teta1=-pi/2:.01:pi/2
    counter=counter+1;
    teyf1(counter)=Candidate'*matA(teta1,N,KK)*Candidate;
end
semilogy(sin(-pi/2:.01:pi/2),abs(teyf1),'m--')
semilogy(sin(-pi/2:.01:pi/2),rectA(-pi/2:.01:pi/2,.31),'m--')