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

조회 수: 1 (최근 30일)
In-chan Kim
In-chan Kim 2020년 12월 7일
댓글: Sunand Agarwal 2020년 12월 24일
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