% Drunk Sailor Problem. Non-symmetric walks. Diffusion.
x=[];k=0;S=[];P=[];
m=5;%number of steps in the bar
d=.2;%symmetric part of transitions
v=.2;%non-symmenric part. Directed to the right
vf=.2;%probability to leave the last working cell

%The matrix
P=zeros(m+1,m+1);
for i=1:m;P(i,i+1)=d;P(i+1,i)=d+v;end;P(m,m+1)=0;P(m+1,m)=vf;
for i=1:m+1;P(i,i)=1-sum(P(:,i));end;
if min(min(P))<0;warning='Matrix is incorrect',break;end %check the matrix for absence of negative elements  
%The initial state vector
S0=zeros(m+1,1);S0(1)=1;
S(:,1)=S0;
N=150;%number of steps (transitions)
for i=1:N
    S(:,i+1)=P*S(:,i);
    end
Sd=diff(S(m+1,:));%Calculation of differential output - outflow
im=[1:N]*Sd';%mean number of steps before leaving - mean residence time
%Plot the results 
figure(1);colormap(white);bar3(S);pbaspect([2 1 1]);axis([.5 N+1+.5 .5 m+1+.5  0 1]);ylabel('cell number');
xlabel('transition number');zlabel('probability')
figure(2);stairs(Sd,'k');hold on;line([im im],[0 max(Sd)],'linewidth',2);grid on;axis([ .5 N+.5 0 1.1*max(Sd)]);
xlabel('transition number');ylabel('outflow')