2
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 ?

4

4 回答 4

2

Use nargin in your function to provide some defaults inputs when not enough inputs are provided by the user.

于 2013-09-27T13:32:16.387 回答
2

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
于 2013-09-27T14:50:31.830 回答
1
  1. 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.

  2. The use of varargin is probably the neatest way to do this if you want to exclude elements in general.

  3. 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.

于 2013-09-27T13:41:11.650 回答
0

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)
于 2013-09-27T13:32:00.907 回答