When writing functions in MATLAB sometimes the function requires a number of arguments some of which can have default values. So when the arguments are given, they overwrite the default arguments. Consider the following example:

function c = myfcn(a,b) if nargin < 2 b = 2; end c = a+b; end

First of all, we can determine the number of arguments given when the function was executed. based on the number of arguments, we can then decide whether use the default value for **b** or use the given value. In this case: **myfcn(2,3)** results in **5** but **myfcn(2)** results in **4**.

This is good, but the problem begins when the number of arguments increases. Consider the function has **8** arguments. In order to decide whether using the default or the given values, you should check which arguments are given and which are not. In other words, you might need to write an if for different conditions, for instance:

function k = myfcn(a,b,c,d,e,f,g,h) if nargin < 8; h=0.2; end if nargin < 7; g=0.3; end if nargin < 6; f=1; end if nargin < 5; e=0; end ... end

You can see this is ugly and not professional. It also prevents you from providing the function with a specific set of parameters, say you want new values for **d** and** f** and want to use the default values for the rest of the arguments.

The best way, I know and have used for a long time is using the arguments as a cell list. Check the following example:

function y = myfcn(n,varargin) defaultValues = {2 20 150 0.85}; % default values {x1 x2 x3 x4}; idx = ~cellfun(@isempty,varargin); % find which parameters have changed defaultValues(idx) = varargin(idx); % replace the changed ones [x1,x2,x3,x4] = defaultValues{:}; % convert from cell to var y = (x1+x2*x3+x4)^(1/n); end

Test:

>> myfcn(1) ans = 3.0028e+03 >> myfcn(1,2) ans = 3.0028e+03 >> myfcn(1,[],2) ans = 302.8500 >> myfcn(1,[],[],2) ans = 42.8500 >> myfcn(1,[],[],2) ans = 42.8500 >> myfcn(1,[],[],2,2) ans = 44