Reputation: 1492
It takes variable number of arguments but how can i check if a particular variable argument exists like for example varargin{2}
, So far I have tried using exist
but maybe I am not using it correctly
function vatest(testindex,varargin)
if (exist('varargin{1}','var'))
disp('oneexist')
else if (exist('varargin{2}','var'))
disp('twoexist')
end
end
like for example vatest(1,2,3)
should output
twoexist
NOTE: I am already using nargin
to get the number of inputs ,but please suggest something else than that
UPDATE: Explanation for not using a nargin
lets suppose I have a test function as above
function vatest(testindex,textindex2,textindex3,varargin)
and it does some something like
if nargin >3
%%do something
if nargin >4
%%do something
if nargin >5
%%do something
if nargin >6
%%do something
if nargin >7
%%do something
if nargin >8
%%do something
and for some reason I no longer need testindex3 in the input then I have to change condition for all the if conditions
I hope it clarifies
Upvotes: 3
Views: 2686
Reputation: 14939
YEY I finally got to use the sexist
function:
function vatest(testindex,varargin)
values = {'zero','one','two', 'three', 'four'};
fprintf('%sexist',values{numel(varargin)})
end
For some reason, you didn't want a space between "one" and "exist". So, this should do what you specified (but not necessarily what you want).
On a more serious note, I suggest switch
:
function vatest(testindex, varargin)
num_argin = numel(varargin);
fprintf('%d inputs', num_argin);
switch num_argin
case 1
% Some code
case 2
% Some code
case 3
% Some code
otherwise
% Some code
Upvotes: 1
Reputation: 65460
varargin
is simply a cell array containing the inputs. Therefore, you can determine how many inputs were provided by testing it's length: numel(varargin)
.
exist
is not really designed for this and is likely going to be much slower than simply determining the length of a known variable.
nInputs = numel(varargin)
if nInputs > 1
disp('More than 1 input')
elseif nInputs > 0
disp('Only 1 input')
else
disp('No inputs')
end
Or more simply:
fprintf('%d inputs\n', numel(varargin));
Upvotes: 4