Calling Multiple Functions from Cells in MATLAB

I store some functions in a cell for example. f = {@sin, @cos, @(x)x+4}

...

Is it possible to call all these functions at the same time (with the same input). I mean something more efficient than using a loop.

+3


source to share


3 answers


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]

...

+3


source


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.

      

+3


source


This might do the trick

functions = {@(arg) sin(arg),@(arg) sqrt(arg)}
x = 5;
cellfun(@(arg) arg(x),functions)

      

hope this helps.

Adrien.

0


source







All Articles