
clear
clf

% Monte Carlo sampling of a probability density function

% for simplicity we use the "peaks" function. The corresponding
% section can simply be replaced with the probability from a
% proper inverse problem (e.g. hypocenter location)

% Some global parameters
np=10000;				% number of tries to take
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)));

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<=100,

	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;
      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

   
   