Azzera filtri
Azzera filtri

Overloading User Written Function

3 visualizzazioni (ultimi 30 giorni)
Marc
Marc il 8 Ago 2014
Commentato: Marc il 8 Ago 2014
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.

Risposta accettata

Adam
Adam il 8 Ago 2014
Modificato: Adam il 8 Ago 2014
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 Commento
Marc
Marc il 8 Ago 2014
Thank you. That's exactly what I was looking for, trimming down an 85 line long switch statement to 10 lines.

Accedi per commentare.

Più risposte (0)

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!

Translated by