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!