| MATLAB Function Reference | ![]() |
Syntax
global X Y Z
Description
global X Y Z
將 X, Y, Z
定義為全域變數。
一般說來,每一個M檔案所定義的函式中,都有只屬於本身函式而且和其他函式、其他基本工作欄(base workspace)不同的區域變數。然而,若多個函式或基本工作欄(base workspace)都宣告某個特定的變數為全域變數的話,這些函式就可以共用這個變數。因此,只要這個函式定義此變數為全域變數,就可以存取該變數。
若你是第一次利用 global
指令來定義一個之前未宣告過的全域變數,此變數一開始為一空矩陣。
若你宣告的全域變數名稱已經在目前的工作欄(workspace)中,MATLAB會發出警告訊息並改變此變數的值,使其能符合全域變數。
Remarks
可利用 clear global variable
指令來清除全域工作欄(global workspace)中的全域變數。利用 clear variable
來在不影響全域變數的情形之下從目前的工作欄中清除全域連結。
To use a global within a callback, declare the global, use it, then clear the global link from the workspace. This avoids declaring the global after it has been referenced. For example,
uicontrol('style','pushbutton','CallBack',...
'global MY_GLOBAL,disp(MY_GLOBAL),MY_GLOBAL = MY_GLOBAL+1,clear MY_GLOBAL',...
There is no function form of the global command (i.e., you cannot use parentheses and quote the variable names).
Examples
下列範例是函式名稱為 tic
和 toc 的程式碼(有些指令已被省略)。 這些函式操縱一個碼表記時器。這二個函式共享全域變數 TICTOC
,但此變數在基本工作欄(base workspace)和未宣告此變數的函式中均無法看見(invisible)。
function tic
% TIC Start a stopwatch timer.
% TIC; any stuff; TOC
% prints the time required.
% See also: TOC, CLOCK.
global TICTOC
TICTOC = clock;
function t = toc
% TOC Read the stopwatch timer.
% TOC prints the elapsed time since TIC was used.
% t = TOC; saves elapsed time in t, does not print.
% See also: TIC, ETIME.
global TICTOC
if nargout < 1
elapsed_time = etime(clock,TICTOC)
else
t = etime(clock,TICTOC);
end
See Also
| ginput | gmres | ![]() |