%Drunk Sailor Problem. Individual realizations. Random walks. 
x=[];X=[];
m=5;%number of steps in the bar
N=30;%number of steps given to sailor 
x(1)=1;%Initiaal position of sailor
X=zeros(m+1,N);X(1,1)=x(1);%Preparing 'Position-step number' matrix. (m+1) is the state outside the bar.
%Game itself
for i=1:N
        if x(i)==1;x(i+1)=2;%the first step from the bar
    else z=rand;if z<.5;x(i+1)=x(i)+1;else x(i+1)=x(i)-1;end;end %random choice of intermediate step
    if x(i+1)==m+1,K=i+1;X(x(i+1),K)=1;break;end % he is out
    X(x(i+1),i+1)=1;%filling 'Position-step number' matrix.
end
if i+1<N;k=1;else;k=0;end;k %fixation of the end in Command Window
% plot the results. If you want only matrix graph, put % at 16,17     
figure(1);for j=1:i;bar(x(j),1,'g');axis([.5 m+1+.5 0 1.5]);pause(.3);hold off;end;
bar(x(i+1),1.5,'m');axis([.5 m+1+.5 0 1.5]);
figure(2);colormap(white);
bar3(X(:,1:N));axis([ .5  N+.5 .5 m+1+.5 0 1.0]);ylabel('cell number');xlabel('step number')