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

조회 수: 41 (최근 30일)
Kobi
Kobi 2014년 10월 24일
편집: Guillaume 2014년 10월 24일
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에서 Operators and Elementary Operations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by