Drunken Man in Matlab

I wrote a script that plots the results of the "drunken lamppost" problem in MATLAB. Now I need to create a road-width from -3 to +3, length from 0 to infinity but the drunk can walk just ahead. It means that when he reaches the road's edge MATLAB will automatically stop plotting.

My code is here:

r=[0 0];
for t= 0:0.1:100
B1=rand(1,2);
B=B1>0.5;
if B==1
rnew=r+[0 1];

elseif B(1)==1
rnew=r+[-1 1];

elseif B(2)==1
rnew=r+[1 1];
end

hold on;
plot([r(1) rnew(1)],[r(2) rnew(2)]);
drawnow ;
r=rnew;
end


• Cant you just insert an if statement? You know his cartesian x-y coordinates from the rnew vector, so it seems like you could just check with an if statement whether rnew is outside [-3,3]. – James Apr 30 '14 at 13:22

In other words add this right before the end for your for loop:
if ((rnew(2) < -3) || (rnew(2) > 3))

I do have a comment about your first conditional, B==1. B is a logical matrix, and I can't find in the documentation how matlab handles this. Please make sure this is doing what you think it is, and consider rewriting it if you can find a better way to express your logic.