I want to write a function getNewProjectionImageSize
that has two different kinds of argument structures. One is [Wp, Hp] = getNewProjectionImageSize(Wo, Ho)
and the other is Hp = getNewProjectionImageSize(Wp)
. On my research I couldn't find how to do it. Ie this link, doesn't explain it.
Is it possible with not too much effort? In standard matlab functions, ie interp2 there are different argument structures: interp(V)
interp(X, Y, V, Xq, Yq)
etc.
The only solution that came to my mind is a more common argument structure [Wp, Hp] = getNewProjectionImageSize(W, H)
with H
as an optional argument (using nargin
), leaving the interpretation of W
and H
to the user. But I would prefer the first way if it is possible.
matlab differing argument structures
51 views Asked by Peter At
2
There are 2 answers
0
On
Use varargin
as your input argument and varargout
as the output. These allow you to accept/return variable numbers of inputs and outputs. E.g. something like this:
function varargout = getNewProjectionImageSize(varargin)
if nargin==1
% Have passed in one input argument, Wp
Wp = varargin{1};
% Calculate Hp here...
varargout{1} = Hp;
elseif nargin==2
% Have passed in two input args, Wo, Ho
Wo = varargin{1};
Ho = varargin{2};
% Calculate Wp and Hp here ...
varargout{1} = Wp;
varargout{2} = Hp;
else
error('Must supply one or two input arguments');
end
end
An alternative would be to pass in named arguments with key/value pairs, so your calls would look like:
[Wp, Hp] = getNewProjectionImageSize('Wo',Wo, 'Ho',Ho)
Hp = getNewProjectionImageSize('Wp',Wp)
There's some description of how to do that here using inputParser.
Use
nargin
andnargout
to know the number of input and output arguments with which the function has been called, and then usevarargin
andvarargout
to access the inputs or define the outputs.You also need to decide what to do if the function is called without any output arguments. In many functions that case is treated as if the call had been with one output.
Here's an example.
Code:
Examples: