Parallel Pool; variable does not exist after running
Afficher commentaires plus anciens
Hello,
When I run the following simple script there is no problem and I'll get i and e at the end of the loop
for i=1:30
e=i/2
end
However, when I want to use parallel pool for the same loop, but with parfor:
parfor i=1:30
e=i/2
end
I don't get any thing when running the loop finishes. Am I missing something here?
Réponses (1)
Raymond Norris
le 13 Août 2020
2 votes
Hi Parsa,
A for loop runs in a serial fashion, one iteration after the other, with the same reproducable results each time (more or less). In your example, we know e will always equal 15. A parfor loop runs its iterations in any order. Therefore, the last value of i could be 14 (and not 30) and therefore, e would equal 7 (and not 15). For this reason, after a parfor, i and e are not know (more about this in a second).
MATLAB must clasify each of the variables within the body of a parfor. You can read more about classification here
Based on this classification, we deem i to be a loop variable and e to be a temporary variables, nether of which persist after the completion of a parfor. Sliced output and reduction variables can be assigned and persist after a parfor.
Raymond
3 commentaires
Walter Roberson
le 13 Août 2020
in order for a change inside parfor to be visible outside the parfor, then one of two things must be true :
- the variable must indexed by the parfor loop control variable; or
- the variable must be acting as a reduction variable
An example of a reduction is
t = 0
parfor k = 1 : 50
t = t + x.^k./factorial(k) ;
end
parfor is able to figure out that the result for t would be the same no matter what order the loop ran, except for round-off error, and permits that case.
Raymond Norris
le 13 Août 2020
I make brief mention at the end about sliced output and reduction variables. In the OP's example, e is neither of them, though I suspect it's a toy example and not the actual code.
Parsa Ghadermazi
le 14 Août 2020
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!