how to create function without having to use all the inputs in the script

21 views (last 30 days)
i have a function with many inputs how can i write this function so i would not have to fill all the inputs? for example now i have this function
T=Tavg('none',12,[],[])
to avoid using the last 2 inputs i must set them to empty array in the script

Accepted Answer

Guillaume
Guillaume on 24 Oct 2014
Edited: Guillaume on 24 Oct 2014
You have several options:
1. Use empty matrices as you have done. Advantages: Optional arguments can be anywhere. Disadvantages: You still have to pass empty matrices for optional arguments.
function T = Tavg(a,b,c,d)
if isempty(a)
a = defaulta;
end
%same for b,c,d
usage:
T = Tavg(a, [], c, []);
2. Use nargin as per James example. Advantages: dead simple. Disadvantages: Only the last(s) argument(s) is(are) optional. You can't have an optional argument in the middle
3. Use the property/value pair that mathworks use for a number of functions like plot. Advantages: Very flexible. Disadvantages: you have to do all the parsing and the user has to refer to the documentation to know the names of the properties.
function T = Tavg(varargin)
a = defaulta; b = defaultb; ...
for opt = 1:3:nargin
switch varargin{opt}
case 'a'
a = varargin{opt+1};
case 'b'
b = varargin{opt+1};
...
usage:
T = Tavg('a', a, 'c', c);
4. Use a class for your function and class property for the optional arguments (like a functor, if you're familiar with C++). Advantages: Very flexible. Automatic tab completion for arguments. Self-documented. Can be reused without having to reenter the arguments. Disadvantages: usage may be too unusual for some people as it's OOP.
classdef Tavg
properties
a = defaulta;
b = defaultb;
...
end
methods
function T = Apply(this)
T = this.a + this.b - this.c * this.d;
end
end
end
usage:
TAvgfun = Tavg;
TAvgfun.a = a;
Tavgfun.c = c;
T = Tavgfun.Apply(); % or T = Apply(TAvgfun);

More Answers (1)

James Tursa
James Tursa on 24 Oct 2014
Use nargin in your function to determine how many inputs are actually being passed in. E.g.
function T = Tavg(a,b,c,d)
if( nargin == 2 )
c = something; % c wasn't passed in
d = something; % d wasn't passed in
end
etc.

Categories

Find more on Scope Variables and Generate Names in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!