Search code examples
matlabparallel-processingparfor

Parfor in Matlab


I'm trying to run this loop as a parfor-loop:

correlations = zeros(1,N);   
parfor i = 1:(size(timestamps,1)-1)
    j = i+1;
    dts = timestamps(j) - timestamps(i);
    while (dts < T) && (j <= size(timestamps,1))
        if dts == 0 && detectors(i) ~= detectors(j)
            correlations(1) = correlations(1) + 2;
        elseif detectors(i) ~= detectors(j)
            dts = floor(dts/binning)+1;
            correlations(dts) = correlations(dts) + 1;
        end
        j = j + 1;
        if j <= size(timestamps,1)
            dts = timestamps(j) - timestamps(i);
        end
    end
end

Matlab gives me the following error:

Error: File: correlate_xcorr.m Line: 18 Column: 17
The variable correlations in a parfor cannot be classified.
See Parallel for Loops in MATLAB, "Overview".

Line 18 is the following:

correlations(1) = correlations(1) + 2;

I can not understand why this shouldn'n be possible. The final value of correlations doesn't depend on the order in which the loop is executed, but only dts and detectors. I found similar examples in the documentation which work fine.

Why can't Matlab execute this code and how can I fix it?


Solution

  • I found the following solution and it seems to work. The program looks a litte different, but it has the same shape. This way Matlab is forced to think x/correlations is a reduction variable.

    X = zeros(1,5);
    parfor i= 1:1000
        a = zeros(1,5);
        dts = randi(10)-1;
        if dts == 0
            a(1) = (a(1) + 2);
        elseif dts <= 5
            a(dts) = a(dts) +1;
        end
        X = X + a;
    end