Reputation: 5789
function y = myFunc(tR,mode)
if ~isfield(tR, 'isAvailable')
tR.isAvailable= false;
end
if tR.isAvailable
y = fullfile(workingFolder,'file.txt');
else
y = '';
switch(mode)
case '1'
.....
case '2'
.....
end
end
when I call myFunc(tR,'1') it'es OK but I would also to be able to call myFunc sometimes without the mode just myFunc(tR)
how could I say in some cases within the function myFunc don't execute the switch case when the mode varaible isn't provided in arguments ?
Upvotes: 2
Views: 232
Reputation: 21563
The use of exist is probably the neatest and simplest way to do this if you want to exclude elements 'at the end', though nargin
can also do the trick. In general I would use nargin
if variables have meaningfull positions or no meaningfull names, and exist
only if they have meaningfull names. See this question for more about this choice.
The use of varargin
is probably the neatest way to do this if you want to exclude elements in general.
However, if you just want to exclude 1 element in the middle, a simple alternative would be:
If you don't want to use the mode
, give it as []
, then you put your switch statement inside this:
if ~isempty(mode)
% Your switch statement here
end
Of course the risk is that strange things will happen if you forget to use the if
statement later in the same function.
Upvotes: 1
Reputation: 9864
The answer by Dennis Jaheruddin gives a good list of possibilities, but I also find using exist
a useful method:
if exist('mode', 'var')
% Your switch statement here
end
Upvotes: 2
Reputation: 13886
Use nargin
in your function to provide some defaults inputs when not enough inputs are provided by the user.
Upvotes: 2
Reputation: 6060
You can use varargin, but you need to access the parameters differently then. Also, check with nargin how many arguments you've got.
http://www.mathworks.de/de/help/matlab/ref/varargin.html
Your function declaration would read:
function y = myFunc(tR, varargin)
Upvotes: 0