MATLAB:错误

MATLAB: parfor error

我有以下 MATLAB 代码,我想使用 parfor 运行 它:

max = -1;
for i = 1:10
    for j = (i+1):10
       X = my_function(i, j);
       if (X > max)
           max = X;
       end
    end
end
disp(max)

我想将第一个 for 更改为 parfor。我阅读了几个教程和文档,但我不知道如何使用 parfor 获得相同的 max 结果。

我知道 for j = (i+1):10.

中 i 的使用存在一些问题

如有任何建议,我将不胜感激。

can not use parfor for dependent iterations,即在你的情况下 max 是循环迭代之间的因(共享)变量:

You cannot use a parfor-loop when an iteration in your loop depends on the results of other iterations. Each iteration must be independent of all others.

这也反映在显示的警告消息中:

Warning: The temporary variable max will be cleared at the beginning of each iteration of the parfor loop. Any value assigned to it before the loop will be lost. If max is used before it is assigned in the parfor loop, a runtime error will occur. See Parallel for Loops in MATLAB, "Temporary Variables".

MATLAB 实现 one exception to this rule, i.e. Reduction Variables:

The exception to this rule is to accumulate values in a loop using Reduction Variables.

因此,您可以重写代码以使用缩减变量:

maxX = -1;
for i = 1:10
    for j = (i+1):10
       maxX = max(maxX, my_function(i, j));
    end
end
disp(maxX)