Go to CCP Homepage Go to Materials Page Go to Engineering Mathematics Materials Go to Table of Contents
Go Back One Page Go Forward One Page

MATLAB Tutor

Part 6: M-Files and User-defined Functions

A good way to "automatically" execute a sequence of often-used commands without having to go to the trouble of typing them in each time is to use an m-file. An m-file is a plain text file that you can create with any text editor. In it, you can put the same kind of commands that you type in at a MATLAB prompt.

Typing the m-file's name at a prompt simply successively executes the commands in the file. It is just as if you had typed them in at individual MATLAB prompts.

  1. Use a text editor to create a file that contains the following lines. Save the file in your working directory under the name tester.m.

    d2r = pi/180
    a = sin(30*d2r)
    b = (1 + a)/4

  2. In MATLAB, at the prompt, enter

    tester

There will be occasions when you will need to define your own specialized functions which are not built into MATLAB. You do this by using a special kind of "function" m-file. As with standard functions like sin(x), a function m-file accepts input arguments and returns outputs.

An example function m-file is given below. It accepts the input argument x and returns y = fun(x). Note that the first line contains the key word "function" and describes inputs and outputs. The output value must be assigned within the "program" to the variable y which appears before the equals sign on the first line of the file. The m-file must be given the same name as the function, namely fun.m.

  1. Use a text editor to create a file that contains the following lines. Save in your working directory under name fun.m.

    function y = fun(x)
    d2r = pi/180 ;
    y = 3*cos(x*d2r) - 1 ;

  2. In MATLAB, at the prompt, enter

    fun(45)

  3. Enter

    z = 30
    a = fun(z)+ 8

User-defined functions can be plotted as easily as built-in ones. We will use the plot commands we learned in Part 5 of this Tutorial.

  1. Enter

    x = -10: 0.5: 20;
    y = fun(x);
    plot(x, y)

  2. Enter

    fplot('fun(x)', [- 10, 20], '-o')

You can define functions that take inputs of more than one variable. Output can likewise be more than one variable. Both input and output variables can be vectors.


Go to CCP Homepage Go to Materials Page Go to Engineering Mathematics Materials Go to Table of Contents
Go Back One Page Go Forward One Page


| CCP Home | Materials | Engineering Mathematics | Module Contents | Back | Forward |

modules at math.duke.edu Copyright CCP and the author(s), 2000