is it possible to use multiple functions in cellfun
25 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commento
Stephen23
il 11 Set 2023
"is it possible to implement that: use multiple functions as first argument of cellfun, like bellow"
You could use a cell array.
Risposta accettata
Rik
il 11 Set 2023
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.
0 Commenti
Più risposte (3)
Shubham
il 11 Set 2023
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!
0 Commenti
Bruno Luong
il 11 Set 2023
[f1, f2] = cellfun(@(x) deal(func1(x),func2(x)), {A, B, C, D})
0 Commenti
Bruno Luong
il 11 Set 2023
[f1, f2] = cellfun(@(x) func(x), {A, B, C, D})
function [f1, f2] = func(x)
f1 = func1(x);
f2 = func2(x);
end
0 Commenti
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!