Variables Unrecognized in parfor but Work in for Loop
Show older comments
I have a struct variable with which I extract each variable using 'eval()'. I then call those variables in a parfor loop and I recieve an error (provided below). Notably, if I define the variable explicitly and don't use 'eval()', the parfor loop works fine... Why is this the case and are there any fixes? I would rather not extract each variable from the struct manually in my code because there are many variables and it would make the code look unorderly.
I would appreciate any suggestions. Thank you!
"Error using *FUNCTION NAME* (line 26)
The source code (*FILE PATH*) for the
parfor-loop that is trying to execute on the worker could not be found.
Caused by:
Unrecognized function or variable 'x0'.
Worker unable to find file.
Unrecognized function or variable 'x0'."
The simplified code is provided as follows:
function [output] = *FUNCTION NAME*(params)
% Start Parallel processing
parpool('local',8)
% Extract variables from the struct
fields = fieldnames(params);
for i = 1:length(fields)
eval([fields{i} ' = params.' fields{i} ';']); % Extract variable from struct (i.e. attain x0)
end
parfor j = 1:NumTrials
[x, z] = truth_gen(x0);
*ADDITIONAL CODE*
end
*ADDITIONAL CODE*
end
EDIT: Upon a more rigorous search, it appears that using 'eval' is bad practice! Instead I will save my variables to a mat file and reload them: https://www.mathworks.com/matlabcentral/answers/299135-is-it-possible-to-extract-all-fields-from-a-structure-automatically#answer_231447
However, for my own knowledge, I am still curious why the creation of variables (via 'eval') does not work in parfor.
EDIT 2: It seems saving the variables in a mat file and loading them still causes the same error. Can someone explain why?
Accepted Answer
More Answers (1)
I am aware of this, but I was hoping to avoid writing 'params.' to reduce clutter in my code.
You might consider this File Exchange download,
It doesn't avoid the need to explicitly unpack the struct, but it reduces the manual effort of writing code to do so, and can also automatically layout the statements in a way that condenses the code. Example, suppose you have a 30-field struct,
args=cell(2,30);
args(1,:)=cellstr("x"+(1:30));
p=struct(args{:}) %struct with 30 fields
Then you can auto-generate the unpacking statements by doing as below and copy/pasting the output text into your code.
columns=6;
structvars(columns,p) %copy-paste the output into your code
Categories
Find more on Parallel for-Loops (parfor) in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!