Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call multiple functions from cells in MATLAB

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

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

like image 317
user1666938 Avatar asked Jan 18 '26 14:01

user1666938


1 Answers

As constructed, the *fun family of functions exists for this purpose (e.g., cellfun is the pertinent one here). They are other questions on the use and performance of these functions.

However, if you construct f as a function that constructs a cell array as

f = @(x) {sin(x), cos(x), x+4};

then you can call the function more naturally: f([1,2,3]) for example. This method also avoids the need for the ('UniformOutput',false) option pair needed by cellfun for non-scalar argument.

You can also use regular double arrays, but then you need to be wary of input shape for concatenation purposes: @(x) [sin(x), cos(x), x+4] vs. @(x) [sin(x); cos(x); x+4].

like image 166
TroyHaskin Avatar answered Jan 20 '26 07:01

TroyHaskin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!