필터 지우기
필터 지우기

Overloading User Written Function

조회 수: 3 (최근 30일)
Marc
Marc 2014년 8월 8일
댓글: Marc 2014년 8월 8일
I have a function that can take a variable number of inputs. The function definition looks like this:
function [i] = fun(func,argin1,argin2,argin3, argin4, argin5,argin6,argin7)
These variables then get passed into a switch statement like this:
switch nargin
case 1
try
i = calllib('User_DLL',func);
catch exception
str = {exception.identifier,sprintf('%s did not load',func)};
h = warndlg(str);
waitfor(h);
end
case 2
try
i = calllib('User_DLL',func,argin1);
catch exception
str = {exception.identifier,sprintf('%s did not load',func)};
h = warndlg(str);
waitfor(h);
end...
And it keeps going for all possible number of inputs. Is there a way to overload this function so that I just need to know the number of input and then I can pass the input arguments into calllib in the order they first appeared in? It seems like this process can be greatly streamlined.

채택된 답변

Adam
Adam 2014년 8월 8일
편집: Adam 2014년 8월 8일
I think generally for this you would use a varargin type of input to your function.
You can then test the length of varargin and you can pass it on as varagin{:} to another function that also wants those arguments in the same way.
e.g. if you have a function that will call the plot(...) function you can have a varargin argument to your function (even after named arguments) and then just pass it straight to plot as varargin{:} if you know the arguments are in a form that plot accepts - e.g. property, value pairs.
For example I have a function in one of my classes that does the following:
function setGUIHandleProperty( guiHandle, varargin )
if ishandle( guiHandle )
set( guiHandle, varargin{:} );
end
end
which just acts as a wrapper for setting some figure properties.
  댓글 수: 1
Marc
Marc 2014년 8월 8일
Thank you. That's exactly what I was looking for, trimming down an 85 line long switch statement to 10 lines.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by