% BROWN Script which shows a cloud of n particles undergoing Brownian % motion. The motion is simulated by a random walk with normally distributed % steps of mean size dx. Note n and dx can be adjusted for better viewing. % ELB 4/10/05 n = 100; % number of particles dx = 0.006; % distance moved in one step maxsteps = 100000; dt=dx^2; % scaling law for Brownian motion x = zeros(n,1); y = zeros(n,1); % all particles start at origin figure(1), h = plot(x,y,'.'); title('Brownian particles') text(-0.8,0.95,'stops when one leaves box (also: Ctrl-C stops)') axis([-1 1 -1 1]), axis square, grid off set(h,'EraseMode','xor','MarkerSize',18) % makes previous dots disappear for k=1:maxsteps if ~all((x>-1)&(x<1)&(y>-1)&(y<1)), break, end x = x + dx*randn(n,1); y = y + dx*randn(n,1); % new positions set(h,'XData',x,'YData',y), drawnow % draw new positions end disp(['time for first particle to leave box = ' num2str(k*dt)]) disp([' (number of steps of simulation = ' num2str(k) ')'])