Script Files, Function Files and Inline Functions

Contents:

1. Editing files

2. Script M-files

3. Function M-files

4. Inline functionsMATLAB offers the possibility to store commands in special files - called M-files – with the ending .m. There are two types of M-files: Scripts and Functions. To edit an M-file, select ‘New’ or ‘Open’ from the file-menue. In each case the MATLAB Editor window will be opened and you can continue by editing either a new file or, after opening, an existing file. When the MATLAB Editor is open, you can load further files or save and close opened files by selecting the appropriate item from the file menue of the Editor. Select ‘Save As’ and the browser if you save a new file or if you want to change the name of an existing file, or ‘Save’ if you have edited an existing file whose name you want to leave unchanged. The directory in which the files should be saved is usually the working directory: in our case either the temp-directory or the chosen directory on your floppy.

2. Script M-filesIn a Script M-file you just write a sequence of commands separated by semicolons (result not displayed) or commas (result displayed). A Script M-file is treated as if the commands were written in the Command window. All variables defined in the workspace are accessed and the computations are carried out in the workspace.

Example:Assume you wish to multiply a complex number c by e^{i}^{q}and extract magnitude and polar angle of the product. If both c and q are defined in the workspace under the variable names c and theta, type the follwong commands into a file,product=c1*e^(i*theta);

magn=abs(product);phi=angle(product);save the file as product.m and call it at appropriate stages of the calculation. You then have access in the workspace to the variables magn and phi which are assigned to the computed values. For calling the Script M-file there are three options:

- If the file is opened in the MATLAB Editor select ‘Debug->Run’ from the Editor’s ‘Tools’-menue
- Type `product' and press the Enter key in the workspace
A Script M-file may contain an arbitrary number of commands. The advantage of using Script M-files is that you can repeat calculations easily whenever new data have been computed, and that it is easy to make changes.

Example:disp('Plotting the sine is fun');

fplot('sin(x)',[-2*pi,2*pi],'k');

hold on

fplot('sin(2*x)',[-2*pi,2*pi],'r');If this file is saved as sinescript.m and executed, you are informed that Plotting the sine is fun in the command window, and two sine curves in the interval -2p £ x £ 2p are plotted. Here the command hold on has the effect that previous plots in the figure window are kept when a new plotting command is exectuted. Type hold off if you want to clear the window for the next plot. The command fplot is reserved for Matlab functions which can be buildt in functions such as sine.m as well as user defined function M-files (see below). Note the apostrophes: the first argument passed to fplot is the filename and therefore must be a character string.

3. Function M-filesThese files differ from Script M-files in so far that the commands are not executed in the present workspace, but in a separate workspace which is created whenever the function is called. As a consequence, you have to transfer variables from your workspace to the function workspace and specify what has to be returned, i.e you have to specify input and output arguments.

The first (command) line of a Function M-file MUST be a function declaration line specifying input and ouput variables.Below this line any sequence of MATLAB commands can appear, in which the inputs are processed and the outputs should be defined. You have to make sure that no undefined variable occurs as input to these commands!

You can use Function M-files for programming in MATLAB as well as in the mathematical sense, i.e. for numerical implementation of formulae.

Example:Let’s start with a simple example, the (mathematical) function y(x)=x^{2}. To implement this function through a Function M-file, simply typefunction y=f(x)

y=x.^2;

in a file and save the file as square.m. In the workspace (or a Script M-file) you can then evaluate the function by

» square(2.1)

ans =

4.4100

or by square(varname) if varname is assigned to a numerical value. By writing .^ instead of just ^, the function is "array smart", i.e. one can pass arrays as argument as well. For example,

» square([1 2 3])

ans =

1 4 9

returns the array consisting of the squares of the the input array [1 2 3]. The command» fplot('square',[-1 1])

will generate a graph of y(x)=x

^{2}in the interval -1 £ x £ 1.Instead of the simple output above, one can perform any sequence of arithmetic operations which may also involve functions buildt into MATLAB or user defined functions.

Example:y(x)=[e^{-x}/(x^{2}+1) + sin^{2}(x)]^{2}+ 0.2 can be implemented array smart asfunction y=f(x)

u=exp(-x)./(x.^2+1);v=sin(x).^2;

w=u+v;y=w.^2+0.2;After saving the file as fun.m you can evaluate it again via fun(var) where var is either a number, an array, or a variable assigned to a numerical value or an array. Note that the variables u,v,w – defined internally in the function workspace – are not returned to your workspace.

A Function M-file can accept any kind of input variables, generate any desired type of output variables, and may contain any sequence of commands, including plots and control flow commands such as for, if else, while etc.

Example:In this example it will be demonstrated how to include symbolic expressions in a Function M-file. Suppose you performed some symbolic calculations which finally resulted in the expression.» y

y =

(1+a*x)^2/b/(1+x^2)

Now you may want to create a function M-file in which the symbolic expression is evaluated numerically for given values of x,a,b. To do this you can write

function y=f(x,a,b,y)

y=eval(y);y=y(x,a,b);

into a file and save the file as fun.m again. The function call

» fun(1.1,1,2.1,y)

ans =

0.9502

yields a numerical evaluation. In this application a symbolic variable (y) has been passed to the function workspace in addition to numerical values. Thus in the first command of the function M-file, the symbolic variable is evaluated through the ‘universal’ MATLAB command eval (this command evaluates ‘everything’ which can be evaluated). The second command evaluates the symbolic expression y at the given numerical values of the arguments. This Function M-file is, however, not array smart. To make it array smart, one has to include a loop:

function yout=f(u,a,b,y)

syms x;y=eval(y);yout=[];

for i=1:length(u)

yout=[yout subs(y,x,u(i))];

endIf this extended file is called, the first input argument can also be a linear array:

» fun([1.1 2 3],1,2.1,y)

ans =

0.9502 0.8571 0.7619

This example is at the boarderline between symbolic and numerical computations. You may wonder why to make the effort and associate a Function M-file to a computed symbolic expression if the function call is not much shorter than execution of the substitution command. The reason is that many MATLAB tools require Function M-files as input arguments.

Example:Suppose we want to find a numerical solution of the ODE du/dt=y(u,a,b) for given values of the parameters a,b and given initial condition u(t_{0})=u_{0}. The standard ODE solver of Matlab is ode45. This solver requires a Function M-file, in which the slopes are defined, as input argument. An array smart function is not needed for this purpose, but the syntax required by ode45 makes a slight modification of the previously used file necessary:function yout=f(t,u,FLAG,a,b,y)

syms x;y=eval(y);

yout=subs(y,x,u);If this file is again saved as fun.m, we can apply the command

[t u]=ode45('fun',[0.2 1],0.8,[],1,2.1,y);

to obtain a numerical solution of du/dt=y(u,1,2.1) with initial condition u(0.2)=0.8. The ode45 command yields 2 outputs: t and u. Both are arrays of the same lengths. The array t contains a set of (usually nonuniformly distributed) "time values" in the interval 0.2 £ t £ 1 (the terminal time has been set to 1), and in the array u the values of the approximated solution at these values are stored. The 'FLAG' in the input declaration line is necessary to distinguish between variables of the ODE (both the independent and the dependent variables must appear) and parameters - including the symbolic parameter y. You can plot the solution via the usual array-plot-command plot(t,u). The empty input [] passed to ode45 means that we use the default options provided by the solver (type help ode45 for details). If you want to evaluate fun.m numerically, you have to type, e.g., fun(1,1,'',1,2.1,y).

4. Inline FunctionsAn alternative to function M-files is provided by objects called inline functions. Inline functions are like function M-files, i.e. they accept (usually numerical) input and return output. The difference to function M-files is that the function evaluation takes place in the current workspace, whereas function M-files operate in separate workspaces.

Example:Let's define the function y(x)=(1+x)^{2}/(1+x^{2}) as inline function:» '(1+x).^2./(1+x.^2)'

ans =

(1+x).^2./(1+x.^2)

» y=inline(ans,'x')

y =

Inline function:

y(x) = (1+x).^2./(1+x.^2)In the first command the formula is edited as a string, i.e. it is quoted by apostrophes. In the second command the string is evaluated and converted to an inline function. With the third argument we fix the parameter of the inline function. Note that all arguments passed to inline must be strings. Since the answer of the first command is already a string, the apostrophes must be omitted in the argument ans, but the apostrophe quotation

mustbe used in the variable declaration 'x'. The above two commands can also be combined in the single command y=inline('(1+x).^2./(1+x.^2)','x'). The definition of the inline function was made array smart:» y(1),y([1 2 3])

ans =

2

ans =

2.0000 1.8000 1.6000

Inline functions can be exploited in a similar manner as Function M-files. Specifically we can apply the fplot command:

» fplot(y,[-1 1])

will generate a graph of the function in the range -1 £ x £ 1. Note that here y must not be quoted by apostrophes, in contrast to plots of functions defined in Function M-files.

Inline functions can depend on several arguments.

Example:Let's defined the function y(x,a,b) introduced symbolically in the previous section as inline function:» y=inline('(1+a*x).^2/b./(1+x.^2)','x','a','b')

y =

Inline function:

y(x,a,b) = (1+a*x).^2/b./(1+x.^2)This function is also array smart w.r.t. x (but not w.r.t. a,b):

» y([1 2],1,1)

ans =

2.0000 1.8000

The commands

» argnames(y),formula(y)

ans =

'x'

'a'

'b'

ans =

(1+a*x).^2/b./(1+x.^2)

provide information about the variables on which y depends and the formula through which y is defined.

With the command char (which extracts the character string of an expression) it is possible to convert symbolic expressions to inline functions and conversely.

Example:» y=inline('(1+a*x)^2/b/(1+x^2)','x','a','b');

» syms x a b;y=sym(char(y));diff(y)

ans =

2*(1+a*x)/b/(1+x^2)*a-2*(1+a*x)^2/b/(1+x^2)^2*x

» y=inline(char(y),'x','a','b');y(1,1,1)ans =

2

In the first command the inline function y(x,a,b) is defined as before, but not in an array smart manner because .^ cannot be used in a symbolic expression. In the 2nd command line first the necessary symbolic variables have been introduced, then the character string of the inline function is used to define a symbolic expression and (for demonstration purpose) differentiated. In the 3rd command line the character string of the symbolic expression is redefined as inline function and evaluated numerically.