Search code examples
matlabparfor

Matlab parfor nested loop variable access


I need to write a simple nested for loop in MATLAB using parfor for the outer loop. The skeletal code is:

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

After this, I need to find the maximum value in the matrix A (corresponding row and column numbers). However, this variable is not accessible outside of the parfor loop. What is the simplest way to do this? This is required for multiple parameter tuning for a classifier.

Update

Here is the exact code:

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);

This gives the error:

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

Solution

  • Minor modification and Matlab is able to understand your code.

    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);