Matlab parfor嵌套循环变量访问

时间:2016-02-12 16:36:58

标签: matlab parfor

我需要在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.

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

If all you want is the minimum value of .container { width: 300px; height: 300px; background-color: #eceded; position: relative; } .info { width: 290px; height: 30px; } .sigma { display: none; } .container:hover~.sigma{ display: block; } , you don't need to store all of the elements - A understands reductions like parfor, so something like this works:

min

Ok, if you want the extremal value and the location, you need to do a bit more work. You don't need to store the whole of A = Inf; parfor i=1:M for j=1:N A = min(A, rand); end end though, you can still phrase this as a A reduction.

parfor