在Matlab中的并行for循环内使用for循环

时间:2019-02-13 06:46:34

标签: matlab for-loop nested-loops parfor

我正在尝试在Matlab的parfor循环内使用for循环。
for循环等效于here中的Ballode示例。
for循环中,调用函数ballBouncing,该函数是一个由6个微分方程组成的系统。

所以,我想做的是为ODE系统使用500个不同的参数值集并运行它,但是对于每个参数集,都会添加一个突然的脉冲,通过“ for”中的代码处理环。

但是,我不明白如何使用parforfor循环来实现此目标,如下所示。
我可以通过使用两个for循环来运行此代码,但是当将外部循环设为parfor时,会出现错误,
the PARFOR loop cannot run due to the way variable results is used
the PARFOR loop cannot run due to the way variable y0 is used
Valid indices for results are restricted in PARFOR loops

results=NaN(500,100);
x=rand(500,10);

parfor j=1:500

    bouncingTimes=[10,50];%at time 10 a sudden impulse is added
    refine=2;
    tout=0;
    yout=y0;%initial conditions of ODE system
    paras=x(j,:);%parameter values for the ODE 
    for i=1:2
        tfinal=bouncingTimes(i);
        [t,y]=ode45(@(t,y)ballBouncing(t,y,paras),tstart:1:tfinal,y0,options);
        nt=length(t);
        tout=[tout;t(2:nt)];
        yout=[yout;y(2:nt,:)];

        y0(1:5)=y(nt,1:5);%updating initial conditions with the impulse
        y0(6)=y(nt,6)+paras(j,10);

        options = odeset(options,'InitialStep',t(nt)-t(nt-refine),...
                                 'MaxStep',t(nt)-t(1));
        tstart =t(nt);
    end

    numRows=length(yout(:,1));
    results(1:numRows,j)=yout(:,1);

end
results;

有人可以帮助我使用parfor外循环来实现此功能吗。

1 个答案:

答案 0 :(得分:1)

将分配固定到results相对简单-您需要做的是确保始终分配整个列。这是我的处理方式:

% We will always need the full size of results in dimension 1
numRows = size(results, 1);
parfor j = ...
    yout = ...; % variable size
    yout(end:numRows, :) = NaN; % Expand if necessary
    results(:, j) = yout(1:numRows, 1); % Shrink 'yout' if necessary
end

但是,y0很难处理-parfor循环的迭代不是顺序无关的,因为您将信息从一个迭代传递到下一个迭代。 parfor仅能处理迭代与顺序无关的循环。

相关问题