How can I write this in MatLab?
4 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(1 个)
William Rose
2022-4-20
编辑:William Rose
2022-4-20
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 个评论
William Rose
2022-4-20
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Random Number Generation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!