How to work with nested containers.Map()s inside a parfor loop

15 views (last 30 days)
Hi, I am currently having a problem related to using nested containers.Map()s inside parfor loops. The data structure I am working with the following:
I have an outer containers.Map(), whose keys are strings and whose values are other containers.Map()s. The inner containers.Map()s have keys which are strings (the same keys as the outer containers), and values which are arrays.
The purpose of this structure is to store arrays which will be graphed later on. The values inside these arrays are going to be calculated using a parfor loop, which is where I am running into a problem.
This is how I am trying to update the array values. Note, that at the end I want for inner_array_2 to have 2312312 in every entry of the array
outer_container = containers.Map();
outer_container("1") = containers.Map();
inner_container_1 = outer_container("1");
inner_container_1("2") = zeros([1 12]);
parfor x = 1:12
inner_container_2 = outer_container("1");
inner_array_1 = inner_container_2("2");
inner_array_1(x) = 2312312;
inner_container_2("2") = inner_array_1;
outer_container("1") = inner_container_2;
end
inner_container_3 = outer_container("1");
inner_array_2 = inner_container_3("2");
disp(inner_array_2)
However, when I do this, it only outputs an array of zeros. This is in contrast to when I use this exact same code, but with a for loop instead of a parfor loop like so:
outer_container = containers.Map();
outer_container("1") = containers.Map();
inner_container_1 = outer_container("1");
inner_container_1("2") = zeros([1 12]);
for x = 1:12
inner_container_2 = outer_container("1");
inner_array_1 = inner_container_2("2");
inner_array_1(x) = 2312312;
inner_container_2("2") = inner_array_1;
outer_container("1") = inner_container_2;
end
inner_container_3 = outer_container("1");
inner_array_2 = inner_container_3("2");
disp(inner_array_2)
This code outputs an array with 2312312 everywhere, as I wanted. Is there any way for me to modify the parfor loop code to behave the way it would in this for loop?
Note that this is just a toy example, in the actual code I am writing I am also looping over the keys of the inner containers.Map(), which is why they are nested.

Answers (1)

Edric Ellis
Edric Ellis on 21 Apr 2022
containers.Map instances are MATLAB handle objects. These get copied to the workers, and so when you try to modify them on the worker, you're operating on a separate copy. There's more here in the doc. The short answer unfortunately is: don't try to modify containers.Map instances inside parfor. Send your result back in a cell array or something, and modify the containers.Map instance back on your desktop MATLAB.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!