我正在学习一个现有代码,该代码会产生许多不同的变量。我的目标是在工作空间中识别变量并本地化生成该变量的脚本。
我需要对脚本进行本地化,因为在代码中,我有一个脚本可以调用其他三个脚本。因此,很难识别产生特定变量的脚本。此外,这三个代码很长。
如何仅根据工作区变量来识别源脚本?
答案 0 :(得分:8)
最近我遇到了类似的问题,所以我一起破解了一个快速函数,该函数将基于初始状态检测新创建的变量。
function names2 = findNewVariables(state)
persistent names1
if state == 1
% store variables currently in caller workspace
names1 = evalin('caller', 'who');
names2 = [];
elseif state == 2
% which variables are in the caller workspace in the second call
names2 = evalin('caller', 'who');
% find which variables are new, and filter previously stored
ids = ismember(names2,names1) ~= 1;
names2(~ids) = [];
names2(strcmp(names2, 'names1')) = [];
names2(strcmp(names2, 'names2')) = [];
names2(strcmp(names2, 'ans')) = [];
end
要使用此功能,请首先使用参数1
初始化该函数,以获取当前在工作区中的变量:findNewVariables(1)
。然后运行一些代码,脚本等等,这将在工作区中创建一些变量。然后再次调用该函数,并按如下方式存储其输出:new_vars = findNewVariables(2)
。 new_vars
是一个单元格数组,其中包含新创建的变量的名称。
示例:
% make sure the workspace is empty at the start
clear
a = 1;
% initialize the function
findNewVariables(1);
test % script that creates b, c, d;
% store newly created variable names
new_vars = findNewVariables(2);
这将导致:
>> new_vars
new_vars =
3×1 cell array
{'b'}
{'c'}
{'d'}
注意,它将仅检测新创建的变量(因此在脚本开始时需要clear
),而不检测更新/覆盖的变量。
答案 1 :(得分:4)
assert( ~exist('varName', 'var'), 'Variable exists!');
script1(in1, in2);
assert( ~exist('varName', 'var'), 'Variable exists!');
script2(in1, in2);
assert( ~exist('varname', 'var'), 'Variable exists!');
断言失败时,表示已创建变量。