Constructing class objects before the parfor loop

2 次查看(过去 30 天)
Hi!
I am using OOP by constructing objects and running it multiple times within a while loop. In order to make the code faster, I pass my initial arguments to the class before the loop so it does not need to be initilized everytime.
I am tried switching the while loop to a parfor loop since I have multiple objects which I need to run independently every iteration. However, I am not able to initialize the objects before the parfor loop nor can I figure out how to call the objects after the loop since they are defined within the loop.
I am very new to oop so I might be wrong on many things and I would really appreciate the help.
Thanks!

采纳的回答

Walter Roberson
Walter Roberson 2022-8-2
编辑:Walter Roberson 2022-8-2
It is valid to construct objects and use them in parfor loops.
However, the mechanism used is that the objects are effectively save() on the client and load() on the worker. This will fail if the objects contain anything that is not serializable such as a Java object or an identifier to an open file, or if you are using handle objects and you expect the workers to all be referencing the same object instead of copies of the object.
Global variables and persistent variables are also not copied.
  3 个评论
Walter Roberson
Walter Roberson 2022-8-2
You are updating a variable within a loop. The A for the second time step is not independent from the A for the first time step: the second time step depends on the first having already been run.
However when you convert to a parfor, something like
for K = 1 : ceil(stoptime/timestep) + 1
t = (K-1) * timestep;
A = A.Runtimestep(t);
end
Then you run into the problem that the time steps are done out of order, typically starting at the end, and not in a fixed order. If you could update A in such a case you would be updating out of order. The 20th might get run then the 16th then the 5th then the 19th, and so on. And the updates for one worker could not affect other workers.
There are a small number of cases in which parfor permits variables to be updated. The permitted cases involve "reduction variables" such as F = F + calculation, or F = F * calculation — cases in which algebraically you can do the updates out of order as long as they all get done.
You will not be able to update your objects for use in later iterations; even if the updates turn out to equivalent to reduction variables, MATLAB is not able to analyze methods of classes to prove that updating out of order is safe.
Nagat Elrefaei
Nagat Elrefaei 2022-8-2
Thank you very much! I really appreciate the help and detailed explaination.

请先登录,再进行评论。

更多回答(0 个)

类别

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