NMM Chapter 3: Programming in Matlab: 10.10 Introduction To Chemical Engineering
NMM Chapter 3: Programming in Matlab: 10.10 Introduction To Chemical Engineering
When you use “sin” or “log” or “exp” in Matlab you are using “function m-files”. They
are different from “script m-files” primarily because they have inputs and outputs. To
specify which variables in the m-file are the inputs, and which are the outputs, the first
line of the m-file should be in this form:
function output=function_name(input)
For example, an m-file that begins with the line:
function L=vec_length(V)
takes a column vector V as its input, and returns its length L as its output. Here is the
complete file vec_length.m :
function L=vec_length(V)
% returns the length of column vector V
L=sqrt(V' * V); % square root of the dot product of V with itself
You would invoke on the command line this way:
>> W=[1; 2; -3]
>>Length_of_W=vec_length(W)
Several more examples are given in NMM 3.2, and on the 10.10 Web page. We
recommend you make the name of the function given on the first line match the file name
of the m-file, i.e. function vec_length is in file vec_length.m, not in sillyname.m
We also recommend you put only one function in each m-file (though under some
circumstances it is allowed to group a set of functions together into a single m-file.) If
you store all your m-files in the same directory, any function can call any other function.
If you get a message saying that Matlab cannot find your m-file, on the command line
type
>> pwd
to make sure Matlab is looking in the correct folder, and then
>> dir
or
>> ls
to make sure that the m-file is really in that folder. You may have accidentally saved it in
the wrong folder.
Functions can have any number of inputs and outputs. Here is an example with three
inputs and three outputs:
function [x,y,z]=Spherical_to_Cartesian(r,theta,phi)
% converts from (r,theta,phi) to (x,y,z) assuming theta and phi in radians.
%x,y,z will have the same units as r
% last revised by W.H. Green, Aug. 22, 2002
z=r*cos(theta);
x=r*sin(theta)*cos(phi);
y=r*sin(theta)*sin(phi);
% Sample input/output:
%>> r=2; theta=(pi/2); phi=pi;
%>> [x,y,z]=Spherical_to_Cartesian(r,theta,phi);
%>> x
%
%x =
%
%-2
% >> y
%
%y =
%
%2.4493e-016
%
% >> z
%
%z =
%
%1.2246e-016
(Note that in exact math, y=z=0, but roundoff errors cause them to take these very small
nonzero values. We discuss this more below.) If you want, you can lump variables
together into arrays, e.g.
function V=Spherical_to_Cartesian_Vector(r,theta,phi)
% converts from (r,theta,phi) to V=[x;y;z] assuming theta and phi in radians.
%Components of V will have the same units as r
% last revised by W.H. Green, Aug. 22, 2002
z=r*cos(theta);
x=r*sin(theta)*cos(phi);
y=r*sin(theta)*sin(phi);
V=[x;y;z];
% Sample input/output:
%>>r=2; theta=(pi/2); phi=pi;
%>>Cart_vec=Spherical_to_Cartesian_Vector(r,theta,phi);
%>>Cart_vec'
%
%ans =
%
%-2.00000.00000.0000
Note that in this case the variables x,y,z only exist inside the function, they would not
interfere with any other variables named x,y,z used on the command line or inside other
functions. Chapter 3.3 discusses how to make your functions get input from the keyboard
or from a file, and how to save output to a file; you can skip 3.3 until you need to do this.
Functions can call other functions. This allows you to break tasks up into pieces, and to
write small functions that solve each piece separately, rather than trying to do the whole
thing at once in a giant m-file. This is called modularization, and we strongly recommend
you use it!
(Functions can even call themselves, this is called recursion, a too-tricky method we
recommend you avoid, as it often leads to bugs and sometimes to slow execution times.)
Each function should start with its name, then a comment line giving the purpose of the
function, its author and the date when it was last revised, and if it is a homework
assignment specify which problem it is solving and give your email address.
Then give details about the required inputs and the outputs: what they mean physically,
and what units they should be in. Also, list the other user-defined functions this function
relies upon. (Do not list Matlab’s built-in functions like cos or exp). This set of
information is called the “header”, and it is all the information that someone should need
to run your function correctly (i.e. if the function works, they shouldn’t have to look at
the rest of the m-file at all.) It is critically important that this section be clear and
complete!
To help yourself remember what you did (and to help the grader) you should add a few
additional comments inside the body of the function, particularly at points that seem
tricky or not-obvious to you as you write the program.
Finally, all functions should give a sample input and output as a comment at the bottom.
You can just cut and paste the appropriate section from the Matlab command line or
history into the function, and put % in front of each line.
MATLAB programs are stored as plain text in files having names that end with the
extension ``.m''. These files are called, not surprisingly, m-files. Each m-file contains
exactly one MATLAB function. Thus, a collection of MATLAB functions can lead to a
large number of relatively small files.
One nifty difference between MATLAB and traditional high level languages is that
MATLAB functions can be used interactively. In addition to providing the obvious
support for interactive calculation, it also is a very convenient way to debug functions
that are part of a bigger project.
MATLAB functions have two parameter lists, one for input and one for output. This
supports one of the cardinal rules of MATLAB programming: don't change the input
parameters of a function. Like all cardinal rules, this one is broken at times. My free
advice, however, is to stick to the rule. This will require you to make some slight
adjustments in the way you program. In the end this shift will help you write better
MATLAB code.
MATLAB m-files must be plain text files, i.e. files with none of the special formatting
characters included by default in files created by word-processors. Most word-processors
provide the option of saving the file as plain text, (look for a ``Save As...'' option in the
file menu). A word-processor is overkill for creating m-files, however, and it is usually
more convenient to use a simple text editor, or a ``programmer's editor''. For most types
of computers there are several text editors (often as freeware or shareware). Usually one
plain text editor is included with the operating system.
When you are writing m-files you will usually want to have the text editor and MATLAB
open at the same time. Since modern word-processors require lots of system RAM it may
not even be possible or practical (if you are working on a stand-alone personal computer)
for you to use a word-processor for m-file development. In this case a simple, text editor
will be your only option.
Function Defintion
To make the preceding point more concrete, consider the following statement
>> y = sin(x)
which is a call to the built-in sine function. If x is a scalar (i.e. a matrix with one row and
one column) then y will be a scalar. If x is a row vector, then y will be a row vector. If x
is a matrix then y is a matrix. (You should verify these statements with some simple
MATLAB calculations.)
This situation-dependence of input and output variables is a very powerful and potentially
very confusing feature of MATLAB. Refer to the ``addtwo.m'' function below for an
example.
Comment statements
MATLAB comment statements begin with the percent character, %. All characters from
the % to the end of the line are treated as a comment. The % character does not need to
be in column 1.
The first two lines after the function definition are comment statements. Not only do
these statements describe the statements in the file, their position in the file supports the
on-line help facility in MATLAB. If the first line of a MATLAB function definition is
immediately followed by non-blank comment statements, then those comment statements
are printed to the command window when you type ``help function_name". Try it with
the addtwo function. MATLAB will print up until a blank line or an executable
statement, whichever comes first. Refer to the Function prologues -- providing help
section for more information.
To test your understanding of input and output variables, pass the following definitions of
x and y to the addtwo function. (To save space the x and y variables are defined on the
same line. You can enter these variables on the same line, as shown, or use separate
lines.)
>> x = 2; y = 3;
>> x = [2 3]; y = [4; 5];
>> x = eye(3,3); y = -2*eye(3,3);
>> x = 'Sue'; y = 'Bob'
>> x = 'Jane'; y = 'Bob'
Here is another simple function, traparea.m, with three input parameters and one output
parameter. Since there is only one output parameter the square brackets may be omitted.
Finally, here is another simple function, cart2plr.m, with two input parameters and two
output parameters.
r = sqrt(x^2 + y^2);
theta = atan2(y,x);
The comment statements have empty lines, but these will be printed if you type ``help
cart2plr''.
Local Variables
Unless explicitly declared to be global variables, all variables appearing in a MATLAB
function are local to that function.
Flow Control
MATLAB supports the basic flow control constructs found in most high level
programming languages. The syntax is a hybrid of C and Fortran and I often create
polyglot statements which lead to the joyless task of squashing trivial bugs.
if constructs
• if ... end
• if ... else ... end
• if ... elseif ... else ... end
Here are some examples based on the familiar quadratic formula. (n.b. This is not an
endorsement of the code logic, just an easy to follow example of the ``if'' constructs.)
A simple warning
• no semicolon is needed to suppress output at the end of lines containing if, else,
elseif or endif
• elseif has no space between ``else'' and ``if''
• the end statement is required
• the ``is equal to'' operator has two equals signs (see Logical Comparisons below)
The compact if
If you read tightly coded m-files (e.g., many of the built-in MATLAB functions) you will
discover a variant of the if ... end construct that is written on one line. Here's an example
if x<0, disp('imaginary'); end
Notice the comma between the x<0 and the disp(...). Apparently the comma tells the
MATLAB interpretter that the conditional test has ended. To my knowledge this is only
place where a statement (OK, part of a statement) ends with a comma. It's just one of
those quirks that true believers come to use without hesitation.
Logical comparisons
The preceding table lists the logical comparison operators used in MATLAB. Note that
these operators can be used in assignment statements, as illustrated in this example
enough = xnew-xold < delta
if ~enough
stepSize = stepSize/2;
end
The first statement assigns the value of the logical comparison to the variable ``enough''.
If the comparison on the right hand side evaluates to be true, then enough is given the
value 1. If the comparison evaluates to be false, then enough is given the value 0. In the
subsequent if statement, enough = 1 is true, and enough = 0 is false.
Binary operators take two arguments (operands). Unary operators take one argument.
The && operator (read ``and'' operator) takes two logical expressions and returns ``true'' if
both expressions are true, and ``false'' otherwise.
The || operator (read ``or'' operator) takes two logical expressions and returns ``true'' if
either of the expressions are true, and ``false'' only if both expressions are false. The
possible outcomes of && and || operations are summarized in the following truth table.
The ~ operator (read ``not'') takes only one logical expression and returns the opposite
(negation) of that expression. Consider the following code
a = 2; b = 3;
asmall = a < b; % asmall is ``true''
if ~asmall
disp('a is greater than b')
end
Since a is less than b the if ~asmall block is not executed because ~asmall is false.
while constructs
i = 2;
while i<8
i = i + 2
end
Executing the preceding block of code results in the following output to the command
window
i = 4
i = 6
i = 8
(The output has been adjusted to take up less space. MATLAB likes to sprawl its printout
over several lines.) Note that no disp or fprintf statement was needed in the preceding
block because the i = i + 2 statement did not end in a semicolon.
for constructs
The for construct is used to create a loop, usually over a fixed range of steps
sum = 0;
for i=1:length(x)
while i<10
sum = sum + abs(x(i));
end