Search code examples
matlabparallel-processingparfor

MATLAB parfor error "The variable in a parfor cannot be classified."


I'm trying to run parallel jobs with Parallel Computing Toolbox (PCT) in Matlab. The Matlab code that I would like to run in parallel looks like the following:

I=100000;
a=[-4   0.2  0.3   0.4  0.2; 
   -3   0.7  1.8   1.4  1.1]; 
beta=[0.2 0.3];
c=randi([0 3],I);
S=zeros(1,I);

parfor i=1:1:I
    S(1,i)=1;
    meanPr=a(S(1,1),:); 


    D=1/(1+exp(-(repmat(meanPr(1),1,1) + beta(1,1)*c(1,i))));
    r=rand(1,1);
    D(D>r)=1;
    D(D<1)=0;
    P(1,i)=D;

    xyw(1,i)=poissrnd(meanPr(1,2),1,1);

end

I'm getting the following error:

The variable S in a parfor cannot be classified. See Parallel for Loops in MATLAB, "Overview".

My understanding is that the loops in the aforementioned code are independent. Any idea why I'm getting this error and how it can be resolved?


Solution

  • You are using S(1,1) in each iteration. That is not possible as it adds a dependency between the first iteration (which writes S(1,1)) and all further iterations (which read S(1,1))