Page 52 - Applied Numerical Methods Using MATLAB
P. 52
TOWARD GOOD PROGRAM 41
function m = fctrl(n)
ifn<0, error(’The factorial of negative number ??’);
else m = 1; for k = 2:n, m = m*k; end
end
This shows the error message (given as the input argument of the error()
routine) together with the name of the routine in which the accidental “error”
happens, which is helpful for the user to avoid the error.
Most common runtime errors are caused by an “out of domain” index of array
and the violation of matrix dimension compatibility, as illustrated in Section 1.1.7.
For example, consider the gauss(A,B) routine in Section 2.2.2, whose job is to
solve a system of linear equations Ax=b for x. To appreciate the role of the fifth
line handling the dimension compatibility error in the routine, remove the line
(by putting the comment mark % before the line in the M-file defining gauss())
and type the following statements in the Command window:
>>A = rand(3,3); B = rand(2,1); x = gauss(A,B)
?? Index exceeds matrix dimensions.
Error in ==> C:\MATLAB6p5\nma\gauss.m
On line 10 ==> AB = [A(1:NA,1:NA) B(1:NA,1:NB)];
Then MATLAB gives you an error message together with the suspicious state-
ment line and the routine name. But it is hard to figure out what causes the
runtime error, and you may get nervous lest the routine should have some bug.
Now, restore the fifth line in the routine and type the same statements in the
Command window:
>>x = gauss(A,B)
?? Error using ==> gauss
A and B must have compatible dimension
This error message (provided by the programmer of the routine) helps you to
realize that the source of the runtime error is the incompatible matrices/vectors A
and B given as the input arguments to the gauss() routine. Very like this, a good
program has a scenario for possible user mistakes and fires the error routine for
each abnormal condition to show the user the corresponding error message.
Many users often give more/fewer input arguments than supposed to be given
to the MATLAB functions/routines and sometimes give wrong types/formats of
data to them. To experience this type of error, let us try using the MATLAB
function sinc1(t,D) (Section 1.3.5) to plot the graph of a sinc function
sin(πt/D)
sin c(t/D) = with D = 0.5and t = −2, 2 (1.3.6)
πt/D
With this purpose, type the following statements in the Command window.