function rw2d(N, M)

for j=1:M
   r = rand(1,N);

   for i=1:N
       if (r(i)<0.25)               x(i) = -1; y(i)=0; end
       if (r(i)>=0.25 && r(i)<0.50) x(i) = +1; y(i)=0; end
       if (r(i)>=0.50 && r(i)<0.75) y(i) = -1; x(i)=0; end
       if (r(i)>=0.75)              y(i) = +1; x(i)=0; end
   end

   xx(1) = 0;
   yy(1) = 0;
   for i=2:N
       xx(i) = xx(i-1) + x(i);
       yy(i) = yy(i-1) + y(i);
   end
   
   xfinal(j) = sum(x);
   yfinal(j) = sum(y);
   distance(j) = sqrt(xfinal(j)^2 + yfinal(j)^2);
end

figure(1)
subplot(2, 1, 1)
hist(xfinal)
subplot(2, 1, 2)
hist(yfinal)

figure(2)
plot(xx, yy,'b',xx(length(xx)),yy(length(yy)),'or')