Calling Multiple Functions from Cells in MATLAB
As built, there is a family of functions *fun
(eg cellfun
) for this purpose . These are other questions about the use and performance of these features.
However, if you construct f
as a function that builds the cell array as
f = @(x) {sin(x), cos(x), x+4};
then you can call the function more naturally: f([1,2,3])
eg. This method also avoids the need for the option pair ( 'UniformOutput'
, false
) required cellfun
for a non-scalar argument.
You can also use regular double arrays, but then you need to be wary of the input form for concatenation purposes: @(x) [sin(x), cos(x), x+4]
vs. @(x) [sin(x); cos(x); x+4]
...
source to share
I'm just posting these results for comparison, just to illustrate that loops aren't necessarily slower than other approaches:
f = {@sin, @cos, @(x)x+4};
x = 1:100;
tic
for ii = 1:1000
for jj = 1:numel(f)
res{jj} = f{jj}(x);
end
end
toc
tic
for ii = 1:1000
res = cellfun(@(arg) arg(x),functions,'uni',0);
end
toc
Elapsed time is 0.042201 seconds.
Elapsed time is 0.179229 seconds.
Troy's answer is almost twice as fast as the loop approach:
tic
for ii = 1:1000
res = f((1:100).');
end
toc
Elapsed time is 0.025378 seconds.
source to share