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

问题描述 投票:0回答:1

我试图在Matlab中使用parfor循环内部的for循环。 for循环相当于here中的气球示例。 在for循环内部,调用函数ballBouncing,这是一个由6个微分方程组成的系统。

因此,我想要做的是为ODE系统使用500组不同的参数值并运行它,但是对于每个参数集,会添加一个突然的脉冲,这是通过'for'循环中的代码处理的。

但是,我不明白如何使用parforfor循环实现这一点,如下所示。 我可以通过使用两个for循环来运行此代码,但是当外部循环被设为parfor时,它会给出错误, the PARFOR loop cannot run due to the way variable results is usedthe PARFOR loop cannot run due to the way variable y0 is usedValid 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外循环实现这一点。

matlab for-loop nested-loops parfor
1个回答
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只能处理迭代与顺序无关的循环。

© www.soinside.com 2019 - 2024. All rights reserved.