Parallel for loop parfor clasiffying variable for a structure input how to?

2 次查看(过去 30 天)
Hi,
I have a structure that I fill in by loading a data in a loop, where each loop opens a particular file and fills the structure.
What would be the correct way of doing it in a parfor?
Currently, the code works if I use for loop instead of parfor.
When I use parfor, I get this error:
Error: Unable to classify the variable 'indvoutputagg' in the body of the parfor-loop. For more information, see Parallel for Loops in
MATLAB, "Solve Variable Classification Issues in parfor-Loops".
form=1;
scenarios = 1:4;
N = numel(scenarios);
filedir = 'Outputs';
indvoutputagg = cell(N,1); % preallocate
indvoutputcomp={};
tic
parfor k = 1:N
filename = sprintf('Form1_Scenario%d_indvoutputagg.mat',scenarios(k));
indvoutputagg{k,:} = importdata(fullfile(filedir,filename)); % allocate using indexing
% Make it into one big table
indvoutputcomp(1+size(indvoutputcomp,1):size(indvoutputcomp,1)+size(indvoutputagg{k,1},1),:)=indvoutputagg{k};
end

回答(1 个)

Sunand Agarwal
Sunand Agarwal 2020-12-14
Hello,
This usually happens because the variable 'indvoutputagg' exists in the function workspace on the worker while the loop runs in the worker's base workspace.
Use either evalin or assignin inside of the parfor body to create or move the variable to the base workspace of the worker. For this example, you could use
assignin('base', 'indvoutputagg{k,:}', importdata(fullfile(filedir,filename)));
to assign a value 'indvoutputagg' in the worker's base workspace.
Hope this helps.
  4 个评论
In-chan Kim
In-chan Kim 2020-12-24
Thank you.
Just so I understand correctly, is this what you had in mind?
form=1;
scenarios = 1:9;
N = numel(scenarios);
filedir = 'Outputs';
indvoutputagg = cell(N,1); % preallocate
indvoutputcomp={};
tic
for k = 1:N
filename = sprintf('Form1_Scenario%d_indvoutputagg.mat',scenarios(k));
assignin('base', 'indvoutputagg{k,:}', importdata(fullfile(filedir,filename)));
end
Sunand Agarwal
Sunand Agarwal 2020-12-24
Hello
Yes, your code should work now if you change the loop to parfor as well.
Usually, whenever we assign a variable in the parfor loop using the assignment operator, it is assigned to the worker's function workspace as mentioned before.
For example,
b = 1;
The above statement assigns the variable 'b' to value '1' in the function workspace of the worker. To assign it to the base workspace of the worker for the parfor loop to work successfully, we use the 'assignin' function as below:
assignin('base', 'b', 1);
Hope this helps.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Parallel for-Loops (parfor) 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by