An UndefinedFunction error thrown by parfor but not for

I have a script 'load_constants.m' that has:
a = 1737400.0;
main program:
load_constants
el = fce();
and the called function is defined:
function el = fce()
load_constants
parfor i = 1:n
alpha = fce2(a)
end
When i run it, i get
Error using fce (line 50)
An UndefinedFunction error was thrown on the workers for 'a'. This might be because the file containing 'a' is not accessible on the workers. Use addAttachedFiles(pool, files) to specify the required files to be attached. For more information see the documentation for 'parallel.Pool/addAttachedFiles'.
Error in run (line 3)
el = fce();
Caused by:
Undefined function or variable 'a'.
When I change the loop to for loop, all works fine.
What is the issue?

 Accepted Answer

Constants defined in scripts cannot be identified by the Matlab, when it parses the parfor block. In addition such scripts have a bunch of further disadvantages also. A good programming practice is to avoid scripts consequently. Use functions instead:
function el = fce()
C = load_constants();
parfor i = 1:n
alpha = fce2(C.a);
end
end
function C = load_constants()
C.a = 1737400.0;
end

More Answers (0)

Categories

Products

Release

R2018b

Tags

Asked:

on 9 Jun 2021

Answered:

Jan
on 9 Jun 2021

Community Treasure Hunt

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

Start Hunting!