"valid indices for 'a' are restricted in PARFOR loops" for unindexed struct?
73 views (last 30 days)
Show older comments
For the following code:
parfor k = 1:2
a.b = k;
end
I'm getting the error "valid indices for 'a' are restricted in PARFOR loops"
But there is no indexing here. Could someone explain what I'm missing?
In case it's important, the code above comprises the entire script.
You cannot create a structure in a parfor-loop using dot notation assignment.
It's not clear why, though.
Edit 2: Mathworks support has submitted an enhancement request to update the error message to something clearer in a future release.
MATLAB Version: 9.1.0.441655 (R2016b)
0 Comments
Answers (1)
OCDER
on 16 Jul 2018
Edited: OCDER
on 16 Jul 2018
parfor k = 1:2
a(k).b = k;
end
The reason a.b = k does NOT work is because when the parfor finishes, and there are, say N workers creating 1000 parallel versions of a.b = k, which one is going to be the final a.b? If 1000's of parallel universes converge into 1 universe, which universe will we be the "real" universe? Error error.
But, a(k).b = k works because each worker creates its own separate variable (or isolated universe), a(1).b, a(2).b, ..., a(N).b. No conflict issues.
In the example, this works too because temp is defined inside the parfor, which tell matlab "this is a temporary variable that's created in the parallel world - do not bring it to the real world"
parfor i = 1:4
temp = struct(); %What's created in the parallel world stays in the parallel world
temp.myfield1 = rand();
temp.myfield2 = i;
end
7 Comments
See Also
Categories
Find more on Parallel for-Loops (parfor) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!