Optional args in MATLAB functions

Yekver picture Yekver · Jul 20, 2011 · Viewed 106.5k times · Source

How can I declare function in MATLAB with optional arguments?

For example: function [a] = train(x, y, opt), where opt must be an optional argument.

Answer

Morgan picture Morgan · Oct 10, 2012

A simple way of doing this is via nargin (N arguments in). The downside is you have to make sure that your argument list and the nargin checks match.

It is worth remembering that all inputs are optional, but the functions will exit with an error if it calls a variable which is not set. The following example sets defaults for b and c. Will exit if a is not present.

function [ output_args ] = input_example( a, b, c )
if nargin < 1
  error('input_example :  a is a required input')
end

if nargin < 2
  b = 20
end

if nargin < 3
  c = 30
end
end