Search code examples
matlabmatrixparallel-processingparfor

How to classify a matrix within a Matlab parfor loop?


I am looking to classify the values of a matrix. The following example works outside of a parfor loop, however it does not work when used within a parfor loop. What are my options to classify matrices, following the provided example, within a parfor loop?

% Sample data
Imag1 = [ 62  41 169 118 210;
         133 158  96 149 110;
         211 200  84 194  29;
         209  16  15 146  28;
          95 144  13 249 170];

% Perform the classification
Imag1(find(Imag1 <= 130)) = 4;
Imag1(find(Imag1 >= 150)) = 1;
Imag1(find(Imag1 >  140)) = 2;
Imag1(find(Imag1 >  130)) = 3;

Results in the following (outside parfor loop):

Imag1 =

    62    41   169   118   210
   133   158    96   149   110
   211   200    84   194    29
   209    16    15   146    28
    95   144    13   249   170

Imag1 =

   4   4   1   4   1
   3   1   4   2   4
   1   1   4   1   4
   1   4   4   2   4
   4   2   4   1   1

Solution

  • You can use another matrix to store the result.

    Imag2 = zeros(size(Imag1));
    
    % Perform the classification
    Imag2(find(Imag1 <= 130)) = 4;
    Imag2(find(Imag1 >= 150)) = 1;
    Imag2(find(Imag1 >  140)) = 2;
    Imag2(find(Imag1 >  130)) = 3;
    

    so you can use a parfor loop somehow. Since parfor doesn't care about order of execution. Your code doesn't work in a parfor loop because right now you are modifying the values of Imag1, then comparing those values again, aka any loop iteration would be be dependent on the prior loop iterations