1

I have this code:

Result = {};

% parfor k=1:1:3
for k=1:1:3

    % parfor j=1:1:10
    for j=1:1:10
        time = 1000*j;
        [A, B, C] = test (time,k,j);
        Result = cat(1,Result,{k,j,time,A,B,C});
    end

end

Each 'k' iteration takes about 20 minutes, because the function 'test' is heavy. As you see, the variable 'Result' is a cell matrix where each row contains the result of the function along with other variables.

If I change the first 'for loop' for 'parfor' the result is firstly a warning (Warning: The temporary variable Result will be cleared at the beginning of each iteration of the parfor loop) and finally an error (Reference to a cleared variable Result).

As additional data, the two loops can be run in parallel as the 'test' function is independent. The problem is to store the result.

What would you do to solve this?

Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
JaviCru
  • 51
  • 1
  • 9

2 Answers2

2

When running task in parallel, each worker has its own workspace. Therefore, each worker must have its own cells in the results matrix. That is, Result must be pre-allocated and you should assign to a specific row at a time.
For example:

Result = cell(3,10,6);

for k=1:3
    parfor j=1:10
        time = 1000*j;
        [A, B, C] = test(time,k,j);
        Result(k,j,:) = {k,j,time,A,B,C};
    end
end  

Note that either one of the for loop can be changed to parfor

ThP
  • 2,312
  • 4
  • 19
  • 25
0

1) To succesfully create a sliced variable, use only Result{k} inside a parfor loop, where k is your iterator. If you don't like nested cell arrays, take a closer look at this documentation page

2) If you want to nest parfor loops (put one loop into the other), linearize the loops: How to nest multiple parfor loops

Community
  • 1
  • 1
Daniel
  • 36,610
  • 3
  • 36
  • 69