%This m-file generates draws from a triangular density, using the 
%random walk MH algorithm with a normal proposal. 

clear;
clc;
clf;

randn('seed',sum(100*clock));
rand('seed',sum(100*clock));

c = .5;      %variance parameter: can change to see how performance is affected


iter = 51000;
burn = 1000;
U = rand(iter,1);
theta_draws = zeros(iter-burn,1);

current_val = .2;
target_curr = 1- abs(current_val);
source_curr = normpdf(current_val,0,sqrt(c));
counter_accept = 0;

for i = 1:iter;

    candidate = sqrt(c)*randn(1,1);
    source_cand = normpdf(candidate,0,sqrt(c));
    target_cand = max([0 (1-abs(candidate))]);
    
    R = min([1 ( (target_cand*source_curr)/(target_curr*source_cand))]);
    
    %----------------------------------------------------------------
    %decide to accept and update current value and denominator value
    %accordingly
    %----------------------------------------------------------------
    accept_new = .5 + .5*sign(R-U(i));  %=1 if accept new candidate
    current_val = accept_new*candidate + (1-accept_new)*current_val;    
    target_curr = accept_new*target_cand + (1-accept_new)*target_curr;
    source_curr = accept_new*source_cand + (1-accept_new)*source_curr;
    
    if i > burn;
    theta_draws(i-burn,1) = current_val;
    counter_accept = counter_accept + accept_new;
    end;
end;
disp('Fraction of Candidates Accepted')
counter_accept/(iter-burn)
hist(theta_draws,30)    
    