%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 changes


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

current_val = .2;
ratio_denominator = 1- abs(current_val);
counter_accept = 0;

for i = 1:iter;

    candidate = current_val + sqrt(c)*randn(1,1);
    ratio_numerator = max([0 (1-abs(candidate))]);
    R = min([1 (ratio_numerator/ratio_denominator)]);
    
    %----------------------------------------------------------------
    %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;    
    ratio_denominator = accept_new*ratio_numerator + (1-accept_new)*ratio_denominator;
    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)    
    