10.10 Introduction to Chemical Engineering

NMM Chapters 3-4: Programming in MATLAB

Flow of Control

We need a way to make the computer do repetitive processes, and give it some logic so it can decide when to stop iterating. In Matlab the repetitive processes are done using “for”(NMM 3.4.5) and “while” (NMM 3.4.6) commands to set up loops. There are several ways to handle the logic discussed in NMM 3.4; by far the most popular is the “if…else” construction (NMM 3.4.3). You must master these three constructions. Several examples are given in the text, and posted on the 10.10 Web page.
 
The flow of control syntax (if, while, for) is just a notation for writing down common flowchart constructions; here are some equivalents:

IF….ELSE….END

 
 
if a<4
   command 1
else
   command 2
end
command 3

 

If there is no command 2, the else can be omitted.
 




WHILE….END

 
 
while abs(r_old-r_new) > tol 
   r_old=r_new; 
   r_new=0.5*(r_old + x/r_new) 
end
command 4
 

 
 
 
WARNING: At least one of the
variables used in the test must change
inside the while loop, or the loop will
execute forever without exiting.

 
 
 
 
 
 
 
 
 
 



 

FOR …. END

for n=1:10
    sum = sum + n;
end
command 5

 
 
 
 
 
 
 
 
 

You can skip Section 3.5 and most of Section 3.6. However, don’t miss the feval function described in NMM 3.6.3, which allows you to pass function names as inputs; you will need that for some of the programming assignments.

Once you start using logic and loops in your programs, you will certainly introduce bugs. If you are not careful, you could spend many hours this semester trying to root out the bugs you introduced. Chapter 4 is full of good suggestions about how to write your programs to reduce the likelihood of introducing bugs, and of methods for identifying the bugs you will inevitably introduce. Modularization really helps with debugging: it is much easier to correctly write and debug a short m-file than it is to debug a long m-file. To benefit from this advantage, you must carefully test and debug each little m-file separately, before you call it from other functions.

When you get to the stage in your life when you are considering writing a really long computer program, we strongly recommend that you read the book Code Complete before you begin. But Chapter 4 of NMM will suffice for 10.10.


Next Chapter: Numerical Errors
Back to Study Guide Index
Back to 10.10 home page
last modified: August 29, 2002