clc
clear
N=10;                         % Number of the Antennas
M=120;                        % Number of the directions
KK=1;
Pt=10^(-0.692);                         % Transmit Power of each Antenna
teta=-pi/2:pi/M:pi/2;
Pd1=ones(M+1,1)*(0);% Desired pattern
Pd2=ones(M+1,1)*(0);
shift=0;
counter = 0;
t1=(-15+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=(0+shift)/180*pi;
i2=t2/pi*M+M/2+1;
Pd1(i1:i2)=10;


t3=(20+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=(40+shift)/180*pi;
i4=t4/pi*M+M/2+1;
Pd2(i3:i4)=10;

Pd = Pd1 + Pd2;




cvx_begin sdp
variable X1(N,N) hermitian;
variables z1
minimize z1
subject to
for i=1:M
  
    trace(matA(teta(i),N)*X1) - Pd1(i)  <= z1 ;
    trace(matA(teta(i),N)*X1) - Pd1(i)  >= -z1 ; 
end

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

X1  >= 0
cvx_end

cvx_begin sdp
variable X2(N,N) hermitian
variable z2 
minimize z2
subject to
for i=1:M
    trace(matA(teta(i),N)*X2) - Pd2(i)  <= z2;
    trace(matA(teta(i),N)*X2) - Pd2(i)  >= -z2; 
end

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

X2  >= 0

cvx_end

WW = randomize_subopt(X1,X2,Pd)
WW = [WW(:,1) WW(:,3) WW(:,2) WW(:,4)];

for k = 1:length(teta)
    for l = 1:N;
    a(l,1)=exp(j*pi*sin(teta(k))*(l-1));
    end
    b(k) = a'*WW*WW'*a;
    d(k) = a'*X1*a;
    e(k) = a'*X2*a;
end
   

% for teta1= -pi/2:.01:pi/2;
%     counter = counter+1;
%     teyf1(counter) = trace(matA(teta1,N)*WW*WW') + trace(matA(teta1,N)*WW1*WW1');
% end
% 
% teta2 = [-pi/2:.01:pi/2];




figure
% plot(teta2,teyf1)
% hold on
plot(teta,b,'b-')

figure(2)
plot(teta,d,'r-',teta,e,'b--')

X_sub_opt = WW;
save X_sub_opt.mat X_sub_opt

%Xrot = [Xopt(:,1) Xopt(:,2)];

%Xrot1 = integ(Xrot,N);

%save Xrot1.mat Xrot1

%e = [1 -1];
%ee = e.'*e;