用mcmc方法生成markov链 的MATLAB代码
时间: 2023-09-11 09:04:25 浏览: 149
用MATLAB仿真markov链程序.docx
以下是一个使用Metropolis-Hastings算法生成Markov Chain的MATLAB代码示例:
```matlab
% Metropolis-Hastings algorithm to generate Markov Chain
% Define the target distribution
target_dist = @(x) exp(-x.^2/2) ./ sqrt(2*pi);
% Define the proposal distribution (normal distribution)
proposal_dist = @(x) normrnd(x, 1);
% Set the number of iterations and the initial state
n_iterations = 10000;
x = 0;
% Preallocate memory for the Markov Chain
markov_chain = zeros(n_iterations, 1);
% Loop over the iterations
for i = 1:n_iterations
% Propose a new state
x_new = proposal_dist(x);
% Compute the acceptance probability
alpha = min(1, target_dist(x_new)/target_dist(x));
% Generate a random number from a uniform distribution
u = rand();
% Accept or reject the proposed state
if u <= alpha
x = x_new;
end
% Store the current state in the Markov Chain
markov_chain(i) = x;
end
% Plot the Markov Chain and the target distribution
x_range = -5:0.1:5;
figure;
histogram(markov_chain, 'Normalization', 'pdf');
hold on;
plot(x_range, target_dist(x_range), 'LineWidth', 2);
xlabel('x');
ylabel('p(x)');
legend('Markov Chain', 'Target Distribution');
```
这个例子中,我们使用了一个目标分布 $p(x) = e^{-x^2/2}/\sqrt{2\pi}$ 和一个正态分布作为建议分布。我们使用Metropolis-Hastings算法从初始状态 $x=0$ 开始生成长度为10000的Markov Chain,并将其与目标分布进行比较。
如果需要更好的理解MCMC方法,可以参考相关教材和文献,如《MCMC方法及其在统计学习中的应用》、《Bayesian Data Analysis》等。
阅读全文