Reputation: 87
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
.
Upvotes: 1
Views: 779
Reputation: 10580
You don't need to use eval
at all to create a cell array of function handles using a for
or parfor
loop. Then all you need to do is to call each function handle stored in functions
cell array.
functions = cell(1, 10);
parfor i = 1:10
functions{i} = str2func([ 'function', num2str(i) ]);
end
parfor i = 1:10
result = functions{i}();
fprintf('%d ', result);
end
Upvotes: 0
Reputation: 4398
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
Upvotes: 1