Shortcut for applying two functions to two arrays.

1 次查看(过去 30 天)
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.

回答(2 个)

Dyuman Joshi
Dyuman Joshi 2024-1-11
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 2024-1-11
编辑:Florian Bidaud 2024-1-11
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

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by