Pergunta

I'm trying to write a function in MATLAB, having optional input arguments and the function is called in for loop, I want two things:

  • firstly, optional input arguments i.e no need of sequence of inputs
  • secondly, whenever the function is calling, it numbers the variable name so that no conflict is left, it is required as no output is deserved.

My function:

function mYfunc(a,b,c,d,e,f)
var1= 'some string';
% for numbering, may be use of eval(['var' num2str(1)]) but how the function call is identified, 
% i.e in same loop function calls again, then iteration is identified

if nargin >= 3
 %some operation
end

if nargin >= 4
  %some operation
end
if nargin >= 5
   %some operation
end
if nargin >= 6
   %some operation
end
end

The for loop:

for i=1:3
mYfunc(a,b,c,d,e,f); %first call, var1 is expected
mYfunc(a,b,e,f); %second call, var2 is expected
mYfunc(c,d,e,f); %third call, var3 is expected
mYfunc(a,b,c,d); %fourth call, var4 is expected
mYfunc(c); % fifth call, var5 is expected
end
Foi útil?

Solução

You may be able to use varargin along with your if statement to assign inputs to certain variable names (e.g. if nargin==4, b=varargin{2}; end or whatever you want).

There is a slight learning curve, but for the most versatile solution I also suggest you look into using MATLAB's inputParser, which gives you all the flexibility you need. It also allows you to specify inputs by a name (string). See also this description of inputParser.

Outras dicas

I don't quite understand your question, but probably the inputname function can help you. It tells you the name of a certain argument when the function is called.

http://www.mathworks.com/help/matlab/ref/inputname.html

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top