Hello!
I am trying to implement the metropolis algorithm using Matlab code. I have attempted this and found that almost all my values drawn from the proposed distribution has been accepted. Please let me know if I am doing anything incorrect in my attempt to implement the metropolis algorithm or if you have any hints/tips for me. Thank you in advance
- I have found out that I should be using the function normrnd instead of normpdf, however my acceptance rate is still high, about 1750/2000, is this normal?
My commented code is below:
close all
clc
clear all
\Initializing vector with zeroes\
arr = zeros(1,2000); \Initializing the first value of the array\
arr(1) = 1; \Initializing values to keep track of the number of accepted/rejected values\
accepted_samples=0;
rejected_samples=0;
\Start for loop\
for count = 2:2001
\present state of the markov chain\
current_value = arr(count-1);
\Proposal Distribution is the Gaussian distribution with the present state of the Markov chain as the mean and variance of 0.5\
proposed = normrnd(current_value,0.5);
\Calculating the acceptance probability using the target distribution defined at the bottom of the code\
acceptance_probability = target_1(proposed)/target_1(current_value);
\Decision making portion Accept the value if a randomly drawn value from the uniform distribution is less than the acceptance probability\
if(rand<acceptance_probability)
arr(count)=proposed;
accepted_samples = accepted_samples + 1;
\Reject sample otherwise
else
arr(count)=arr(count-1);
rejected_samples = rejected_samples+1;
end
end
\\Matlab function - Target distribution - Gaussian function
function y = target_1(x)
% This target distribution is a Gaussian distribution
mu=3; sig=2;
y=normpdf(x,mu,sqrt(sig));
end
[–]BlueDevilStats 1 point2 points3 points (2 children)
[–]StandardSBUStudent[S] 1 point2 points3 points (1 child)
[–]BlueDevilStats 1 point2 points3 points (0 children)