clc
clear
N=10;                         % Number of the Antennas
M=120;                        % Number of the directions
KK=1;
Pt=N;                         % Transmit Power of each Antenna


%--------------------FIRST BEAMPATTERN-------------------------------------
%--------------------------------------------------------------------------
%--------------------------------------------------------------------------

teta=-pi/2:pi/M:pi/2;
Pd1=ones(M+1,1)*(0);             % Desired pattern
shift=0;
t1=(-10+shift)/180*pi;                   % x/180*M should be a integer numberv
i1=t1/pi*M+M/2+1;               % for the case of M=120, x=3*k
t2=(-5+shift)/180*pi;
i2=t2/pi*M+M/2+1;
Pd1(i1:i2)=Pt*5;
t3=(-5+shift)/180*pi;                   % x/180*M should be a integer numberv
i3=t3/pi*M+M/2+1;               % for the case of M=120, x=3*k
t4=(0+shift)/180*pi;
t01=t1;
t02=t4;
i4=t4/pi*M+M/2+1;
Pd1(i3:i4)=Pt*5;

cvx_begin sdp
variable X(N,N) hermitian;
variable z
variable alpha
minimize (z)
subject to
for i=1:M
   -trace(matA(teta(i),N)*X)-z <= -Pd1(i);
    trace(matA(teta(i),N)*X)-z <= Pd1(i);
end

X(1,1)+X(10,10) == Pt/10;
X(2,2)+X(9,9) == Pt/10;
X(3,3)+X(8,8) == Pt/10;
X(4,4)+X(7,7) == Pt/10;
X(5,5)+X(6,6) == Pt/10;

X  >= 0
cvx_end

[u,v]=eig(X);
root_mat=u*v.^(.5);
for shomara=1:1000
    disp(shomara)
    Candidatew=[];
    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;
        Candidatew=[Candidatew Candidatetemp];
    end
    for lll=1:N/2
        aaa=[Candidatew(lll) Candidatew(N-(lll-1))];
        Candidatew(lll)= Candidatew(lll,:)/norm(aaa)*sqrt(Pt/10);
        Candidatew(N-(lll-1))= Candidatew(N-(lll-1))/norm(aaa)*sqrt(Pt/10);
    end


    for ind1=1:M
        temp(ind1)=abs(trace(matA(teta(ind1),N)*Candidatew*Candidatew')-Pd1(ind1));
    end
    Val1=max(temp);
    if (shomara ==1)
        Val=Val1;
        Candidatefinal=Candidatew;
    else
        if ( abs(Val)- abs(Val1) > 0  )
            Val=Val1;
            Candidatefinal=Candidatew;
        end
    end
end
WW1=[Candidatefinal];



% Plot of the Patterns
counter=0;
% for teta1=-pi/2:.01:pi/2
%     counter=counter+1;
%     teyf(counter)=trace(matA(teta1,N)*X);
% end
% plot((-pi/2:.01:pi/2)/pi*180,10*log10(abs(teyf)),'b')
WW=[WW1 conj(WW1(10:-1:1))]/sqrt(2);
save WW.mat WW
% save('MATTT','WW');
% hold on
counter=0;

for teta1=-pi/2:.01:pi/2
    counter=counter+1;
    teyf1(counter)=trace(matA(teta1,N)*WW*WW');
end
plot((-pi/2:.01:pi/2)/pi*180,10*log10(abs(teyf1)),'m--'.)

