clear all
clc


n=1000;
x(1,:)=random('normal',0,10,1,n);
u1=random('normal',0,10,1,n);


for i=1:20
    u1=random('normal',0,10,1,n);
    x(i+1,:)=0.5*x(i,:)+(25*x(i,:)/(1+x(i,:).^2)) + 8*cos(1.2*i)+u1;
    v1=random('normal',0,1,1,n);
    wt1(i,:)=((x(i,:).^2)/20) + v1;  
    wt(i,:)=wt1(i,:)/(sum(wt1(i,:)));
    
    for j=1:n
       x_0=find(rand<cumsum(wt(i,:)));
       x_1 = min(x_0);
       xhat(i,j)=x(i,x_1);
    end
end
normx1(i)=norm(x(i,:)-mean(xhat(i,:)));
for i=1:20
    sum1=0;
    for j=1:n
       sum1 = sum1 +x(i,j)*wt1(i,j)/(sum(wt1(i,:))/n); 
    end
    avg1(i) = sum1/n;
    normx1(i)=norm(x(i,:)'-avg1(i)*ones(n,1));
end

figure(1)
hist(x(1,:));
title(['Histogram of x when t=1']);
saveas(figure(1),['Histogram when (t=1) x prob 3.png']);

figure(2)
hist(xhat(1,:));
title(['Histogram of xhat when t=1']);
saveas(figure(2),['Histogram when xhat, (t=1) x prob 3.png']);

figure(3)
hist(x(5,:));
title(['Histogram of x when t=5']);
saveas(figure(3),['Histogram when (t=5) x prob 3.png']);

figure(4)
hist(xhat(5,:));
title(['Histogram of xhat when t=5']);
saveas(figure(2),['Histogram when xhat, (t=5) x prob 3.png']);


figure(5)
hist(x(10,:));
title(['Histogram of x when t=10']);
saveas(figure(5),['Histogram when (t=10) x prob 3.png']);

figure(6)
hist(xhat(10,:));
title(['Histogram of xhat when t=10']);
saveas(figure(6),['Histogram when xhat, (t=10) x prob 3.png']);

figure(7)
hist(x(15,:));
title(['Histogram of x when t=15']);
saveas(figure(7),['Histogram when (t=15) x prob 3.png']);

figure(8)
hist(xhat(15,:));
title(['Histogram of xhat when t=15']);
saveas(figure(8),['Histogram when xhat, (t=15) x prob 3.png']);

figure(9)
hist(x(20,:));
title(['Histogram of x when t=20']);
saveas(figure(9),['Histogram when (t=20) x prob 3.png']);

figure(10)
hist(xhat(20,:));
title(['Histogram of xhat when t=20']);
saveas(figure(10),['Histogram when xhat, (t=20) x prob 3.png']);

figure(11)
plot(normx1);
title(['||X(t) - Xhat(1)|| versus time']);
saveas(figure(11),['Error plot prob 3.png']);
