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
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
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.
댓글 수: 0
추가 답변 (3개)
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!
댓글 수: 0
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!