0
$\begingroup$

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

enter image description here

$\endgroup$
  • 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
0
$\begingroup$

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))
    break;
end

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 | |
$\endgroup$

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.