Читать книгу Applied Numerical Methods Using MATLAB - Won Y. Yang - Страница 39
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. OK, 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 variable(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.m clear, clf global D D=0.5; 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=<b>sinc1</b><![CDATA[(t,D) if nargin<2, D=1; end t(find(t==0))=eps; x=sin(pi*t/D)./(pi*t/D); | function x=<b>sinc2</b><![CDATA[(t) global D t(find(t==0))=eps; x=sin(pi*t/D)./(pi*t/D); |
Then, how convenient it would be, since you do not have to bother about passing the parameters. But as you get proficient in programming and handle many functions/routines that are involved with various sets of parameters, you might find that the global variable is not always convenient, because of the following reasons:
Once a variable is declared as global, its value can be changed in any of the MATLAB functions having declared it as global, without being noticed by other related functions. Therefore, it is usual to declare only the constants as global and use long names (with all capital letters) as their names for easy identification.
If some variables are declared as global and modified by several functions/routines, it is not easy to see the relationship and the interaction among the related functions in terms of the global variable. In other words, the program readability gets worse as the number of global variables and related functions increases.
For example, let us look over the above script “plot_sinc.m” and the function ‘ sinc2()
’. They both have a declaration of D
as global and consequently, ‘ sinc2()
’ does not need the second input argument for getting the parameter D
. Running the script, you will see that both ‘ sinc1()
’ (accepting D=0.5
as an input argument) and ‘ sinc2()
’ (knowing D=0.5
as a global variable) result in the same graphic result as the solid‐line graph shown in Figure 1.7b.