Overloading User Written Function

4 次查看(过去 30 天)
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 中查找有关 Whos 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by