MATLAB Answers

Global variables in parfor loop

157 views (last 30 days)
Abhinav on 29 Jun 2018
Commented: Abhinav on 29 Jun 2018
I am using global variables in parfor loop and I get following m-lint
The code uses a global variable in a parfor loop. Because parfor loops run on several different machines simultaneously, the global workspace might not be the same on each machine. Therefore, using a global variable in a parfor loop could have unpredictable or unexpected results and Code Analyzer flags it as an error.
This is my code:
parfor samp=1:size(sample,1)
GLOBAL_DATA,GEOMORPH); % these two are global variables
Any suggestions on how to fix it? I don't understand the suggested fix by MATLAB. The suggestion by MATLAB is:
Make local copies of the global variables that you want to use within the parfor loop before beginning the parfor loop
Also,I am not changing my global variables in parfor loop.


Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 29 Jun 2018
Edited: Adam Danz on 29 Jun 2018
What was the suggestion by Matlab? Have you read through the plethora of answers to this topic?
There are lots of reasons not to use global variables at all and this is one of them. As the error message indicates, parfor() is executed in parallel potentially between >1 machine. Global variable are not accessible between machines. So you'll have to initialize them independently within your code.


Show 3 older comments
Abhinav on 29 Jun 2018
I am not updating global variables in the loop. I have two scripts which need to interact with each other.
Steven Lord
Steven Lord on 29 Jun 2018
So your mulgennormrnd function needs information from the CovarianceMatrixEstimation call that took place earlier in the same loop iteration (not cross-iteration)?
The simplest approach, and the one that makes it clear that you're not trying to share data across iterations, would be to have your CovarianceMatrixEstimation function return that information as additional outputs and have your mulgennormrnd function accept that information as additional inputs.
Abhinav on 29 Jun 2018
yes, the output of covarianceMatrixEstimation is used in same iteration, not cross-iteration. Thanks a lot for your suggestion!

Sign in to comment.

More Answers (0)

Sign in to answer this question.