Execute multiple functions in parfor

1 view (last 30 days)
Hi, 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));
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. Thank you

Accepted Answer

Walter Roberson
Walter Roberson on 10 Apr 2012
functions = {@function1, @function2, @function3, @function4, @function5, @function6, @function7, @function8, @function9, @function10};
parfor i = 1 : length(functions)
functions{i}()
end
Your current code is going to be a problem, as it will attempt to access the field named "m" in the return value of function "function1"
Any time you use eval(), you are probably doing something wrong. (There are a few times that it is needed, but not often.)
  3 Comments
Walter Roberson
Walter Roberson on 10 Apr 2012
functions = cell(10,1);
for i = 1 : 10
functions{i} = str2func(sprintf('function%d',i));
end
parfor i = 1 : length(functions)
functions{i}()
end

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!