问题
I am trying to make the following loop parallel-friendly in MATLAB
so that I can use parfor
:
for ivert = 1 : nVerts
b = obj.f( obj.neighIDs{ ivert } );
x = obj.coeffMatrix{ ivert } \ b;
obj.solution( ivert, : ) = x( 1 : 3 );
end
I tried to slice the variables according to MATLAB documentation posted here:
parfor ivert = 1 : nVerts
i = obj.neighIDs{ ivert };
b = obj.f( i );
A = obj.coeffMatrix{ ivert }
x = A \ b;
obj.solution( ivert, : ) = x( 1 : 3 );
end
But MATLAB complains that:
Valid indices for `obj` are restricted in PARFOR loops.
Could someone give me some hints how to slice the variables in the above loop?
回答1:
The problem here is that MATLAB sees the first three lines of your parfor
loop, and treats those as indexing expressions on obj
- and it concludes that obj
must be a parfor
"broadcast" variable. The final line of your parfor
loop is treated as an indexed assignment into obj
(even though it looks like an indexed assignment into a field of obj
). Because obj
has been classified as "broadcast", you cannot assign into it. To fix this, I'd recommend doing something like this:
tmpSolution = zeros(nVerts, 3);
parfor ivert = 1:nVerts
... %# calculate 'x'
tmpSolution(ivert, :) = x(1:3);
end
obj.solution = tmpSolution;
来源:https://stackoverflow.com/questions/37265344/matlab-slicing-variable-for-parfor-loops