% Perform n steps of random walk starting from (x0,y0)

disp('Do a random walk!')
n = input('How many steps? ');
x0 = input('From what x-coordinate? ');
y0 = input('From what y-coordinate? ');

% possible movements:  ( xdir(i), ydir(i) )
  xdir = [ 1 -1  0  0];
  ydir = [ 0  0  1 -1];

x = [x0 zeros(1,n)];  % trajectory in x direction
y = [y0 zeros(1,n)];  % trajectory in y direction

% Perform walk, each step is based on a random integer
edge = max(10,n/100);
plot(x(1),y(1),'r*')
axis('equal',[x0-edge,x0+edge,y0-edge,y0+edge]);
title([num2str(n) ' steps of random walk from * to o'])
hold on;
for k = 2:n+1
    r = ceil(rand(1,1)*4);  % get a random integer in range 1..4
    x(k) = x(k-1) + xdir(r);
    y(k) = y(k-1) + ydir(r);
    plot(x(k-1:k),y(k-1:k),'-')
    pause(0.5)
 end
plot(x(end),y(end),'ro')
hold off;
