S_S
S_S

Reputation: 1402

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.

Upvotes: 1

Views: 133

Answers (2)

Edric
Edric

Reputation: 25140

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

Upvotes: 0

Daniel
Daniel

Reputation: 36710

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

Upvotes: 1

Related Questions