is it possible to use multiple functions in cellfun

25 次查看(过去 30 天)
I have bellow code:
  • cellfun's first argument - function "func", which contains multiple lines/functions "func1", "func2", ...
cellfun(@(x) func(x), {A, B, C, D})
function func(x)
func1(x)
func2(x)
...
end
is it possible to implement that: use multiple functions as first argument of cellfun, like bellow (off cause bellow is wrong)
cellfun(@(x) func1(x) func2(x), {A, B, C, D})
cellfun(@(x) func1(x),func2(x), {A, B, C, D})
cellfun(@(x) func1(x);func2(x), {A, B, C, D})
  1 个评论
Stephen23
Stephen23 2023-9-11
"is it possible to implement that: use multiple functions as first argument of cellfun, like bellow"
You could use a cell array.

请先登录,再进行评论。

采纳的回答

Rik
Rik 2023-9-11
This is only possible if these functions have an output.
But the more important question is why you want to use cellfun for a more complex situation. Loops are very fast and very efficient. cellfun doesn't magically vectorize your code; it only hides the loop. That extra layer hiding the loop add overhead, resulting in code that is slower than a loop.
The only exception to this rule is the legacy syntax: cellfun('prodofsize',___) is faster than a loop.
So I would suggest calling your function in a loop instead of hacking something together with cellfun.

更多回答(3 个)

Shubham
Shubham 2023-9-11
Hi Leo,
No, it is not possible to directly use multiple functions as the first argument of cellfun in the way you described. The first argument of cellfun expects a single function handle, not multiple functions.
However, you can achieve the desired result by modifying your code slightly. Instead of trying to pass multiple functions directly to cellfun, you can define a wrapper function that calls the multiple functions within it. Here's an example:
A = [1, 2, 3];
B = [4, 5, 6];
C = [7, 8, 9];
D = [10, 11, 12];
% Call the wrapper function using cellfun
cellfun(@(x) wrapperFunc(x), {A, B, C, D});
% Define the individual functions
function wrapperFunc(x)
func1(x);
func2(x);
% ... other function calls
end
function func1(x)
disp(['Function 1 called with input: ', num2str(x)]);
end
function func2(x)
disp(['Function 2 called with input: ', num2str(x)]);
end
In this case, wrapperFunc acts as a single function that encapsulates the multiple function calls func1(x), func2(x), and any other functions you want to include.
I hope this helps!

Bruno Luong
Bruno Luong 2023-9-11
[f1, f2] = cellfun(@(x) deal(func1(x),func2(x)), {A, B, C, D})

Bruno Luong
Bruno Luong 2023-9-11
[f1, f2] = cellfun(@(x) func(x), {A, B, C, D})
function [f1, f2] = func(x)
f1 = func1(x);
f2 = func2(x);
end

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by