在 Matlab 中并行处理期间出错

Error during parallel processing in Matlab

我有这个(相当长的)带有嵌套循环的 Matlab 代码,我想在其中并行化主要的耗时迭代。唯一(显然)给我带来问题的变量是 DMax,在那里我得到错误:

Error: The variable DMax in a `parfor` cannot be classified.
See Parallel for Loops in MATLAB, "Overview".

这是我的代码草稿:

t0=matrix (Maxiter,1); % This is a big matrix whose dimensions are reported in brachets
Maxiter = 1E6;
DMax = zeros(Maxiter,40);
% Other Stuff
for j=1:269 
     % Do more stuff
     for soil=1:4
        parfor i =1:Maxiter        
            k(i,soil) = a %k is a real number
            a(i,soil) = b %similar to k
            % Do a lot of stuff
            for t= (floor(t0(i,soil))+1):40
                DMax(i,t) = k(i,soil)*((t-t0(i,soil))^a(i,soil));
                % Do some more stuff
            end
        end
    end
end
for time=1:40
   % Do the final stuff
end

我想问题出在我定义 DMax 的方式上,但我不知道它可能更准确。我已经在网上看了,但结果不是很令人满意。

documentation that each variable inside parfor must be classified into one of several types. Your DMax variable should be a sliced variable (arrays whose segments are operated on by different iterations of the loop), but in order to be classified as such, all the following conditions must hold中描述的很清楚:

  • Type of First-Level Indexing — The first level of indexing is either parentheses, (), or braces, {}.
  • Fixed Index Listing — Within the first-level parenthesis or braces, the list of indices is the same for all occurrences of a given variable.
  • Form of Indexing — Within the list of indices for the variable, exactly one index involves the loop variable.
  • Shape of Array — The array maintains a constant shape. In assigning to a sliced variable, the right-hand side of the assignment cannot be [] or '', because these operators attempt to
    delete elements.

显然,固定索引列表 属性 不成立,因为您将其引用为 DMax(i,t),其中 t 更改了它的值。文档中描述了一个相同的示例,请注意。因此,一种解决方法是在内循环中使用一个临时变量,然后将整行分配回 DMax.

另请注意,变量a也不能归入任何类别。更不用说它根本没有在您的示例中定义。请仔细阅读指南并确保它可以归入其中一类。如果需要重写代码,例如引入新的临时变量。

这是更正 DMax 用法的代码:

Maxiter = 1E6;
t0 = randn(Maxiter,1); % This is a big matrix whose dimensions are reported in brachets
DMax = zeros(Maxiter,40);
% Other Stuff
for j = 1:269 
     % Do more stuff
     for soil = 1:4
        parfor i = 1:Maxiter        
            k(i,soil) = a %k is a real number
            a(i,soil) = b %similar to k
            % Do a lot of stuff
            tmp = zeros(1,40);
            for t = (floor(t0(i,soil))+1):40
                tmp(t) = k(i,soil)*((t-t0(i,soil))^a(i,soil));
                % Do some more stuff
            end
            DMax(i,:) = tmp;
        end
    end
end
for time = 1:40
   % Do the final stuff
end