function - matlab differing argument structures -
i want write function getnewprojectionimagesize
has 2 different kinds of argument structures. 1 [wp, hp] = getnewprojectionimagesize(wo, ho)
, other hp = getnewprojectionimagesize(wp)
. on research couldn't find how it. ie this link, doesn't explain it.
possible not effort? in standard matlab functions, ie interp2 there different argument structures: interp(v)
interp(x, y, v, xq, yq)
etc.
solution came mind more common argument structure [wp, hp] = getnewprojectionimagesize(w, h)
h
optional argument (using nargin
), leaving interpretation of w
, h
user. prefer first way if possible.
use nargin
, nargout
know number of input , output arguments function has been called, , use varargin
, varargout
access inputs or define outputs.
you need decide if function called without output arguments. in many functions case treated if call had been 1 output.
here's example.
- with 1 input , 0 or 1 outputs: function outputs element-wise square of input.
- with 2 inputs , 2 outputs: function outputs element-wise sum , product of inputs.
code:
function varargout = f(varargin) if nargin==1 && nargout<2 % nargout<2 covers 0-output case, % interpreted 1 output varargout{1} = varargin{1}.^2; % compute first (and only) output elseif nargin==2 && nargout==2 varargout{1} = varargin{1} + varargin{2}; % compute first output varargout{2} = varargin{1} .* varargin{2}; % compute second output else error('incorrect number of inputs or outputs') end
examples:
>> y = f([10 20 30]) % 1 input, 1 output y = 100 400 900 >> f([10 20 30]) % 1 input, 0 outputs ans = 100 400 900 >> [a, b] = f([10 20 30], 4) % 2 inputs, 2 outputs = 14 24 34 b = 40 80 120 >> y = f([10 20 30], 4) % 2 inputs, 1 output error using f (line 9) incorrect number of inputs or outputs
Comments
Post a Comment