我将使用这个简单的,独立的函数,应该将其作为输入:初始位置,力,时间步长和迭代次数;并返回输出:时间和位置向量。
function [time,pos] = example(pos0, force, N, dt)
clc;
pos = zeros(N+1,3);
vel = zeros(N,3);
pos(1,:)=pos0;
for i = 1:N
time(i+1) = i*dt;
% solver finds the velocities given forces and previous positions
vel(i,:) = force./(norm(pos(i,:)+1));
% evolution calculates new positions using new velocities
pos(i+1,:) = pos(i,:) + vel(i,:)*dt;
end
end
我想使用并行池来计算这一点-在我的情况下,它由2个内核组成。由于使用了变量pos
的方式,下面的修改后的代码不起作用,这使得每次迭代都依赖于前一个。我该如何解决?我已经阅读了文档,但是即使对于这种简单的情况,它也对我来说还是很晦涩的。可以完全并行化吗?
function [time,pos] = example(pos0, force, N, dt)
clc;
delete(gcp('nocreate'));
pos = zeros(N+1,3);
vel = zeros(N,3);
pos(1,:)=pos0;
parpool(2)
parfor i = 1:N
time(i+1) = i*dt;
% solver finds the velocities given forces and previous positions
vel(i,:) = force./(norm(pos(i,:)+1));
% evolution calculates new positions using new velocities
pos(i+1,:) = pos(i,:) + vel(i,:)*dt;
end
end