MATLAB: Parfor indexing problem (Subscripted assignment dimension mismatch)

dimension mismatchindexindexingparfor

I have set up a parfor loop and am receiving the following indexing problem:
Error using parallel_function (line 598)
Subscripted assignment dimension mismatch.
Error in Abel_Shell (line 17)
parfor i = 1:len
This is my code:
len = length(phase(1,:));
parfor i = 1:len
line = phase(i,:);
if max(line) > 1e-2
cen = round(trapz(xaxis.*line)/trapz(line));
lhs = fliplr(line(1:cen));
rhs = line(cen+1:length(line));
denlhs = Abel_DanSteve(lhs,pixel);
denrhs = Abel_DanSteve(rhs,pixel);
density(i,:) = [fliplr(denlhs), denrhs];
else
density(i,:) = 0;
end
end
I have confirmed that len = 3000 at the start of the loop as expected. What could this be?
Thanks, Dan

Best Answer

Firstly, I think your PARFOR loop bounds are suspicious - you calculate 'len' as the number of columns in 'phase', but then use that as the upper bound on the number of rows you're going to access.
I suspect the actual problem is that you haven't pre-allocated 'density'. Normally with PARFOR, you do not need to do this; however in your case I suspect that the 'else' clause is being hit, and you might be hitting an ordering where MATLAB doesn't know how large to make 'density'. The other way to fix this would be to always assign into 'density' using the correct size zeros. I would perhaps modify your code like this:
[nRows, nCols] = size(phase);
parfor i = 1:nRows
line = phase(i, :);
if ...
...
else
density(i, :) = zeros(1, nCols);
end
end