MATLAB: Self avoiding random walk

random walkself avoiding random walk

I need to program a self avoiding random walk, and find the squared mean distance from start to end. I have made the random walk, but as soon as the walk is to long or is repeated to often, it fails. Matlab kinda freezes. I need the chain to be up to 10.000 steps long and repeated at least 100 times, is i my computer that is the problem or is it something else? and how do i fix it?
kind regards
distressed student.
function R=saw(N)
d=zeros(1,N);
n=2;
x=zeros(1,N);
y=zeros(1,N);
while n<=N
d(n)=rand;
if d(n)<0.25
x(n)=x(n-1)-1;
y(n)=y(n-1);
elseif d(n)<0.5
x(n)=x(n-1)+1;
y(n)=y(n-1);
elseif d(n)<0.75
y(n)=y(n-1)+1;
x(n)=x(n-1);
elseif d(n)<1
y(n)=y(n-1)-1;
x(n)=x(n-1);
end
r=[x(1:n);y(1:n)]';
ur=unique(r,'rows');
if size(ur)==size(r)
n=n+1;
end
end
R2=x(end)^2+y(end)^2;
R=sqrt(R2);

Best Answer

The problem is that you walked yourself into an alleyway and you have no mechanism for backing up. You're basically trapped with no place to go. All the potential next step locations (up, down, left, and right) have been visited already. I think you should just set n=1 in that case and start fresh.
Related Question