【问题标题】:Matlab parfor nested loop variable accessMatlab parfor 嵌套循环变量访问
【发布时间】:2016-02-12 16:36:57
【问题描述】:

我需要在 MATLAB 中使用 parfor 为外部循环编写一个简单的嵌套 for 循环。骨架代码是:

parfor i=1:M
    for j=1:N
         A(i,j)=myFunction(i,j);
    end
end

在这之后,我需要在矩阵A(对应的行号和列号)中找到最大值。但是,在parfor 循环之外无法访问此变量。最简单的方法是什么?这是分类器的多参数调整所必需的。

更新

这是确切的代码:

C1=[0.001;100]; C2=[0.001;100];

A=zeros(length(C1),length(C2));

parfor i=1:length(C1)
  for j=1:length(C2)
     A(i,j)=2*i-3*j;
  end
end

[max_num,max_idx] = max(A(:)); %finding maximum element
[X Y]=ind2sub(size(A),max_num); %retrieving location of max element

% Need to use these values
bestC=C1(X)
bestD=C2(Y)

poolobj = gcp('nocreate');
delete(poolobj);

这给出了错误:

Error: The variable A in a parfor cannot be classified.

【问题讨论】:

  • 循环完成后,A 应该在 parfor 之外可用。我刚刚通过用 A(i,j) = iM + jN; 替换您的内部语句来测试这一点;当您尝试访问它时遇到什么错误?
  • 我已编辑问题以添加代码和错误。请看一看。
  • 我尝试了您的代码并得到了同样的错误。然后我尝试了下面丹尼尔的代码,它有效。很明显,用变量替换length(C1)和length(C2)解决了这个问题。

标签: matlab parfor


【解决方案1】:

稍加修改,Matlab 就能理解您的代码。

C1=[0.001;100]; C2=[0.001;100];
n=length(C1);
m=length(C2);
A=zeros(n,m);

parfor i=1:n
  for j=1:m
     A(i,j)=2*i-3*j;
  end
end

[max_num,max_idx] = max(A(:)); %finding maximum element
[X Y]=ind2sub(size(A),max_num); %retrieving location of max element

% Need to use these values
bestC=C1(X)
bestD=C2(Y)

poolobj = gcp('nocreate');
delete(poolobj);

【讨论】:

    【解决方案2】:

    如果你想要的只是A 的最小值,你不需要存储所有元素 - parfor 理解像 min 这样的缩减,所以这样的事情有效:

    A = Inf;
    parfor i=1:M
        for j=1:N
            A = min(A, rand);
        end
    end
    

    好的,如果你想要极值和位置,你需要做更多的工作。不过,您不需要存储整个 A,您仍然可以将其表述为 parfor 缩减。

    function Axy = pfeg
    
    % Axy contains the running maximum value of A, and the location
    % where it was found. Initialize it with default values:
    Axy = {-Inf, -1, -1};
    parfor i=1:10
        for j=1:10
            % calculate the new value of "A(i,j)"
            tmp = rand();
            % Update the running maximum
            Axy = iReduce(Axy, {tmp, i, j});
        end
    end
    end
    
    function axy = iReduce(axy, candidate)
    if candidate{1} > axy{1}
        axy = candidate;
    end
    end
    

    【讨论】:

    • 我不确定这是否能满足我的要求。我已编辑问题以添加代码和错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    • 2012-11-06
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多