% Listing 15.4 for Example 15.2 of the book 
% "Principles of System Identification: Theory and Practice"

% Arun K. Tangirala
% September 04, 2015
% Freely distributed under no warranty

%% Generate measurement
ymeas = sqrt(2)*randn(100,1) + 3;

%% Create inline functions for prior and likelihood
sigma_pr = 2; mu_pr = 0;
prior_pdf = inline('(1/sqrt(2*pi*P2^2))*exp(-(1/2)*((theta -  P1).^2/P2^2))','theta','P1','P2');

sigma_wn = sqrt(2);
like_ymeas = inline('(1/sqrt(2*pi*2))*exp(-(1/2)*(y - theta).^2/2)','y','theta');

%% Compute posterior with increasing no. of observations
theta_vec = (-10:0.01:10)';
post_pdf = prior_pdf(theta_vec,mu_pr,sigma_pr);
post_pdf = post_pdf/sum(post_pdf);

for k = 1:100,
    like_y = 1;
    for i = 1:k,
        temp_like = like_ymeas(ymeas(i),theta_vec);
        like_y = temp_like.*like_y;
    end
    post_pdf(:,k+1) = prior_pdf(theta_vec,mu_pr,sigma_pr).*like_y;
    post_pdf(:,k+1) = post_pdf(:,k+1)/sum(post_pdf(:,k+1));
end