%% System Identification Using Least Mean Square (LMS) algorithm
% Plant identification simulation
%% Start
clc;
clear all;
close all;
%% LMS parameter
runs = 10; % Monte Carlos Simulations (number of independent simulations)
etas = 1e-2; % Learning rate for LMS
N = 1000; % Number of samples
SNR = 10; % Noise level (signal to noise ratio)
NWD_lms=0;
MSE_lms=0;
for run=1:runs
h = randn(1,5); % Plant impulse response
x = sqrt(1)*randn(1,N)+0; % random signal from zero mean gaussian distribution of variance one
r = filter(h,1,x); % Input passed trought system(h)
d = awgn(r, SNR); % Addition of white Gaussian noise of SNR value defined above
Wlms = randn(size(h)); % Initial weights of LMS
Us = zeros(1,length(h)); % Input frame length of LMS
for n = 1 : N
%% LMS
% Convolution
Us(1,2:end) = Us(1,1:end-1); % Shifting of frame window
Us(1,1) = x(n); % Input of LMS
ys = (Wlms)*Us'; % Output of LMS
es = d(n) - ys; % Instantaneous error of LMS
Wlms = Wlms + etas * es * Us; % Weight update rule of LMS
%% Normalized weight difference (NWD)
temp_NWD_lms(n) = norm(Wlms-h)./norm(h); % Normalized weight difference of LMS
temp_MSE_lms(n) = es*es;
end
NWD_lms=NWD_lms+temp_NWD_lms;
MSE_lms=MSE_lms+temp_MSE_lms;
end
% Mean values
NWD_lms=NWD_lms./runs;
MSE_lms=MSE_lms./runs;
% %% Cost function plots
figure
fsize=14; % plot text font size
subplot(2,1,1)
plot(10*log10(NWD_lms),'r','linewidth',2)
lgh=legend(horzcat('Least mean square (LMS)', int2str(SNR),' (dB)'),'Location','NorthEast');
grid minor
xlabel('Iterations','FontName','Times New Roman','FontSize',fsize);
ylabel('NWD in (dB)','FontName','Times New Roman','FontSize',fsize);
title('NWD vs iterations)','FontName','Times New Roman','FontSize',6*fsize/5);
set(lgh,'FontName','Times New Roman','FontSize',fsize)
set(gca,'FontName','Times New Roman','FontSize',fsize)
subplot(2,1,2)
plot(10*log10(MSE_lms),'','linewidth',2)
lgh=legend(horzcat('Least mean square (LMS)', int2str(SNR),' (dB)'),'Location','NorthEast');
grid minor
xlabel('Iterations','FontName','Times New Roman','FontSize',fsize);
ylabel('MSE in (dB)','FontName','Times New Roman','FontSize',fsize);
title('MSE vs iterations','FontName','Times New Roman','FontSize',6*fsize/5);
set(lgh,'FontName','Times New Roman','FontSize',fsize)
set(gca,'FontName','Times New Roman','FontSize',fsize)
saveas(gcf,strcat('LMS_Results.png'),'png')
actual_plant=h;
obtained_model=Wlms;
fprintf('\nactual_plant \t=\t')
fprintf('%2.2f\t',actual_plant)
fprintf('\nobtained_model \t=\t')
fprintf('%2.2f\t',obtained_model)
fprintf('\n\n')