Inside a parfor loop, I am trying to call a function that accesses a global to no avail.
The function
function a = getA()
global OPTIONS;
a=OPTIONS.PROBLEM.A;
end
The loop:
parfor i=1:3
b=getA();
end
The error:
Error using parallel_function (line 589)
Attempt to reference field of non-structure array.
What am I doing wrong?
From the documentation on
parfor:In the context of your problem, i.e., calling a function within the
parforthat in turn references aglobal, this translates into: “parforwill probably not give expected or meaningful results”.This makes perfect sense. Consider the following
if the contents of
GetB()is this:what will the value of
Bbe when it is referenced onLab 1? and onLab 2? How are the different outcomes ofrandcommunicated? It’s going to be a mess!Writing code suited for
parforloops can be a real pain when that code comes from something that only had normalfor-loops in mind. Generally, when you know beforehand you’re going to write a computationally intensive piece of Matlab code, write all functions and loops asparforloops right from the beginning. That is the only way that bugs like these will not cost you a day on transcoding your functions.Converting from
fortoparforis not at all trivial.