2012-10-28 16 views
2

我在Matlab中使用全局變量有一個很奇怪的問題。Matlab:變量自動設置爲一次聲明爲全局的值?

通常,在將一個變量聲明爲全局變量之前,它將作爲一個空變量保留。我有一個變量R,我想聲明爲全局變量。但在輸入clearglobal R之後,在變量列表R已被設置爲1 * 18數組,其中填充了一些零和其他數字。

我確實有一些其他的功能和腳本共享的全局變量R,但我確信我沒有叫任何腳本或函數的我輸入clear後,變量列表已經爲空,當我從輸入global R提示。

enter image description here

但儘管如此,問題依然存在。我想我必須對有關全局變量的規則有一些嚴重的誤解。有人可以解釋爲什麼會發生這種情況嗎?

在此先感謝。

回答

6

clear命令不清除全局變量。它從您的本地工作區中刪除變量,但它仍然存在。因此,如果您以前爲其分配了一些值,則再次聲明它只會在您的本地範圍中「顯示」全局變量。您必須使用clear allclear global。從documentationclear的:

如果變量名是全局的,那麼清楚當前工作空間中刪除它,但它仍然在全球的工作區。

請看下面的例子:

>> clear all; 
>> global v; 
>> v = 1:100; % assign global variable 
>> whos  % check if it is there 

    Name  Size    Bytes Class  Attributes 

    v   1x100    800 double global  

>> clear; 
>> whos  % nothing declared in local workspace 
>> global v; 
>> whos  % ups, v is not empty!! 

    Name  Size    Bytes Class  Attributes 

    v   1x100    800 double global  

>> clear global;  % you have to clear it properly 
>> whos 
>> global v   % now it is empty 
>> whos 
    Name  Size   Bytes Class  Attributes 

    v   0x0     0 double global  
+0

工作就像一個魅力,謝謝! – Vokram