Aqua Phoenix
     >>  Lectures >>  Matlab 4  
 

Navigator
   
 
       
   

4.3 m-files and Functions

We have thus far used m-files for aggregating expressions and evaluating them all by executing the m-file. However, m-files serve another more important purpose: they are used to define functions in Matlab. We have already been using several functions, such as imread, wavplay, rand, etc., all of which are by default present in Matlab and have been added to the Matlab package by MathWorks, the company that develops Matlab.

A function is formally defined as something that takes one or more arguments, computes something based on those arguments, and returns a value. In the case of imread, the argument is an image file name and the return value is the raw image data stored in a matrix. We can assume that the function body involves opening the file, reading the file's contents, and creating and populating the image matrix.

The reason for using functions is to break down a large problem into smaller re-usable pieces. For example, displaying an image is done in two steps: imread and image. These are in fact long functions that do a lot of processing. If we had to write out the contents of these two functions everytime we intend to display an image in Matlab, we would not only be exhausted from writing, but we would also have a messy m-file. Typing in two function calls is much simpler. Moreover, loading an image and displaying an image are so commonly used that it makes sense to put these two actions into re-usable functions for everyone to enjoy!

Figure 4.6 outlines all of the parts of a simple function. A function is defined in an m-file with the function keyword on the first line. The remainder of the first line is the function declaration which is similar to a mathematical function, e.g. z = f(x, y). z is the return variable, i.e. the variable that holds the final value of the function. x and y are arguments passed to the function from the Matlab Command Window. f is the name of the function, which must be reflected in the m-file's name. This function f, for example, must be stored in an m-file by the name of f.m .

Immediately following the first line of a function is a series of comments. A comment is a line of text that is not executed, but instead serves as a note. Comment lines must begin with the percent symbol %. When typing into the Command Window 'help rand', it is these commented lines after the function declaration that are printed. It is good practice to use comments so that someone who intends to use your Matlab function may read about the usage of your function.

The actual computation of values takes place in the body of the function. The return value of the function (z in this case) must appear somewhere near the end of the body where it is assigned to the final value of the function. It is this value that is returned to the Command Window as the function's result.

Figure 4.7 shows the flow of a function's execution. This flow corresponds to the previous discussion of a function's logical setup.

Figure 4.6
Figure 4.7
For an example of a function that will be used in later exercises and assignments, we will create a function that converts velocity from kilometers per hour to meters per second: function v_kmh2msec Make sure that that the Current Directory points to a directory in your account, which you can use to store all Matlab related functions, exercises, and assignments.

Note: The output from every line of code in an m-file tends to be suppressed with a semicolon, unless the programmer intends to do debugging (find programming errors). The reason for this practice is that once the function is called, none of the contents is displayed in the Command Window.

To create a new m-file, select File -> New -> m-file. This will bring up an empty Text File Editor.

Figure 4.8
Click image to enlarge, or click here to open
We begin our function with the function declaration:

function v = v_kmh2msec(kmh)

Figure 4.9
Click image to enlarge, or click here to open
We continue by including a few comments that describe the purpose and usage of this function:

% V_KMH2MSEC kilometers per hour
% V_KMH2MSEC(KMH) converts
% kilometers per hour KMH to
% meters per second

Figure 4.10
Click image to enlarge, or click here to open
It is good programming practice to do some form of error checking. A useful function to include is nargchk, which checks the number of arguments passed to the function. Function nargchk takes 3 arguments:
  1. smallest number of valid arguments
  2. largest number of arguments
  3. the actual number of passed arguments, denoted by the built-in variable nargin (number of arguments passed into the function)

Function nargchk is further passed to function error which displays an actual error message.

If our function required 3 arguments, the function call would look as follows: error(nargchk(3, 3, nargin)) If our function required either 2 or 3 arguments, the function call would look as follows: error(nargchk(2, 3, nargin)) In the case of kmh2msec, we require at least 1 and at most one argument, making the function call: error(nargchk(1, 1, nargin))

Figure 4.11
Click image to enlarge, or click here to open
Finally, the main body of the function contains the conversion from km/h to m/sec:

kmh * 1000 / 60 / 60

Figure 4.12
Click image to enlarge, or click here to open
Save the m-file from the File -> Save menu, and name it after the function name, v_kmh2msec

Figure 4.13
Click image to enlarge, or click here to open
In the Command Windows, we can finally try out the function:

v_kmh2msec(1) returns a valid number, 0.2778

v_kmh2msec() returns an error message, as there are not enough number of arguments

v_kmh2msec(1, 2) returns an error message, as the number of arguments exceed the requirement

help v_kmh2msec returns the lines of comments immediately after the function declaration. The help command can be used on every built-in function, and every other function that features help comments.

v_kmh2msec(-10) returns a valid mathematical number, but is physically impossible. We should build the function so that negative numbers are not converted.

Figure 4.14
Click image to enlarge, or click here to open
To edit the m-file, click on the tab Current Directory in the Workspace window, then right-click on the function v_kmh2msec and select Open as Text, or simply double-click on the entry.

Figure 4.15
Click image to enlarge, or click here to open
We will modify the code to include a standard if-then-else statement. In the if clause, we will check whether the passed argument of kmh is negative. The successive then clause defines the result, in case the argument is negative. The successive else clause defines the result, in case the argument is positive:

if (kmh < 0)
  v = 0;
else
  v = kmh * 1000 / 60 / 60;
end
Depending on whether or not the argument is 0, the result v is either set to 0 or the actual conversion.

Save the m-file.

Figure 4.16
Click image to enlarge, or click here to open
We now test the function again with a negative argument, and find a realistic result for negative inputs.

Figure 4.17
Click image to enlarge, or click here to open