3

EDIT: I have modified the question below. The original example I provided was too simplistic to capture the issue I was facing

Consider the following two examples. The first example works fine:

parfor i = 1:4
   for j = 1:3
      A(i,j) = i + j;         
   end
end

However, the second example causes Matlab to complain

B = [1 3 4;1 2 5;2 3 4;1 3 5];
parfor i = 1:4
   for j = 1:3
      A(i,B(i,j)) = i + j;         
   end
end

The error is:

The PARFOR loop cannot run due to the way variable 'A' is used.

How do I fix this?

jonem
  • 429
  • 4
  • 12
  • Why don't you simply switch the outer and inner loops? You might also want to [not use `i` and `j` as variable names](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab) – Adriaan Nov 08 '16 at 17:07
  • @Adriaan Hi, I made the original example too simplistic. The outer index actually defines `vec` by extracting the i'th row from B. – jonem Nov 08 '16 at 17:16
  • 1
    Have a look here: http://www.mathworks.com/help/distcomp/nesting-and-flow-in-parfor-loops.html#bsz9hvi – EBH Nov 08 '16 at 19:05

1 Answers1

4

You need to assign a whole row of A at a time, something like this:

B = [1 3 4;1 2 5;2 3 4;1 3 5];
Am = 4; An = max(B(:));
A = zeros(Am, An);
parfor i = 1:4
    tmp = zeros(1, An);
    for j = 1:3
        tmp(1,B(i,j)) = i + j;
    end
    A(i, :) = tmp;
end

The key parts are that first we create tmp - a temporary array that we can assign into freely, and then we make a single assignment into A that follows the parfor slicing rules.

Edric
  • 23,676
  • 2
  • 38
  • 40