How can I write this in MatLab?

조회 수: 17 (최근 30일)
Hunter Manning
Hunter Manning 2022년 4월 20일
편집: William Rose 2022년 4월 20일
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.

답변 (1개)

William Rose
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
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.

댓글을 달려면 로그인하십시오.

태그

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by