%%
% OFDM MATLAB SIMULATION
% 2011/11/23
% Tom WADA
clear all;
num_symbol=100;
num_carrier=16;
M=4;
modqpsk=[1+1i, -1+1i, 1-1i, -1-1i];

%% 1 generate random data
data = floor(rand(num_carrier,num_symbol)*M);

%% 2 mapping to I-Q constellation
data_s = modqpsk(1+data);

figure(1)
subplot(2,2,1);
plot(real(data_s), imag(data_s),'r.');
title('SEND');
axis([-3 3 -3 3]);

%% 3 IFFT matrix WP
WP=zeros(num_carrier, num_carrier);
for row=1 : num_carrier
  for col=1 : num_carrier
    WP(row,col)=1/sqrt(num_carrier)*exp(1i*2*pi*(row-1)*(col-1)/num_carrier);
  end
end

%% 4 OFDM signal generation
sdwv=WP*data_s;
sdwv2=ifft(data_s);

%% 5 Channel Impulse Response
cir=[0;1;0.5;0.25;0;0;0;0;0;0;0;0;0;0;0;0];
%cir=[1;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0];
HH=[];
for I=1:16
  HH=[HH,[cir(16-(I-2):16);cir(1:16-(I-1))]];
end

%% 6 Receiver wave
rvwv=HH*sdwv;

%% 7 Add Noise
sigpower=mean(mean(abs(rvwv).^2));
sn= 15; % 10dB
awgn = (randn(num_carrier,num_symbol)+1i*randn(num_carrier,num_symbol));
awgnpower=mean(mean(abs(awgn).^2));
awgn = awgn*sqrt(sigpower)/sqrt(awgnpower)*10^(-sn/20);
rvwv=rvwv+awgn;

%% 8 FFT matrix WPC
for row=1 : num_carrier
  for col=1 : num_carrier
    WPC(row,col)=1/sqrt(num_carrier)*exp(-1i*2*pi*(row-1)*(col-1)/num_carrier);
  end
end

%% 9 FFT
data_r=WPC*rvwv;

subplot(2,2,2);
plot(real(data_r), imag(data_r),'b+');
title('RECEIVE');
axis([-3 3 -3 3]);

%% 10 D matrix
D=WPC*HH*WP;

%% 11 E (Equalizer matrx)
E=zeros(num_carrier,num_carrier);
for I=1:16
  E(I,I)=1/D(I,I);
end

%% 11 Equalize
data_eq=E*data_r;

subplot(2,2,3);
plot(real(data_eq), imag(data_eq),'r+');
title('EQUALIZED');
axis([-3 3 -3 3]);