MATLAB: Indexing error using the ‘parfor’ command

indexingparfor

I am new to parallizing code. I am trying to implement a simple parfor. Each iteration of the loop is independent of all others, which I thought was the only consideration in using parfor. But Matlab is giving me an error saying the the () line has invalid indexing for the density variable. What's interesting is it doesn't have a problem with the line just above it. I tried reading about "Sliced Variables" at Matlab's suggestion, but it didn't get me anywhere. Can anyone give me a pointer here?
Thanks, Dan
PS – I realize there's an error in those lines where I'm overwriting the "cen" index, but that's an independent issue.
len = length(phase);
parfor i = 1:length(data.phasemap)
line = phase(i,:);
if max(line) > 1e-2
cen = round(trapz(xaxis.*line)/trapz(line));
lhs = fliplr(line(1:cen));
rhs = line(cen:length(line));
denlhs = Abel_DanSteve(lhs,data.pixel);
denrhs = Abel_DanSteve(rhs,data.pixel);
density(i,1:cen) = fliplr(denlhs);
density(i,cen:len) = denrhs; %**
else
data.density(i,:) = 0;
end
end

Best Answer

When slicing an output variable, PARFOR requires that you always use the same indexing expression. It should work to do:
density(i, :) = [fliplr(denlhs), denrhs];
Or similar. This way, you're always assigning into density the same way.