1. Creating and importing program and data files
  2. Pauses
  3. "For-loops"
  4. Creating and using your own functions

  1. Creating and importing your own program or data file.

    Use a text editor to create an "m-file", e.g. "program1.m" in which you have typed the instructions, and data, exactly as you would do at the MATLAB command line.Invoke the program by typing the name without the extension:

    >> program1

    [Note: Do not start file names with numbers, e.g. 1program.m is not a valid name.]

  2. Pauses

    To have a program pause until return is pushed: pause
    To have a program pause for 10 seconds: pause(10)

  3. "For-loops"

    for n = 1 : 5

    [Note: MATLAB is most efficient when working with vectors (or matrices). Thus whenever possible work with vectorsinstead of using loops. See Section II.1, example 1 for theconciseness and power of the vector approach.]

  4. Creating and using your own functions

    Create the file trans1.m which starts off with:
    function NEW = trans1(OLD)

    To evaluate a function at the variable A:

    >> B = trans1(A).

    [Note: For function names, as well as for the variables, do not use the names of MATLAB functions e.g. det..

    Note: In certain versions you can use capital letters for your functions; e.g. in Section II.3, R( ) is defined to be equal to the MATLAB function sqrt( ).]


  1. Creating and importing your own program or data file.

    Instead of typing in commands at the MATLAB prompt it is often preferable to create a program file which contains the instructions and then call up the program. This is particularly handy when we have several steps to perform in our computation or when we want to perform other calculations which are modifications of a previous one. It makes corrections much simpler and avoids a great deal of frustration caused by typing and other simple errors. When the amount of data to be used in a program is small, as in program.1 of example 1, then the program file will contain both data and instructions. Some files contain just data and are then called up in another program file or via a function (see iv). As far as MATLAB is concerned there is no distinction between a program file and a data file. In both cases we create an "m-file" or "*.m file". If we have two large sets of data that we want to analyse we might put them into two files data1.m and data2.m. In our program file we would then change the call-up portion of the file from data1.m to data2.m. The use of a file that just contains data and is called up by a program is shown in example 2. If we are going to analyse many sets of data, we may prefer to write a function (see iv).

    Program vs. function. The main difference between a program and a function, is that with a program all the variables become MATLAB variables (they are listed when we type whos - Section I.1, viii) that can be used later on. For a function only the designated dependent variables become MATLAB variables. This distinction often helps us to decide if we want to write a program or a function.

    To write a program or data file we simply use a text editor (to create a pure ASCII file) and type in the instructions and the data. When naming the file, the name portion is arbitrary (except that it must start with a letter and not a number), but the extension must be "m", e.g. program1.m. To call the program one types the name, e.g. program1 of the file, without the extension. Large data sets, saving data and loading data are discussed in more detail in section I.4.

    WARNING: Do not use the name of a MATLAB function for your variables because MATLAB will think that you are trying to evaluate the function and forgot the ( ). Thus since det( ) is a built in MATLAB function, if you want to designate the determinant of your output matrix, call it "deter" or "d", but not "det"!

  2. Including a pause in a program.

    Example 1 also illustrates the use of pause. When there are many variables the earlier ones will be "gone" before we have had the time to read and check them. So we put either pause in which case MATLAB waits until you push ENTER (or any key), or pause(10 ) in which case MATLAB automatically resumes after 10 seconds.

    Example 1. I used a text editor to type the following program prog1.m which contains some data and a sequence of commands to manipulate this data. Note that we can leave a space between lines and put in comments using %.

  3. Program 1


    % [prog1.m]  
    C = [1 2 3 ; 4 5 6]  
    % data
    ra_C =rank(C)  
    % find the rank
    ech_C = rref(C)  
    % reduced row echelon form

    I invoke the program with the command prog1; this loads the variable "C" and then invokes functions which find the rank and reduce the matrix to row echelon form are invoked. The output is assigned to the variables "ra_C" and "ech_C".

    >> prog1 % no extension
    C = % MATLAB prints C
    1 2 3
    4 5 6

    MATLAB pauses for 10 seconds

    ra_C = 2

    MATLAB pauses until enter is pushed

    ech_C =

    1 0 -1
    0 1 2

    [Note: In this program the matrix C is automatically printed. For large matrices we may want to suppress printing. To do so wewould place a semicolon after the matrix (see Section I.2,vi.)

    >> C = [1 2 3 ; 4 5 6]; % data

    If we needed to see C we would use disp( ); see Section I.5,i:

    >> disp(C) ]

    Instead of placing the data inside the program we can also place it in a data file data1.m as follows:

    Program 2

    % [data1.m] contains only data
    C = = [1 2 3 ; 4 5 6] % data

    We now modify prog.1 so that it calls up the data file data1.m.

    Program 3


    % [prog1b.m]
    data1 % calls up data file [data1.m]
    ra_C = rank(C) % find the rank
    ech_C = rref(C) % reduced row echelon form

    We now call up prog1b:

    >> prog1b

    C =

    1 2 3
    4 5 6

    ra_C = 2

    ech_C =

    1 0 -1
    0 1 2

    When we type whos (Section I.1, viii) to find out what our variables are we see that all variables that appear in prog1b are there

    >> whos

    Name Size Total Complex
    C 2by 3 6 No
    ech_C 2 by 3 6 No
    ra_C 1 by 1 1 No


  4. "for-loops".

    Often we want to repeat an operation many times and instead of constantly recomputing individual quantities we can use a "for-loop". This consists of a statement of the form:

    for n = 1 : 5

    instructions to do something


    Note that for and end are in lower case letters.

    Loops are normally created in "m-files" and then called up in MATLAB, although simple ones can be typed in at the prompt. It is suggested that neither i nor j be used for indices since these are also used for imaginary numbers (section II.3.iii) and confusion in reading the program might result.

    Example 2. We have a recursive relationship of the form:

    nk = Pk * n0 ,

    where P is a square matrix and nk and n0 are column vectors. To compute nk, for a sequece of values of k, we create the m-file called power1.m which contains P, n0 and a "for-loop":

    Program 4

    % [power1.m] compute powers.

    % enter initial vector and take the transpose; since the elements are % real we can use '.

    n_0 = [2 3]'

    P = [.2 .6 ; .4 .3] % enter the matrix;

    %loop starts
    for n = 1 : 3

  5. u = P^n * n_0

    We call up power1.m by typing power1 without the extension *.m . Notice how for each loop the variable u changes its value and is printed out.

    >> power1

    n_0 =


    P =

      0.2000 0.6000
      0.4000 0.3000

    u =


    u =



    u =


    In the above loop we could have indicated the subscript by adding the index n in the loop:

    Program 5

    % [program3.m] have the program print the value of n

    for n = 1:3

    u = P^n * n_0


    A nicer output can be obtained by suppressing printing using ; and then using disp(n) , disp(u); see section I.5.

    Program 6

    % [program3.m]suppress "n = " and use disp(n)
    for n = 1:3


    % suppress printing n

    u = P^n * n_0;

    % suppress printing u
    disp(n), disp(u)


  6. Creating and using your own functions.
Programs perform a sequence of operations on one set of data. When the same operations are going to be performed over and over it is preferable to define a function. To create a new function we create an "m-file" whose name (without the ".m") is exactly the same as the function. Thus if we want to define a function "trans1( )" we have to create a file "trans1.m"

The first statement - not including comments which start with % - in trans1.m must start off with the word function so that MATLAB knows that it is not dealing with a simple sequence of commands and data as in subsection i. The word function is followed by the statement that defines the dependent variable(s) as trans1( ) of the independent variables. The function name should be written in lower case letters (some older versions will accept upper case). Thus in the file "trans1.m" we start off with:

function NEW = trans1(OLD)

In this case we have one dependent variable, called NEW and one independent variable called OLD, but MATLAB functions can have several dependent and several independent variables as will be seen in the examples below. These variables are all internal variables, i.e. they will not appear directly in the list of MATLAB variables that we obtain when we type whos; see Example 3 for a further discussion of this.

WARNING (second time in this section): Do not use the name of a MATLAB function for your variables because MATLAB will think that you are trying to evaluate the function and forgot the ( ). Thus since det( ) is a built in MATLAB function, if you want to designate the determinant of your output matrix, call it "deter" or "d", but not "det"!

Once the name of the function and symbols for the dependent and independent variables have been decided the next step is to give an algorithm which relates the variables:

Example 3. We have a fixed matrix F = [-2 2 ; 3 1] and we want to take various 2 x 2 matrices, square them and then add F. The function program would be:

Program 7


    % [trans1.m]
    function NEW = trans1(OLD)
    F = [-2 2; 3 1]; % suppress printing
    % give the formula. add ; to avoid printing twice
    NEW = (OLD)^2 + F;

To use this function we have to assign a variable name to the independent variable that whose functional value we are going evaluate. We do not have to use OLD as in the program and can use any variable name, e.g. A:

>> A = [1 2; 3 4];

Next, we a assign a variable name, e.g. B, to the value of the function (we do not have to use the name NEW) as follows

>> B = trans1(A)

B =

5 12
18 23

It is preferable, but not necessary, to assign a variable to the value of the function. If we do not then the value is assigned to the variable ans as follows:

>> trans1(A)

ans =

    5 12
    18 23

Internal variables. Note that in the function trans1.m the variables OLD, NEW, F are variables which are internal to the function; they will not appear when we type whos (Section I.1, viii). Sometimes we do not want to keep a quantity as a MATLAB variable, but we want to print out the value, perhaps as a check when we run the program. The quantities can also be introduced as internal variables as shown in the next example:

Example 4.. Suppose that as we go along in the above calculation we want to check the determinant of A to make sure that it is non-zero:

Program 8

% [trans2.m]
% prints out determinant as part of function call
function NEW = trans2(OLD)
F = [-2 2; 3 1]; % suppress printing
det_check = det(OLD) % do not suppress printing!!
% alternative method of printing out the value
NEW = (OLD)^2 + F;

We run the program and then type whos:

>> B = trans2(A)

det_check = -101

B =

5 12
18 23

>> whos

2 by 2
2 by 2

Note that the quantity det_check has been printed out, but does not appear as a variable. The value of det_check was printed out because we did not put a semicolon. An alternative method, as shown in the program, is to use the disp function. The value assigned to NEW by the function is listed under the variable B.

Functions of several independent variables. MATLAB functions can also be functions of several independent variables. Suppose that instead of a fixed adder in example 3, we want to have a variable adder. We simply include the adder as a variable in the defined function as in the following example:

Example 5.

Program 9

% [trans3.m] - illustrates a function of two variables

function NEW = trans3(OLD, ADDER)

NEW = (OLD)^2 + ADDER; % give the formula do not print out.

To use this function we need to define the adder, using any symbol:

>> C = [1 -2; 0 1]

We designate the dependent variable as D:

>> D = trans3(A , C)

8 8
15 23

Several dependent variables. In calculus a true function can only have one dependent variable, but a MATLAB function can compute and store several variables. For the function trans2( ) in example 4, we computed the determinant of the input matrix as we went along and even had the value printed out, but we did not assign a variable name to it. As we saw in example 4 the quantity does not appear in the "whos" list and thus cannot be used again. If we want to save the quantity as a variable then we proceed as in the following example:

Example 6. Suppose that in example 5 we had wanted to compute the rank of the output matrix, and also to assign a variable name to it. In this case, there are two dependent variables, which we designate as NEW and rank_new. We place both of these variable names inside square brackets on the first line of the m-program. Note that the two variables do not need to have the same dimensions, i.e. we are not forming a true matrix:

Program 10

% [trans4.m] - illustrates a multi-variable output
% modification of program 5

function [NEW, rank_new] = trans4(OLD)

F = [-2 2; 3 1]; %suppress printing

NEW =(OLD)^2 + F; % give the formula do not print out.

rank_new = rank(NEW);

At the MATLAB prompt we define our dependent variables. In this case we will assign the function value NEW to a variable whose name is also NEW. We assign the function value rank_new to a variable whose name is different namely lin_ind.

>> [NEW, lin_ind] = trans4(A) % A was entered above.


5 12
18 23

lin_ind =


If we had just written:

>> Z = trans4(A)

then the value of Z would be that of the first of the variables (NEW) and the second variable lin_ind would not have appeared.

No independent variables. It is possible to define a function with no independent variables. In the following example we use the input function, which is discussed in I.4, to obtain that value we use in the computation.

Program 11

% [squa_it.m] - a function with zero variables

function c = squa_it;

N = input(' what is N? ');
c = N^2;

We could have obtained exactly the same value for c if we had not put in the function statement, in which case we would have had an ordinary MATLAB program. In the function format only c becomes a MATLAB variable, whereas with the program format both N and C become variables that can be used later on.

Functions with one or several dependent variables. For some built-in MATLAB functions there is the possibility of assigning either one or two dependent variables. An example of this is the function eig( ) which is discussed in detail in sections I.3.1 and III.2. If we type:

>> EIG_VAL = eig(A)

then we will obtain a diagonal matrix whose diagonal elements are the eigenvalues of A. But if we type:

>> [EIG_VEC , EIG_VAL] = eig(A)

we obtain two matrices, the first one having the eigenvectors of A stored as columns and the second again being a diagonal matrix whose diagonal elements are the eigenvalues of A.


Back to Table of Contents

Web Site Training provided by Kathryn Charis Apunen Washburn summer 2001