1
votes

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.
2
A should be available outside of parfor once the loop completes. I just tested this by replacing your inner statement with A(i,j) = iM + jN; What error are you getting when you try to access this?Herb
I have edited the question to add the code and error. Please have a look.S_S
I tried your code and got the same error. I then tried Daniel's code below, which worked. So clearly, replacing length(C1) and length(C2) with variables solves the problem.Herb

2 Answers

1
votes

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

If all you want is the minimum value of A, you don't need to store all of the elements - parfor understands reductions like min, so something like this works:

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

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 though, you can still phrase this as a parfor reduction.

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