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?
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