필터 지우기
필터 지우기

Passing function handle to another function and assigning varying number of input arguments to it

조회 수: 1 (최근 30일)
Hi,
I am trying to write a code in which I need to pass a handle function to another function, let say
function b=myfun1(a)
b=2*a;
end
function b=myfun2(handle_f,a)
b=a*handle_f(a)
end
result=myfun2(@(aa)myfun1(aa),a);
Well, this works perfectly fine. Now let say that I want to decide to vary the number of and type of arguments of myfun1 or use completely different function. How should I write myfun2 to be able to work with any type of function with different number of input arguments and of course same output type?

답변 (1개)

Andrei Bobrov
Andrei Bobrov 2012년 4월 20일
please read about varargin, nargin and varargout, nargout
eg
function b=myfun2(handle_f,varargin)
a = varargin{1};
b=a.*handle_f(varargin{:})
end
on Hossein's comment
myfun2(@(x)myfun3(x,y),a); %here y is defined
myfun2(@(y)myfun3(x,y),a); %here x is defined
myfun2(@(x,y)myfun3(x,y),a,y);
myfun2(@(y,x)myfun3(x,y),a,x);
  댓글 수: 2
Hossein
Hossein 2012년 4월 20일
Hi,
Thanks, I think I am getting there. Now how do I pass @(x,y)myfun3(x,y) as argument and then assign a and b to myfun3?
myfun2(@(x,y)myfun3(x,y),a);
Andrei Bobrov
Andrei Bobrov 2012년 4월 21일
myfun2(@(x)myfun3(x,y),a); %here y is defined
or
myfun2(@(y)myfun3(x,y),a); %here x is defined

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Argument Definitions에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by