I want to write code to generate a random path through a rectangle of a given size.
I will start at point (0,0) and go up or right to reach xlim and ylim .
Here is my code
y = 10; x = 10; yOld = 0; xOld = 0; figure axis([0 x 0 y]) while yOld < y && xOld < x DirectionChange = randi([0 1],1); if DirectionChange == 0 yNew = yOld + 1; xNew = xOld; else xNew = xOld + 1; yNew = yOld; end line ([xOld xNew],[yOld yNew],'LineWidth',3);hold on yOld = yNew; xOld = xNew; end line ([xNew x],[yNew y],'LineWidth',3);hold off
The code has a while loop , and it ends when one of x or y reaches the limit.
So it works fine x = y .
However, when y > x more likely that the path will reach xlim earlier.
for 12 runs x = 10, y = 10 I get (I made it bright to look better!),

Setting x = 10, y = 20 , I get

As you can see, I lose randomness in the latter case, since the probability of reaching this limit is limited to x .
Any suggestions on how to keep randomness in case x~=y ?
Thanks.
source share