# Metropolis Algorithm Matlab practice - UFL MAE Metropolis Algorithm Matlab practice Matlab code taken from Professor Joo-Ho Choi He applied it to p x 0.3exp 0.2 x 0.7 exp 0.2 x 10 with proposal distribution N(x,10). Matlab code for that give in the notes. Here applied to the triangular distribution with U(x0.25,x+0.25) 2 2 Metropolis-Hastings algorithm Metropolis algorithm A proposal distribution q(x*|x) is symmetric w.r.t x* and x. Then the ratio p x q x | x is simplified. p x * * * A x, x min 1, min 1, * p x q x | x p x * Example: normal pdf at x* with mean at x equals to the vice versa. Practice with matlab Generate samples of this distribution using a proposal pdf

2 p x 0.3exp 0.2 x 2 0.7 exp 0.2 x 10 q x* | x N x,10 As the random walk progresses, the number of samples are increased, and the distribution converges to the target distribution. 0.1 0.09 0.08 0.07 0.06 0.05 0.04 0.03 0.02 0.01 0 -15 -10 -5 0 5

10 15 20 25 -2- Triangular distribution p=2x in [0,1] Matlab realization [email protected](x) heaviside(x).*heaviside(1-x)*2.*x xx=linspace(-1,2,301); fp=p(xx); plot (xx,fp) 2 1.8 1.6 1.4 1.2 1 0.8 0.6 0.4 0.2 0 -1 -0.5 0 0.5 1 1.5

2 Uniform proposal distribution 2 q(x)=U(x-0.25,x+0.25) 1.8 Sampling: 1.4 1.6 1.2 1 clear; X(1)=0; N=1e4; delta=0.25; for i=1:N-1; x=X(i); xs=x+2*(rand-0.5)*delta u=rand if u

0.4 0.6 0.8 1 1.2 1.4 Compare CDFs F(x) ecdf(X); hold on xx=linspace(0,1,101); xx2=xx.^2; plot(xx,xx2,'r') legend('ecdf','exact') 1 0.9 ecdf exact 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1 0

0 0.1 0.2 0.3 0.4 0.5 x 0.6 0.7 0.8 0.9 1 practice problems 1. Try triangular distribution with with a normal proposal distribution with different mean and standard deviations. 2. Do Professor Chois example with different starting points. Source: Smithsonian Institution Number: 2004-57325