How to add a force to Langevin equation with parfor?
조회 수: 10(최근 30일)
표시 이전 댓글
The code below iterates over a simple Langevin equation, representing Brownian motion of 10^5 particles .
tic
dt=0.1;
Particles=10^5;
x=zeros(1,Particles);
MaxTime=10000 ;
parfor ii=1:MaxTime
Gaussian=sqrt(pi*dt)*normrnd(0,1,[1,Particles]);
x=x+Gaussian;
end
toc
The problem is that I don't know how to add a force term to the equation, in a way which still allows me to use parfor.
I want to do something like this:
tic
dt=0.1;
Particles=10^5;
x=zeros(1,Particles);
Force=zeros(1,Particles);
MaxTime=10000 ;
parfor ii=1:MaxTime
Gaussian=sqrt(pi*dt)*normrnd(0,1,[1,Particles]);
x=x+Force*dt+Gaussian;
Force=-x ;
end
toc
This gives the following error message: "The parfor cannot run due to the way variable 'x' is used".
With a standard 'for' loop of course this is not a problem.
It seems that, even though I know that Matlab is naturally paralellized, when one uses vector & matrices correctly, still for the Brownian motion
parfor seems to be 4 times faster than the standard 'for' loop.
How to do this WITH the force term?
댓글 수: 0
채택된 답변
Raunak Gupta
2020년 12월 30일
Hi Erez,
From the code I think parallelization is not possible in this case because if you see the Force variable is updated in every iteration and x is also dependent on the value of Force that is calculated in previous iteration. So, there is a dependency on the sequence of execution of loop. Also, if x is termed as a reduction variable it has to be initialized within parfor loop, which will not be correct as per the logic in code.
You may refer to the following documentations to get information about parfor loops.
추가 답변(0개)
참고 항목
범주
Find more on Parallel for-Loops (parfor) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!