clc
%16 QAM constellation
x=[-3 -3 -3 -3 -1 -1 -1 -1 3 3 3 3 1 1 1 1 ];
y=[3 1 -3 -1 3 1 -3 -1 3 1 -3 -1 3 1 -3 -1 ];
Qam=x+y*i;
Es=5; %average constellation energy for d=2;
index=1;
%set SNR step
step=3;
% SNR range is here
for SNR=0:step:21
%number of bit errors set to zero
count=0;
%number of iterations
N=10^4;
if SNR==20 N=3*10^4; end; % increase for higher SNR
for it=1:N
%generate 16 bits uniformly distributed
A=round(rand(1,16));
% TX symbols
s1=Qam(bi2de(A(1:4),'left-msb')+1);
s2=Qam(bi2de(A(5:8),'left-msb')+1);
s3=Qam(bi2de(A(9:12),'left-msb')+1);
s4=Qam(bi2de(A(13:16),'left-msb')+1);
C1=[s1 s2 s3 s4; -s2 s1 -s4 s3; -s3 s4 s1 -s2; -s4 -s3 s2 s1];
C=[C1; conj(C1)];
%Channel coefficients
Z=0;
K1=1/sqrt(2)*(randn(4,1)+i*randn(4,1)); % normalize to the variance 1 CN(0,1)
K2=1/sqrt(2)*(randn(4,1)+i*randn(4,1)); % normalize to the variance 1 CN(0,1)
%AWGN channel
N0=(4*Es/10^(SNR/10));
Z1=sqrt(N0/2)*(randn(8,1)+i*randn(8,1)); % variance N0
Z2=sqrt(N0/2)*(randn(8,1)+i*randn(8,1)); % variance N0
%RX symbols
R1=C*K1;%+Z1;
SNG1 = R1;
R1 = R1 + Z1;
R2=C*K2;%+Z2;
SNG2 = R2;
R2 = R2 +Z2;
%decoding ML OSTBC
H1=[K1(1) K1(2) K1(3) K1(4); K1(2) -K1(1) K1(4) -K1(3); K1(3) -K1(4) -K1(1) K1(2); K1(4) K1(3) -K1(2) -K1(1)];
H2=[K2(1) K2(2) K2(3) K2(4); K2(2) -K2(1) K2(4) -K2(3); K2(3) -K2(4) -K2(1) K2(2); K2(4) K2(3) -K2(2) -K2(1)];
H1_1=[H1;conj(H1)];
H2_1=[H2;conj(H2)];
R1_1=[R1(1:4); conj(R1(5:8))];
R2_1=[R2(1:4); conj(R2(5:8))];
%symbol-wise decoding
%S=R.'*H'/(2*sum(abs(K).^2));
S1= H1_1'*R1_1/(2*sum(abs(K1).^2));
S2 = H2_1'*R2_1/(2*sum(abs(K2).^2));
alfa1 = sum(abs(SNG1));
alfa2 = sum(abs(SNG2));
sss = alfa1 +alfa2;
alfa1 = alfa1/sss;
alfa2 = alfa2/sss;
S = alfa1*S1+alfa2*S2;
%symbol decoding for 16-QAM
L=[abs(Qam-S(1)); abs(Qam-S(2)); abs(Qam-S(3)); abs(Qam-S(4))];
[D,I]=min(L,[],2);
%TX bits
dec_bits(1,1:4)=de2bi(I(1)-1,4,'left-msb');
dec_bits(1,5:8)=de2bi(I(2)-1,4,'left-msb');
dec_bits(1,9:12)=de2bi(I(3)-1,4,'left-msb');
dec_bits(1,13:16)=de2bi(I(4)-1,4,'left-msb');
%count errors
count=count+sum(abs(A-dec_bits));
end;
B_err(index)=count/(N*16)
index=index+1;
end;
semilogy(0:step:21, B_err,'g');
hold on;