%% Ehrenfest Model 

% Ehrenfest Model (Ehrenfest, 1907) illustrates the diffusion in
% gasses by consedering transition of molecules between two 
% compartments. 
% 
% Consider  N balls numbered
% from 1 to N, distributed in two boxes, A and B.
% The system is in state i if i balls are in the box A
% (and N-i balls in the box B).
% A number between 1 and N is randomly selected and 
% the ball with the selected number switches the boxes.
% 
% 
% The system constitutes a Markov chain, since the 
% state of the sistem in future depends on the present and not 
% on the past states.
% 
% Answer the following questions for N=4. Use MATLAB
% where appropriate.
% 
% (a) What are possible states of the system? What are 
% transition probabilities among the states? Write down the
% transition matrix P.
% 
% (b)  What is the most likely state of the system after M=10 steps 
% if all balls originally were in A.
%     
% (c) Explore the probabilities of the states for M=10000 steps,
% and plot the histogram. Are the probabilities close
% to binomial Bin(4+1, 1/2)?
% 
% (d) 
% The stationary probabilities are found by 
% solving the following system:
% N=4;   
% ns=N+1; %number of states
% linsolve([(eye(ns)-P)'; ones(1,ns)],[ zeros(ns,1);1])
% 
% Show that these probabilities coincide with Bin(4+1, 1/2)  probabilities,
% which explains (c).
% 
% 
% 
% P. and T. Ehrenfest, \"Uber zwei bekannte Einw\"ande gegen das Boltzmannsche H-Theorem,"
% Physikalishce Zeitschrift, vol. 8 (1907), pp. 311-31
% 
% 



close all force

N=4;
M=10000;
a=[ (1:N)' ones(N,1)];
b=[];
for i=1:M
a(unidrnd(N,1),2)=1-a(unidrnd(N,1),2);
b=[b sum(a(:,2))];
end
plot(b)
%
sum(b==0)/M

