对目标函数target_dist = @(x) x(1).*x(2)-1500用M-H生成 MCMC链的代码
时间: 2023-06-27 15:06:19 浏览: 84
以下是使用 Metropolis-Hastings 算法生成 MCMC 链的 MATLAB 代码,其中目标函数为 $target\_dist(x) = x_1 \cdot x_2 - 1500$:
```matlab
% Define the target distribution
target_dist = @(x) x(1).*x(2) - 1500;
% Define the proposal distribution (a normal distribution centered at the current sample)
prop_dist = @(x) [normrnd(x(1), 1), normrnd(x(2), 1)];
% Define the initial sample
x0 = [1, 1500];
% Set the number of iterations and burn-in period
n_iter = 10000;
burn_in = 1000;
% Initialize the MCMC chain
chain = zeros(n_iter, 2);
chain(1,:) = x0;
% Run the MCMC algorithm
for i = 2:n_iter
% Propose a new sample
x_prop = prop_dist(chain(i-1,:));
% Calculate the acceptance probability
alpha = min(1, target_dist(x_prop)/target_dist(chain(i-1,:)));
% Accept or reject the proposed sample
if rand() < alpha
chain(i,:) = x_prop;
else
chain(i,:) = chain(i-1,:);
end
end
% Remove the burn-in period from the chain
chain = chain((burn_in+1):end,:);
```
在上述代码中,我们首先定义了目标函数 `target_dist` 和建议分布 `prop_dist`。然后,我们定义了初始样本 `x0`,设置了迭代次数 `n_iter` 和燃烧期 `burn_in`。接着,我们初始化了 MCMC 链 `chain`,并在循环中运行了 M-H 算法。最后,我们从链中删除了燃烧期的样本,并返回得到的 MCMC 链。
阅读全文