clear clf % Monte Carlo sampling of a probability density function % for simplicity we use the "peaks" function. % Some global parameters ns=100; % number of samples to keep % Let's define a pdf n=100; % number of dimension in x and y pdf=peaks(n); pdf=sqrt(pdf.*pdf); pdf=pdf/(sum(sum(pdf))); figure(1) surf(pdf) % Random walk % find an initial vector x xcur=round([rand rand]*100); % Let s get moving is=1; np=0; xa(1,1)=xcur(1); xa(1,2)=xcur(2); imagesc(pdf'), hold on while is<=ns, np=np+1; % make a random choice for the next move xnew=round([rand rand]*100); xnew(find(xnew==0))=xnew(find(xnew==0))+1; % compare probabilities Pcur=pdf(xcur(1),xcur(2)); Pnew=pdf(xnew(1),xnew(2)); if Pnew >= Pcur, xcur=xnew; is=is+1; if (xcur(1)==77 & xcur(2)==50), is np break;end; xa(is,1)=xcur(1); xa(is,2)=xcur(2); disp(sprintf(' Made the %i-th move to [%i,%i] ', is,xcur(1),xcur(2))) % display move graphically plot([xa(is-1,1) xa(is,1)],[xa(is-1,2) xa(is,2)],'k-') plot([xa(is-1,1) xa(is,1)],[xa(is-1,2) xa(is,2)],'k+') drawnow end end