MATLAB: How to run a few separate functions in parallell, and keep all of the results in the workspace

classificationMATLABparallel computingParallel Computing Toolboxparfor

I have three different and independent expensive functions that I would like to run in parallel. After some googling, I found this trick:
parfor I=1:3
if I==1
[A,B,C]=f1(A,B,C);
elseif I==2
[D,E,F]=f2(D,E,F);
elseif I==3
[G,H,J]=f3(G,H,J);
end
end
However, I get warnings like these:
The temporary variable A will be cleared at the beginning of each iteration of the parfor loop.
Any value assigned to it before the loop will be lost. If A is used before it is assigned in the parfor loop, a runtime error
will occur.
And since 'A' is cleared at the start of the parfor, it is undefined as input.
How can I do the parallel operation, but keep all of the variables (A,B,C,D,E,F,G,H,J) before, after and during the operation?

Best Answer

The parallel computing toolbox has a function parfeval() which can evaluate functions in parallel. You can then retrieve the result of calling multiple functions in parallel with fetchOutputs().
Example:
tic
F1 = parfeval(@f1, 3, 1,2,3);
F2 = parfeval(@f2, 3, 'a', 1.5, "test");
F3 = parfeval(@f3, 3, 9,8,7);
[R1,R2,R3] = fetchOutputs([ F1, F2, F3 ], 'UniformOutput', false);
disp([R1,R2,R3]);
disp('time:');
disp(toc);
% sleep for 10 seconds to simulate work
function [A,B,C] = f1(A1,B1,C1)
pause(10);
A = A1;
B = B1;
C = C1;
end
function [D,E,F] = f2(D1,E1,F1)
pause(10);
D = D1;
E = E1;
F = F1;
end
function [G,H,I] = f3(G1,H1,I1)
pause(10);
G = G1;
H = H1;
I = I1;
end