Search code examples
multithreadingmatlabparallel-processingparfor

Execute multiple functions in parfor


Currently I have several functions, named function1.m, function2.m, function3.m , ..., function10.m. Each function is independent each other. I would like to run the all the functions in one execution

currently, my code is like this, it runs the functions one by one.

for i = 1 : 10
  result = eval(sprintf('function%d.m',i));
  fprintf('%d ', result);
end

I would like to know is there a way to rewrite the code in parfor instead of for, as I know that eval does not work in parfor.


Solution

  • Use eval in a normal loop to populate a cell array of function handles?

    functions = cell(10, 1);
    for i=1:10
      functions{i} = eval(sprintf('@()function%d', i));
    end
    parfor i=1:10
      result = functions{i}();
      ...
    end