Department of Chemical Engineering
MATLAB Tutorial
 

Function m-files                                                                                             (last updated  9/9/99)

The information in this tutorial is located in either Section 5.14 of the MATLAB manual.  .

The Student Edition of MATLAB, Version 5, The MATH WORKS Inc. Prentice-Hall, 1997.

======================================================================================

This tutorial includes the following sections;

Introduction

Creating Function m-files

Example Problem
 
======================================================================================

Introduction

Function m-files are used to calculate a value of an dependent variable or variables, at specified values of independent variables. 

You may have noticed that when you use the built-in MATLAB functions, such as 'sum' or 'sin', you don't see the specific MATLAB commands that are executed and any variables used internally by the function are not recognized by the Command Window. We can take advantage of this feature to perform calculations or sequences of commands that appear often in working a larger problem. We do this by creating our own functions.

Functions are created in an m-file using the MATLAB Editor, just like a script m-file. The major difference between a script m-file and a function m-file lies in the interaction between the m-file and the Command Window. Remember a script m-files was able to see all variables in the Command Window, and all variables created in the m-file were able to be seen by the Command Window. A function m-file interacts with the Command Window only through its input and output. Intermediate variables that are not passed to or from the function cannot be accessed by the Command Window.
 
======================================================================================

Creating Function m-files

A function is going to accept input that you control, and return output values that you request.

The structure of a function file must be as follows:

(1)    The first executable line of the file must begin with the word function. This is followed by the output arguments. If more than one variable is to be returned they must be in an array (square brackets). This is followed by an equal sign, and the name of the function with the input arguments in parentheses.

function [output1 output2 etc.] = function_name(input1, input2, etc)

The input and output argument names can be the same or different from those used in the command which calls the function. In either case they are merely matched up by location in the input argument list and the output array.

(2)    After the first executable line any comments, variable definitions etc. should be listed. These comments will be displayed when you type >> help function_name at the MATLAB prompt.

(3)    The commands which perform the calculations.

______________________________________________________________________________________________________________________

To emphasize this difference between the way that script m-files and function m-files interact with the computer memory, compare the script and function m-files below.

Create a script m-file by and enter the following commands.
_________________________________________________________________________________________________

a1 = 2 + x1;
y1 = a1^2.5;
__________________________________________________________________________________________________

Save the m-file with the name test1.m

Return to the Command Window and enter the following;

>> x1 = 2;
>> test1    %      This executes the m-file.

Now request the values of y1 and a1 stored in the Command Window memory.
>> y1
y1 =
         32

>> a1
a1 =
      4

Note that a1 has a value stored in the Command Window memory.  
__________________________________________________________________________________________________

Now create a function m-file and enter the following commands.
__________________________________________________________________________________________________

function y2 = test2(x2)
a2 = 2 + x2;
y2 = a2^2.5;
__________________________________________________________________________________________________

Save the m-file with the name test2.m

The name 'test2' in the first line and the m-file name can be different. When you call the function from the Command Window you must use the m-file name. It is best to use the same name to avoid the possible confusion.

Return to the Command Window and enter the following;

>> x2 = 2;
>> y2 = test2(x2);         %   This executes the function file with the current value of x2.
>> y2
y2 =
        32
>> a2
??? Undefined function or variable a2.

Note that the workspace can't recognize a2 because it's an intermediate variable in a function m-file.

======================================================================================

Example Problem

This example calculates the specific and total enthalpy changes for a stream of methane gas. The values of the inlet and outlet temperature and the molar flowrate are set in the script m-file, methane .m, shown here. It calls function m-file, enthalpy.m. Note that the variable names used to call the function are different from those inside the function. Also note in the calling file and the function file that multiple input argument are being passed to enthalpy.m and multiple output arguments are being returned from the function.

______________________________________________________________________________________________________________________

Here is the script m-file that calls the function file.
_________________________________________________________________________________________________________________________

%     Darin Ridgway
%     Chemical Engineering

%    Last updated July 6, 1998

%    This m-file, methane.m, calculates the specific and
%    total enthalpy change for a stream of methane gas
%    for four different stream conditions of temperature and
%    flowrate. It calls function m-file, enthalpy.m, to
%    perform the calculation.

% Define the inlet and outlet temperatures in degrees C

Tin = [ 100 400 40 150 ];
Tout = [ 200 150 320 240 ];
 
% Define the flowrates in moles per second

mol_flow = [ 3.5 1.2 2.7 8.6 ];
 
% Write a loop to call the function for each of the 4 cases. The returned values are stored in an
% array.

for n = 1:4
     [specH_CH4(n),totalH_CH4(n)] = enthalpy(Tin(n),Tout(n),mol_flow(n));
end
 
%    Create a table displaying the output

fprintf('\n Inlet T Outlet T molar flow specific H total H \n')
fprintf(' C C mol/s W W\n\n')

for n = 1:4
     fprintf(' %3.0f %3.0f %3.1f %5.2e %5.2e \n',...
    Tin(n), Tout(n), mol_flow(n), specH_CH4(n), totalH_CH4(n))
end
_______________________________________________________________________________________________

Here is the function file called enthalpy.m.  It is called by the script file methane.m above
______________________________________________________________________________________________________________________

%     Darin Ridgway
%     Chemical Engineering

%    Last updated July 7, 1998

function [ specH, delH ] = enthalpy( Tin, Tout, molar_flow )

% This function file calculates the specific and total enthalpy
% changes for methane gas in watts, given inlet and outlet

% temperatures in degrees Celcius, and the flow rate in moles
% per second.
 
% The constants in the heat capacity formula

a = 34.31;
b = 0.05469;
c = 0.3661e-5;
d = -11.00e-9;
 
specH = a*(Tout - Tin) + b*(Tout^2 - Tin^2) + c*(Tout^3 - Tin^3) + d*(Tout^4 - Tin^4);
delH = molar_flow * specH;
______________________________________________________________________________________________________________________

The output in the Command Window looks like this;
______________________________________________________________________________________________________________________

>> methane

Inlet T    Outlet T     molar flow    specific H       total H
   C            C              mol/s             W                W

 100        200              3.5         5.08e+003    1.78e+004
 400       150               1.2        -1.60e+004  -1.93e+004
  40        320               2.7         1.51e+004    4.08e+004
 150       240              8.6          5.01e+003    4.31e+004