函数概念帮助:检查工作空间MATLAB中是否存在变量



我被这个非常简单的函数卡住了。我犯了一些根本性的概念错误,我看不出来。任何帮助都将不胜感激。

我想使用代码来检查工作空间中是否存在某个变量。如果是,则不应执行任何操作,否则应为文件中的ex-read执行特定操作。感谢

最小可重复性示例:

function workspace_variables_check(variable_to_check)
% Loop over all the Variables in the Workspace to get the all the variable names
workspace_variables = who('-regexp',variable_to_check);
if isempty(workspace_variables) % A variable by this name is present in the workspace
disp('Absent in Workspace')
output = 1 ;
else                            % A variable by this name is not present in the workspace
disp('Present from Workspace')
output = 0 ;
end

示例:a=1;b=1;c=1:d=1:

测试功能:

workspace_variables_check('d')
workspace_variables_check('b')
workspace_variables_check('c')
workspace_variables_check('a')

功能输出:

Variable NOT Present
ans =
0
Variable Present
ans =
1
Variable Present
ans =
1
Variable Present
ans =
1

代码有两个问题:

1( 当函数调用who时,它会返回函数工作区中可用的变量列表,而不是基本工作区中的变量列表。如果从第一行代码中删除分号,您将看到函数的输出:

workspace_variables = who('-regexp',variable_to_check)

当你从命令行运行函数时,你会发现当这一行执行时,函数只有一个变量,这个变量就是输入变量"variable_to_check":

>> workspace_variables_check('b')
workspace_variables =
1×1 cell array
{'variable_to_check'}

所有变量a、b、c等都在"基本"工作空间中,单独的函数无法访问它们。函数可用变量的概念称为scope。这里有一个博客文章的链接,讨论了MATLAB中的作用域。

2( 发生的另一件事是,同一行代码对存在的变量的名称执行regexp,即字符串"variable_to_check"。因此,字符"a"、"b"、"c"都由正则表达式匹配,但"d"不匹配。因此,您可以检查神秘变量"v":

>> workspace_variables_check('v')
workspace_variables =
1×1 cell array
{'variable_to_check'}
Present from Workspace

还有"ch"、"var"等。我敢打赌,这让调试变得混乱:(

如果你想要一个函数来检查"基本"工作区中的变量(这是你在命令行中使用的(,你可以使用这个:

function output = workspace_variables_check(variable_to_check)
% Check to see if a variable exists in the Base Workspace
exist_string = sprintf('exist(''%s'')',variable_to_check);
workspace_variables = evalin('base',exist_string);
if workspace_variables == 1      % A variable by this name is present in the workspace
disp('Present from Workspace')
output = 1 ;
else                        % A variable by this name is not present in the workspace
disp('Absent in Workspace')
output = 0 ;
end

您正在查找函数exist。事实上,你想做以下

if exist(variable_to_check,'var') == 1
% do something
end

请注意,无论是否指定搜索类型(此处为'var'(,该函数都将独立返回整数代码,但为了速度和清晰度,建议使用该函数。

0 — name does not exist or cannot be found for other reasons. For example, if name exists in a restricted folder to which MATLAB® does not have access, exist returns 0.
1 — name is a variable in the workspace.
2 — name is a file with extension .m, .mlx, or .mlapp, or name is the name of a file with a non-registered file extension (.mat, .fig, .txt).
3 — name is a MEX-file on your MATLAB search path.
4 — name is a loaded Simulink® model or a Simulink model or library file on your MATLAB search path.
5 — name is a built-in MATLAB function. This does not include classes.
6 — name is a P-code file on your MATLAB search path.
7 — name is a folder.
8 — name is a class. (exist returns 0 for Java classes if you start MATLAB with the -nojvm option.)

最新更新