【问题标题】:Error during parallel processing in MatlabMatlab中并行处理期间的错误
【发布时间】:2016-05-10 16:08:23
【问题描述】:

我有这个(很长)带有嵌套循环的 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 的方式上,但我不知道它可以更准确地定义。我已经在网上看了,但结果不是很满意。

【问题讨论】:

    标签: matlab loops parallel-processing parfor


    【解决方案1】:

    documentation 中非常清楚地描述了 parfor 中的每个变量都必须分类为几种类型中的一种。您的DMax 变量应该是一个切片变量其段由循环的不同迭代操作的数组),但为了归类,@987654322 @:

    • 一级索引的类型 — 一级索引可以是圆括号 (),也可以是大括号 {}。
    • 固定索引列表 - 在第一级括号或大括号内,索引列表对于所有出现的 a 都是相同的 给定变量。
    • 索引形式 — 在变量的索引列表中,只有一个索引涉及循环变量。
    • 数组形状 — 数组保持不变的形状。在对切片变量赋值时,赋值的右侧不能是 [] 或 '',因为这些运算符试图
      删除元素。

    显然,Fixed Index Listing 属性不成立,因为您将其引用为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
    

    【讨论】:

    • 感谢您的回答,现在代码运行没有错误。对于我提出的问题,我深表歉意,但我不得不说我根本没有发现 Mathworks 的描述很清楚。尽管如此,还是非常感谢你。顺便说一句,我猜你错过了 for 循环中的“tmp (t)”,因为这是我运行它的方式,它完美地替换了我以前的代码。
    • 正确,修正了我的答案。很高兴有帮助)
    猜你喜欢
    • 2013-01-05
    • 1970-01-01
    • 2012-12-14
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多