MATLAB Slicing variable for PARFOR loops

我与影子孤独终老i 提交于 2020-01-06 15:18:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!