is it possible to use multiple functions in cellfun

25 ビュー (過去 30 日間)
Leo Zhai
Leo Zhai 2023 年 9 月 11 日
回答済み: Bruno Luong 2023 年 9 月 11 日
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 Center および File ExchangeLoops 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