Page 54 - Applied Numerical Methods Using MATLAB
P. 54
TOWARD GOOD PROGRAM 43
or, equivalently
for i = 1:length(t), if t(i) == 0, t(i) = eps; end, end
This statement changes every zero element in the t vector into eps (2.2204e-
016). What is the real purpose of this statement? It is actually to remove the
possibility of division-by-zero in the next statement, which is a mathematical
expression having t in the denominator.
x = sin(pi*t/D)./(pi*t/D);
To appreciate the role of the third line in sinc1(), we remove it from the M-file
defining sinc1(), and type the following statement in the Command window.
>>plot(t,sinc1(t,D),’r’)
Warning: Divide by zero.
(Type "warning off MATLAB:divideByZero" to suppress this warning.)
In C:\MATLAB6p5\nma\sinc1.m at line 4)
This time we get just a warning (black) error message with a similar graphic
result as depicted in Fig. 1.8b. Does it imply that the third line is dispensable?
No, because the graph has a (weird) hole at t = 0, about which most engi-
neers/mathematicians would feel uncomfortable. That’s why authors strongly
recommend you not to omit such an error-handling part as the third line as
well as the second line in the MATLAB function sinc1().
(cf) What is the value of sinc1(t,D) for t=0 in this case? Aren’t you curious? If so,
let’s go for it.
>>sinc1(0,D), sin(pi*0/D)/(pi*0/D), 0/0
ans = NaN (Not-a-Number: undetermined)
Last, consider of the fourth line in sinc1(), which is only one essential
statement performing the main job.
x = sin(pi*t/D)./(pi*t/D);
What is the .(dot) before /(division operator) for? In reference to this, authors
gave you a piece of advice that you had better put a .(dot) just before the
arithmetic operators *(multiplication), /(division), and ^(power) in the function
definition so that the term-by-term (termwise) operation can be done any time
(Section 1.1.6, (A5)). To appreciate the existence of the .(dot), we remove it from
the M-file defining sinc1(), and type the following statements in the Command
window.
>>clf, plot(t,sinc1(t,D)), sinc1(t,D), sin(pi*t/D)/(pi*t/D)
ans = -0.0187