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

18 次查看(过去 30 天)
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

采纳的回答

Guillaume
Guillaume 2014-10-24
编辑:Guillaume 2014-10-24
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);

更多回答(1 个)

James Tursa
James Tursa 2014-10-24
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.

类别

Help CenterFile Exchange 中查找有关 Scope Variables and Generate Names 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by