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 
    if B==1
        rnew=r+[0 1];

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

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

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

enter image description here

  • 2
    $\begingroup$ 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]. $\endgroup$ – James Apr 30 '14 at 13:22

You are already handing every step individually, so as @user2697246 says in the comment you can simply add an if statement checking for your condition, and a break.

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.

| cite | improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.