2011-12-25 69 views
3

在MATLAB說你做:Matlab的 - 我怎麼知道一個變量名是否可以自由使用

E = cell(3,1); 

如何知道自己是否被已被使用E和上面的電話不會覆蓋它?我必須運行程序並在那個時間休息嗎?解釋器中有沒有一種方法可以爲我做到這一點?例如,在C++中,編譯器會告訴你是否嘗試使用現有名稱。

+0

Duplicate:http://stackoverflow.com/questions/674474/how-to-determine-whether-a-matrix-is-empty-or-not-in-matlab/674477#674477 – 2011-12-25 13:30:02

+1

@Audrey。這不是一個重複的問題。 OP不詢問變量值是否爲空。問題是關於確定變量是否已被使用。 – Kavka 2011-12-25 21:41:47

+0

@kavka,好吧,你是對的。 – 2011-12-26 14:10:15

回答

0

爲了使用存在,您必須首先運行該腳本,以便工作空間將填充您正在使用的所有變量。如果您想在編寫腳本時檢查變量名是否可用,我最喜歡的方法是使用Matlab IDE中的Tab鍵。它會提出所有的自動完成選項。如果您之前在腳本或函數中定義了變量名稱「E」,則鍵入「E」應顯示E作爲選項,並提醒您不要使用該變量。

此外,IDE的最新版本引入了自動突出顯示腳本中給定變量的所有用法。只需將光標置於字母之間或變量名稱的末尾即可。在腳本中直觀地檢查變量名稱的所有用法非常方便。

8

this page,你應該使用命令exist

help exist 
EXIST Check if variables or functions are defined. 
    EXIST('A') returns: 
    0 if A does not exist 
    1 if A is a variable in the workspace 
    2 if A is an M-file on MATLAB's search path. It also returns 2 when 
     A is the full pathname to a file or when A is the name of an 
     ordinary file on MATLAB's search path 
    3 if A is a MEX- or DLL-file on MATLAB's search path 
    4 if A is a MDL-file on MATLAB's search path 
    5 if A is a built-in MATLAB function 
    6 if A is a P-file on MATLAB's search path 
    7 if A is a directory 
    8 if A is a Java class 
+0

在這種情況下,應該使用「1」。 – 2011-12-25 13:23:20

+3

這是'exist('E','var')'檢查是否存在一個變量'E',它順便比'exists'('E')== 1'更易於理解。 – Egon 2011-12-25 13:40:24

1

用途:

if isempty (whos('E')) 
    % variable can be used 
end 
0

您可以使用checkcodemlint做的MATLAB文件靜態分析,其中除其他事項外如果在函數中使用變量之前應該報告變量。

相關問題