MATLAB: “Index exceeds matrix dimensions” error when using parfor

Parallel Computing Toolboxparfor

I am using Matlab R2013a 64-bit. I am getting an "Index exceeds matrix dimensions" error when using parfor. The following is a minimal code that produces this error.
matlabpool open 4
nbig = 200;
nsmall = 100;
x = rand(3,nsmall);
parfor n = 1:nbig
if (n <= nsmall)
a = x(:,n);
else
a = zeros(3,1);
end
end
matlabpool close
I am wondering why this happens. Thanks.

Best Answer

parfor is treating x as a sliced variable because of the form of indexing you're using. Once x is determined to be "sliced", the parfor machinery sends slices of x to the workers without knowledge of what they're going to do. Hence it tries to send slices of x that do not exist, and you get the error.
You could make this loop work by forcing parfor to send the whole value of x to each worker by including an operation inside the loop that is not in the sliced form. Here's one way:
parfor n = 1:nbig
if n <= size(x,1) % unsliced access to "x" forces "x" to be "broadcast"
a = x(:, n);
else
a = zeros(3, 1);
end
end
Related Question