Читать книгу Applied Numerical Methods Using MATLAB - Won Y. Yang - Страница 40

1.3.6 Parameter Passing Through VARARGIN

Оглавление

In this section, we see two kinds of routines that get a function name (string) with its parameters as its input argument and play with the function.

First, let us look over the routine ‘ ez_plot1()’, which gets a function name ( ftn), its parameters ( p), and the lower/upper bounds ( bounds=[b1 b2]) of horizontal axis as its first, third, and second input arguments, respectively, and plots the graph of the given function over the interval set by the bounds. Since the given function may or may not have its parameter, the two cases are determined and processed by the number of input arguments (nargin) in the if‐else‐end block.

%plot_sinc1.m D=1; b1=-2; b2=2; t=b1+[0:100]/100*(b2-b1); bounds=[b1 b2]; subplot(223), ez_plot1('sinc1',bounds,D) axis([b1 b2 -0.4 1.2]) subplot(224), ez_plot('sinc1',bounds,D) axis([b1 b2 -0.4 1.2])

function <b>ez_plot1</b><![CDATA[(ftn,bounds,p) b1=bounds(1); b2=bounds(2); t=b1+[0:100]/100*(b2-b1); if nargin<=2, x=feval(ftn,t); else x=feval(ftn,t,p); end plot(t,x) function <b>ez_plot</b><![CDATA[(ftn,bounds,varargin) b1=bounds(1); b2=bounds(2); t=b1+[0:100]/100*(b2-b1); x=feval(ftn,t,varargin{:}); plot(t,x)

Now, let us see the routine ‘ ez_plot()’, which does the same plotting job as ‘ ez_plot1()’. Note that it has a MATLAB keyword varargin (variable length argument list) as its last input argument and passes it into the MATLAB built‐in function ‘ feval()’ as its last input argument. Since varargin can represent comma‐separated multiple parameters including expression/strings, it paves the high‐way for passing the parameters in relays. As the number of parameters increases, it becomes much more convenient to use varargin for passing the parameters than to deal with the parameters one‐by‐one as in ‘ ez_plot1()’. This technique will be widely used later in Chapter 4 (Nonlinear Equations), Chapter 5 (on numerical differentiation/integration), Chapter 6 (Ordinary Differential Equations), and Chapter 7 (Optimization).

1 (cf) Note that MATLAB has a built‐in graphic function ‘ ezplot()’, which is much more powerful and convenient to use than ‘ ez_plot()’. You can type ‘ help ezplot’ to see its function and usage.

Applied Numerical Methods Using MATLAB

Подняться наверх