Applied Numerical Methods Using MATLAB. Won Y. Yang

Чтение книги онлайн.

Читать онлайн книгу Applied Numerical Methods Using MATLAB - Won Y. Yang страница 27

Applied Numerical Methods Using MATLAB - Won Y. Yang

Скачать книгу

declared it as global, without being noticed by other related functions. Therefore, it is usual to declare only the constants as global and use long names (with all capital letters) as their names for easy identification.

       If some variables are declared as global and modified by several functions/routines, it is not easy to see the relationship and the interaction among the related functions in terms of the global variable. In other words, the program readability gets worse as the number of global variables and related functions increases.

      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.

      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.

      1 1.1 Creating a Data File and Retrieving/Plotting Data Saved in a Data FileUsing the MATLAB editor, make a script “nm01p01a.m” that lets its user input data pairs of heights (ft) and weights (lb) of as many persons as he wants till he presses <Enter> and save the whole data in the form of an N × 2 matrix into an ASCII data file ‘***.txt’ named by the user. If you have no idea how to compose such a script, you can permutate the statements in the box beneath to make your script. Store the script in the file named “nm01p01a.m” and run it to save the following data into the data file named ‘hw.txt’:%nm01p01a.m: input data pairs and save them into an ASCII data file k=0; while 1 end k=k+1; x(k,1)=h; h=input('Enter height:') x(k,2)=input('Enter weight:') if isempty(h), break; end cd('c:\MATLAB\nma') % to change current working directory filename=input('Enter filename(.txt):','s'); filename=[filename '.txt']; % String concatenation save(filename,'x','-ascii')Make a MATLAB script “nm01p01b.m” that reads (loads) the data file ‘hw.txt’ made in (a), plots the data as in Figure 1.1a in the upper‐left region of the screen divided into four regions like Figure 1.5 and plots the data in the form of PWL graph describing the relationship between the height%nm01p01b.m: to read the data file and plot the data cd('c:\MATLAB\nma') % to change current working directory weight=hw(I,2); load hw.txt clf subplot(221) plot(hw) subplot(222) axis([5 7 160 200]) plot(height,weight,'-+') [height,I]=sort(hw(:,1)); and the weight in the upper‐right region of the screen. Let each data pair be denoted by the symbol ‘+’ on the graph. Also let the ranges of height and weight be [5,7] and [160,200], respectively. If you have no idea, you can permutate the statements in the below box. Additionally, run the script to check if it works fine.

      2 1.2 Text Printout of Alphanumeric DataMake a MATLAB function ‘ max_array(A)’ that uses the ‘ max()’ command to find one of the maximum elements of a matrix A given as its input argument and uses the ‘ fprintf()’ command

Скачать книгу