沒有找到一個乾淨的解決方案,但你可以可能使用try-catch
(如@Ilya建議)和nargin
編輯 - 使用function
避免一些命名衝突;使用exist
到輸入進一步分類(如MEX文件)
function is_script = is_a_script(varargin)
% is_a_script(varargin) returns one of the following:
% 1: if the input is a script
% 0: if the input is a function
% -1: if the input is neither a function nor a script.
is_script = 0;
switch(exist(varargin{1}))
case 2
% If the input is not a MEX or DLL or MDL or build-in or P-file or variable or class or folder,
% then exist() returns 2
try
nargin(varargin{1});
catch err
% If nargin throws an error and the error message does not match the specific one for script, then the input is neither script nor function.
if(strcmp(err.message, sprintf('%s is a script.',varargin{1})))
is_script = 1;
else
is_script = -1;
end
end
case {3, 4, 5, 6} % MEX or DLL-file, MDL-file, Built-in, P-file
% I am not familiar with DLL-file/MDL-file/P-file. I assume they are all considered as functions.
is_script = 0;
otherwise % Variable, Folder, Class, or other cases
is_script = -1;
end
來源
2013-04-09 19:52:32
YYC
如果您嘗試將錯誤數量的參數傳遞給函數,您是否也會得到錯誤?然後,它看起來像你說的問題不是腳本特定的... – 2013-04-09 19:03:28
@Ilya雖然這是一個不同的錯誤。我只是指出了錯誤,指出MATLAB可以區分腳本和函數,因爲它報告這個東西是一個腳本。但也許它只是在運行後纔算出來的,我不知道... – Szabolcs 2013-04-09 19:06:12
它使用標識符MATLAB來拋出異常:scriptNotAFunction當發生這種情況時,所以你可以通過try-catch來檢測這一點與matlab相同,但如果嘗試工作腳本將正常執行... – 2013-04-09 19:10:36