我被这个非常简单的函数卡住了。我正在犯一些根本的概念上的错误,我看不到。任何帮助都将不胜感激。
我想使用代码来检查工作空间中是否存在某个变量。如果是,则不应执行任何操作,否则应对文件中的ex读取执行特定操作。谢谢
最小可重现示例:
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发布于 2020-03-06 05:07:03
代码有两个问题:
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等都在"base“工作区中,单独的函数无法访问它们。函数可以使用哪些变量的概念称为作用域。这里有一个链接,指向讨论MATLAB中的范围的blog post。
2)正在发生的另一件事是,同一行代码对存在的变量的名称执行regexp,即字符串'variable_to_check‘。因此,字符'a‘、'b’、'c‘都由regexp匹配,但'd’不匹配。所以你可以检查一个神秘的变量"v":
>> workspace_variables_check('v')
workspace_variables =
1×1 cell array
{'variable_to_check'}
Present from Workspace还有"ch“、"var”等。我打赌这会使调试变得混乱:)
如果您希望函数检查"base“工作区中的变量(这是从命令行使用的工作区),您可以使用以下命令:
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发布于 2020-03-05 22:13:46
您正在寻找函数exist。实际上,您希望执行以下操作
if exist(variable_to_check,'var') == 1
% do something
end请注意,无论您是否指定搜索类型(这里是'var'),该函数都将独立地返回整数代码,但为了提高速度和清晰度,建议您这样做。
0-名称不存在或由于其他原因无法找到。例如,如果name存在于MATLAB®无权访问的受限文件夹中,则exist返回0。1- name是工作区中的变量。2- name是扩展名为.m、.mlx或.mlapp的文件,或者name是具有未注册文件扩展名(.mat、.fig、.txt)的文件的名称。3- name是MATLAB搜索路径上的MEX文件。4- name是MATLAB搜索路径中加载的Simulink®模型或Simulink模型或库文件。5- name是一个内置的MATLAB函数。这不包括类。6- name是MATLAB搜索路径上的P代码文件。7- name是一个文件夹。8- name是一个类。(如果使用-nojvm选项启动MATLAB,则对于Java类,exist返回0。)
https://stackoverflow.com/questions/60543163
复制相似问题