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

2 views (last 30 days)
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

Answers (1)

Sunand Agarwal
Sunand Agarwal on 14 Dec 2020
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 Comments
In-chan Kim
In-chan Kim on 24 Dec 2020
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 on 24 Dec 2020
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.

Sign in to comment.

Categories

Find more on Parallel for-Loops (parfor) in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!