% % Example on epage 445 % % Problem on epage 471 % % Written by: % -- % John L. Weatherwax 2008-02-20 % % email: wax@alum.mit.edu % % Please send comments and especially bug reports to the % above email address. % %----- clear all; close all; clc; addpath('../../Code/CSTool'); randn('seed',0); rand('seed',0); % Get the variances for the proposal distributions. sigs = 0.5*ones(3,1); % We will generate 500 iterations of the chain. n = 500; % Set up the vectors to store the samples. X = zeros(3,n); % Get the starting values for the chains. X(1,1) = -25; X(2,1) = -15; X(3,1) = -5; fh=figure; lt = {}; for nc=1:3, % Run each chain: X1 = X(nc,:); for i = 2:n % Generate variate from proposal distribution. y = randn(1)*sigs(nc) + X1(i-1); % Generate variate from uniform. u = rand(1); % Calculate alpha. alpha = normpdf(y,0,1)/normpdf(X1(i-1),0,1); if u <= alpha % Then set the chain to the y. X1(i) = y; else X1(i) = X1(i-1); end end X(nc,:) = X1; lt{nc} = ['X(0) = ',num2str(X(nc,1))]; end figure(fh); hold on; ph=[]; ph(end+1)=plot( X(1,:), 'rx-' ); ph(end+1)=plot( X(2,:), 'gx-' ); ph(end+1)=plot( X(3,:), 'x-k' ); grid on; xlabel('iteration value'); ylabel('X(i)'); title( 'MC Chain as a function of different starting values' ); legend( ph, lt, 'location', 'southeast' ); saveas( gcf, '../../WriteUp/Graphics/Chapter11/prob_11_4_chain_w_diff_starts', 'epsc' ); clear functions;