M-files

It is possible to extend MATLAB by adding your own programs. MATLAB programs are all given the extension .m and are referred to as M-files. There are two basic types of M-files.

Script Files

Script files are files that contain a series of MATLAB commands. All the variables used in these commands are global, and consequently the values of these variables in your MATLAB session will change every time you run the script file. For example, if you wanted to determine the nullity of a matrix, you could create a script file nullity.m containing the following commands:

[m,n]=size(A)nuldim=nrank(A)

Entering the command nullity would cause the two lines of code in the script file to be executed. The disadvantage of determining the nullity this way is that the matrix must be named A. Additionally, if you have been using the variables m and n, the values of these variables will be reassigned when you run the script file. An alternative would be to create a function file.

Function Files

Function files begin with a function declaration statement of the form

function[oargl,,oargj]=fname(inarg1,,inargk)

All the variables used in the function M-file are local. When you call a function file, only the values of the output variables will change in your MATLAB session. For example, we could create a function file nullity.m to compute the nullity of a matrix as follows:

function k=nullity(A)% The command nullity(A) computes the dimension%   of the nullspace of A.[m,n]=size(A);k=nrank(A);

The lines beginning with % are comments that are not executed. These lines will be displayed whenever you type help nullity in a MATLAB session. Once the function is saved, it can be used in a MATLAB session in the same way that we use built-in MATLAB functions. For example, if we set

B=[1 2 3;4 5 6;7 8 9];

and then enter the command

n=nullity(B)

MATLAB will return the answer: n=1.

The MATLAB Path

The M-files that you develop should be kept in folders that can be added to the default MATLAB path—the list of folders where MATLAB will automatically search for Mfiles. To add or remove a folder from the MATLAB path or to reorder the folders in the path, select the home tab at the top of the page and then click on the Set Path option.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.82.79