Page 55 - Applied Numerical Methods Using MATLAB
P. 55
44 MATLAB USAGE AND COMPUTATIONAL ERRORS
What do you see in the graphic window on the screen? Surprise, a (horizontal)
straight line running parallel with the t-axis far from any sinc function graph!
What is more surprising, the value of sinc1(t,D) or sin(pi*t/D)/(pi*t/D)
shows up as a scalar. Authors hope that this accident will help you realize how
important it is for right term-by-term operations to put .(dot) before the arithmetic
operators *, / and ^ . By the way, aren’t you curious about how MATLAB deals
with a vector division without .(dot)? If so, let’s try with the following statements:
>>A = [1:10]; B = 2*A; A/B, A*B’*(B*B’)^-1, A*pinv(B)
ans = 0.5
To understand this response of MATLAB, you can see Section 1.1.7 or Sec-
tion 2.1.2.
In this section we looked at several sources of runtime error, hoping that it
aroused the reader’s attention to the danger of runtime error.
1.3.5 Parameter Sharing via Global Variables
When we discuss the runtime error that may be caused by user’s default in passing
some parameter as input argument to the corresponding function, you might feel
that the parameter passing job is troublesome. Okay, it is understandable as a
beginner in MATLAB. How about declaring the parameters as global so that
they can be accessed/shared from anywhere in the MATLAB world as far as the
declaration is valid? If you want to, you can declare any varable(s) by inserting
the following statement in both the main program and all the functions using
the variables.
global Gravity_Constant Dielectric_Constant
%plot_sinc
clear, clf
global D
D=1;b1=-2; b2=2;
t = b1 +[0:100]/100*(b2 - b1);
%passing the parameter(s) through arguments of the function
subplot(221), plot(t, sinc1(t,D))
axis([b1 b2 -0.4 1.2])
%passing the parameter(s) through global variables
subplot(222), plot(t, sinc2(t))
axis([b1 b2 -0.4 1.2])
function x = sinc1(t,D) function x = sinc2(t)
if nargin<2, D = 1; end global D
t(find(t == 0)) = eps; t(find(t == 0)) = eps;
x = sin(pi*t/D)./(pi*t/D); x = sin(pi*t/D)./(pi*t/D);
Then, how convenient it would be, since you don’t have to bother about pass-
ing the parameters. But, as you get proficient in programming and handle many