clc
clear
N=10;                         % Number of the Antennas
M=120;                        % Number of the directions
KK=1;
Pt=0.0186;                         % Transmit Power of each Antenna
theta = linspace(-pi/2,pi/2,M);
teta = linspace(-pi/2,pi/2,M);

Pd=zeros(M,1);% Desired pattern
%Pd2=ones(M+1,1)*(0);
shift=0;
counter = 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=(0+shift)/180*pi;
i2=t2/pi*M+M/2+1;

eta = 5/180*pi;
index1 = find(teta <= t2 & teta >= t1);

Pd(index1) = 0.0355;

index2 = find(teta <= t1 & teta >= t1 - eta);
Pd(index2) = [];
teta(index2) = [];

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

index3 = find(teta <= t4 & teta >= t3);

Pd(index3) = 0.0355;

index4 = find(teta <= t4 + eta & teta >= t4);

Pd(index4) = [];
teta(index4) = [];

T = length(Pd);


% + trace(matA(teta(i),N)*X2)

cvx_begin sdp
variable X1(N,N) hermitian;
variable X2(N,N) hermitian;
variable z
minimize z
subject to
for i=1:T
  
    trace(matA(teta(i),N)*X1) + trace(matA(teta(i),N)*X2) - Pd(i)  <= z ;
    trace(matA(teta(i),N)*X1) + trace(matA(teta(i),N)*X2) - Pd(i)  >= -z ;
    
   
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
X2  >= 0



cvx_end

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

WW = randomize_copy(X1,Pd,teta,1);

% WW = [WW(:,1) WW(:,3) WW(:,2) WW(:,4)];

for k = 1:length(theta)
    for l = 1:N;
    a(l,1)=exp(j*pi*sin(theta(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(theta,10*log10(b),'b-')

figure(2)
% plot(theta,10*log10(d),'r-',theta,10*log10(e),'b--')
plot(theta,10*log10(d),'r-')
Xopt = WW;
save Xopt.mat Xopt