-3

How to handle multiple inputs while writing a matlab function ? For example if n is the number of parameters to be passed in the run time then how do my function prototype will look ? Any help will be good. Thanks.

det
  • 3
  • 1

3 Answers3

1

An example of function with various number of parameters is:

function my_function(varargin)

% This is an example
min_arg = 1;
max_arg = 6;

% Check numbers of arguments
error(nargchk(min_arg,max_arg,nargin))

% Check number of arguments and provide missing values
if nargin==1
    w = 80;
end

% Your code ...

end

The same is for the output.

Giacomo Alessandroni
  • 696
  • 1
  • 14
  • 28
0

If the number of arguments can be changed Matlab offers a very good and simple solution for that:

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

Tibor Takács
  • 3,535
  • 1
  • 20
  • 23
0

While for small functions with few arguments, the solution by @GiacomoAlessandroni works nicely, I would suggest something different for more complex functions: Using InputParser.

It features required and optional parameters, as well as name-value pairs. The handling of default values is easy, without if clauses. There is also a very flexible type-checking available.

Instead of creating an example myself, I post the example from the MATLAB help page linked above. The code is pretty much self-explanatory.

function a = findArea(width,varargin)
    p = inputParser;
    defaultHeight = 1;
    defaultUnits = 'inches';
    defaultShape = 'rectangle';
    expectedShapes = {'square','rectangle','parallelogram'};

    addRequired(p,'width',@isnumeric);
    addOptional(p,'height',defaultHeight,@isnumeric);
    addParameter(p,'units',defaultUnits);
    addParameter(p,'shape',defaultShape,...
                  @(x) any(validatestring(x,expectedShapes)));

    parse(p,width,varargin{:});
    a = p.Results.width .* p.Results.height;
end
hbaderts
  • 14,136
  • 4
  • 41
  • 48