Page 51 - Applied Numerical Methods Using MATLAB
P. 51
40 MATLAB USAGE AND COMPUTATIONAL ERRORS
1.3.3 Iterative Routine Versus Nested Routine
In this section we compare an iterative routine and a nested routine performing the
same job. Consider the following two programs fctrl1(n)/fctrl2(n), whose
common objectives is to get the factorial of a given nonnegative integer k.
k! = k(k − 1) ··· 2 · 1 (1.3.5)
They differ in their structure. While fctrl1() uses a for loop structure, fctrl2()
uses the nested (recursive) calling structure that a program uses itself as a subroutine
to perform a sub-job. Compared with fctrl1(), fctrl2() is easier to program as
well as to read, but is subject to runtime error that is caused by the excessive use
of stack memory as the number of recursive calls increases with large n. Another
disadvantage of fctrl2() is that it is time-inefficient for the number of function
calls, which increases with the input argument (n). In this case, a professional
programmer would consider the standpoint of users to determine the programming
style. Some algorithms like the adaptive integration (Section 5.8), however, may
fit the nested structure perfectly.
function m = fctrl1(n) function m = fctrl2(n)
m=1; ifn<=1, m=1;
for k = 2:n, m = m*k; end else m = n*fctrl2(n-1);
end
1.3.4 To Avoid Runtime Error
A good program guides the program users who don’t know much about the
program and at least gives them a warning message without runtime error for
their minor mistake. If you don’t know what runtime error is, you can experience
one by taking the following steps:
1. Make and save the above routine fctrl1() in an M-file named ‘fctrl.m’
in a directory listed in the MATLAB search path.
2. Type fctrl(-1) into the MATLAB Command window. Then you will see
>>fctrl(-1)
ans=1
This seems to imply that (−1)! = 1, which is not true. It is caused by the mistake
of the user who tries to find (−1)! without knowing that it is not defined. This
kind of runtime error seems to be minor because it does not halt the process.
But it needs special attention because it may not be easy to detect. If you are a
good programmer, you will insert some error handling statements in the program
fctrl() as below. Then, when someone happens to execute fctrl(-1) in the
Command window or through an M-file, the execution stops and he will see the
error message in the Command window as
??? Error using ==> fctrl
The factorial of negative number ??