Читать книгу Applied Numerical Methods Using MATLAB - Won Y. Yang - Страница 41
1.3.7 Adaptive Input Argument List
ОглавлениеA MATLAB function/routine is said to be ‘adaptive’ to users in terms of input arguments if it accepts different number/type of input arguments and makes a reasonable interpretation. For example, let us see the nonlinear equation solver ‘ Newton()
’ in Section 4.4. Its input argument list is
(f,df,x0,TolX,MaxIter)
where f
, df
, x0
, tol
, and MaxIter
denote the name of function (to be solved), the name of the derivative function, the initial guess (for solution), the error tolerance, and the maximum number of iterations, respectively. Suppose the user, not having the derivative function, tries to use the routine with just four input argument as follows:
>Newton(f,x0,tol,MaxIter)
At first, these four input arguments will be accepted as f
, df
, x0
, and tol
, respectively. But when the second line of the program body
if nargin==4&isnumeric(df), MaxIter=TolX; TolX=x0; x0=df; end
is executed, the routine will notice something wrong from that df
is not any function name but a number, and then interpret the input arguments as f
, x0
, tol
, and kmax
to the idea of the user. This allows the user to use the routine in two ways, depending on whether he is going to supply the routine with the derivative function or not. This scheme is conceptually quite similar to function overloading of C++, but C++ requires us to have several functions having the same name, with different argument list.