How can I write this in MatLab?

4 visualizaciones (últimos 30 días)
Hunter Manning
Hunter Manning el 20 de Abr. de 2022
Editada: William Rose el 20 de Abr. de 2022
Start with 10,000 particles all located at x=0 at time t=0. Implement the Monte Carlo “random walk” in one-dimensions to mimic the diffusion of these particles. Thus, after every “unit time step”, simply move each particle 0.1 units to the right (with probability 0.5) or 0.1 units to the left (with probability 0.5). Plot a histogram of the particle distribution after: (a) 50 time steps, and (b) 500 time steps.

Respuestas (1)

William Rose
William Rose el 20 de Abr. de 2022
Editada: William Rose el 20 de Abr. de 2022
N=10000; T=501; %number of particles and times
a=0.1; %amplitude of each step (+ or -)
x=zeros(N,T); %initialize array to hold position of N particles at T times
for i=2:T
x(:,i)=x(:,i-1)+((rand(N,1)>.5)-.5)*2*a;
end
figure;
subplot(211), histogram(x(:,51));
title('Histogram after 50 steps');
subplot(212), histogram(x(:,501));
title('Histogram after 500 steps');
Try it.
  1 comentario
William Rose
William Rose el 20 de Abr. de 2022
The key line is
x(:,i)=x(:,i-1)+((rand(N,1)>.5)-.5)*2*a;
That line says the vector of new positions, x(:,i), equals the vector of old positions, x(:,i-1), plus the vector of random steps. The random steps vector is
rand(N,1)
which is a N-by-1 vector of random numbers, uniform on (0,1).
(rand(N,1)>.5)
is a vector of 1's and 0's: 1 if true, 0 if false.
((rand(N,1)>.5)-.5)
is a vector of +0.5's (true) and -0.5's (false).
((rand(N,1)>.5)-.5)*2*a
is the final vector, of +a's (true) and -a's (false). Add this to the vector of previous positions.

Iniciar sesión para comentar.

Categorías

Más información sobre Random Number Generation en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by