Clear Filters
Clear Filters

Shortcut for applying two functions to two arrays.

1 view (last 30 days)
I know we can apply a function to an array using the feval functionality.
However, is there a way to apply an array of functions to an array of variables?
for example if my first array are the following functions [@exp, @sin] and I want to apply them to [[1 3 5]; [2 4 6]], is there a way to do this in one go? I am looking for something like the feval functionality but for more than one function and one array.
The output of the above example would look like:
[[exp(1) exp(3) exp(5)]; [sin(2) sin(4) sin(6)]]
All the best.

Answers (2)

Dyuman Joshi
Dyuman Joshi on 11 Jan 2024
Vectorization ftw!
f = @(x) [exp(x(1,:)); sin(x(2,:))];
vec = [1 3 5; 2 4 6];
out = f(vec)
out = 2×3
2.7183 20.0855 148.4132 0.9093 -0.7568 -0.2794

Florian Bidaud
Florian Bidaud on 11 Jan 2024
Edited: Florian Bidaud on 11 Jan 2024
Not entierly sure if that's what you want but you can do that
f = @(fun_array,x) [fun_array{1}(x(1,:)); fun_array{2}(x(2,:))];
f({@exp,@sin},[1 3 5;2 4 6])
ans = 2×3
2.7183 20.0855 148.4132 0.9093 -0.7568 -0.2794

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!