% Random walk in 2 dimensions in a city with n*n blocks % Goal: find average number of steps to get out the city % if the initial position is random itests = 1000; % number of tests rng('shuffle'); % seed random number generator ncity=0; fprintf(' Random Walk 2 \n') fprintf(' L Steps \n') fileID = fopen('random2.txt','w'); %writing to a file tic while ncity < 100 ncity = ncity+2; stotal = 0; for it=1:itests x = randi([0 ncity],1,1); %initial random position along x y = randi([0 ncity],1,1); %initial random position along y nsteps = 0; out = 0; while (out == 0) nsteps = nsteps+1; iway = randi([0 3],1,1); switch iway case 0 x = x + 1; case 1 x = x - 1; case 2 y = y + 1; case 3 y = y - 1; end %switch if x < 0 || x > ncity || y < 0 || y > ncity % if out of city out=1; end end %while stotal = stotal + nsteps; end %for % average number of steps asteps = double(stotal)/double(itests); fprintf('%5i %5.2f\n', ncity, asteps) fprintf(fileID,'%5i %5.2f\n', ncity, asteps); end %while toc