I have been doing some calculations which are output by assigning data to a handle class array. The calculations run fine when I use a for loop but when I try to parallelise this by conversion to a parfor loop, the assigned data are no longer there when the parfor loop ends.
The documentation alludes to this as follows: "Changes made to handle classes on the workers during loop iterations are not automatically propagated to the client."
This implies that it may be possible for such changes to be propagated back, even if it's not done automatically. Does anyone know how I might do this?
Here is some example code:
classdef Example < handle
properties data end methods function obj = Example(data) obj.data = data; end function setData(obj,data) obj.data = data; end function data = getData(obj) data = obj.data; end endend
Now here is some example code which generates an array of these objects and then assigns values to them in a parfor loop. Finally we look at the values of the data.
% Function to demonstrate use of Example in a parfor loop
function testExample num = 5;
% Initialise array of objects
for n = 1:num exArray(n) = Example(zeros(1,6)); end % Set data within a parfor loop
parfor n = 1:num setData(exArray(n),n:n+5); end % Now look at assigned data
for n = 1:num disp(getData(exArray(n))); end
end
When I run this code without the matlabpool open, it behaves as expected:
1 2 3 4 5 6
2 3 4 5 6 7
3 4 5 6 7 8
4 5 6 7 8 9
5 6 7 8 9 10
But when I run with matlabpool open, the updated values are lost outside of the parfor loop, giving this result:
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
Does anyone have any idea how to get around this problem, other than by not using parfor?
Best Answer