A script is simply a collection of Matlab commands in an m-file (a
text file whose name ends in the extension ``.m'').
Upon typing the name of the file
(without the extension), those commands are executed as if they
had been entered at the keyboard. The m-file must be located in
one of the directories in which Matlab automatically looks for m-files;
a list of these directories can be obtained by the command `path`.
(See `help path` to learn how to add a directory to this list.)
One of the directories in which Matlab always looks is the *current
working directory*; the command `cd` identifies the current
working directory, and `cd newdir` changes the working directory
to `newdir`.

For example, suppose that plotsin.m contains the lines

x = 0:2*pi/N:2*pi; y = sin(w*x); plot(x,y)Then the sequence of commands

>> N=100;w=5; >> plotsinproduces Figure 4.

As this example shows, the commands in the script can refer to the
variables already defined in Matlab, which are said to be in the global
workspace (notice the reference to `N` and `w` in plotsin.m).
As I mentioned above, the commands in the script are executed exactly as if
they had been typed at the keyboard.

Much more powerful than scripts are functions, which allow the user to create new Matlab commands. A function is defined in an m-file that begins with a line of the following form:

The rest of the m-file consists of ordinary Matlab commands computing the values of the outputs and performing other desired actions. It is important to note that when a function is invoked, Matlab creates a local workspace. The commands in the function cannot refer to variables from the global (interactive) workspace unless they are passed as inputs. By the same token, variables created as the function executes are erased when the execution of the function ends, unless they are passed back as outputs.function [output1,output2,...] = cmd_name(input1,input2,...)

Here is a simple example of a function; it computes the function
. The following commands should be stored in the file
`fcn.m`

(the name of the function within Matlab is the name of the
m-file, without the extension):

function y = fcn(x) y = sin(x.^2);(Note that I used the vectorized operator

`.^`

so that the function
>> x = (-pi:2*pi/100:pi)'; >> y = sin(x); >> z = fcn(x); >> plot(x,y,x,z) >> gridThe graph is shown in Figure 5. Notice how

**Figure 5:** Two curves graphed together

Wed Sep 8 10:44:13 EDT 1999