How can I write this in MatLab?

4 ビュー (過去 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.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeRandom Number Generation についてさらに検索

タグ

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by