如何识别生成特定工作区变量的脚本?
How to identify the script that produced a specific workspace variable?
我正在学习一个现有的代码,它会产生很多不同的变量。我的目标是识别工作区中的变量并本地化生成该变量的脚本。
我需要本地化脚本,因为在代码中我有一个调用其他三个脚本的脚本。因此,很难识别生成特定变量的脚本。另外,三个代码很长
如何仅根据工作区变量识别源脚本?
我最近遇到了类似的问题,所以我一起破解了一个快速函数,它会根据初始状态检测新创建的变量。
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
),而不是 updated/overwritten 变量.
您可以为此使用 exist
。大致:
assert( ~exist('varName', 'var'), 'Variable exists!');
script1(in1, in2);
assert( ~exist('varName', 'var'), 'Variable exists!');
script2(in1, in2);
assert( ~exist('varname', 'var'), 'Variable exists!');
当断言失败时,表示变量已创建。
我正在学习一个现有的代码,它会产生很多不同的变量。我的目标是识别工作区中的变量并本地化生成该变量的脚本。
我需要本地化脚本,因为在代码中我有一个调用其他三个脚本的脚本。因此,很难识别生成特定变量的脚本。另外,三个代码很长
如何仅根据工作区变量识别源脚本?
我最近遇到了类似的问题,所以我一起破解了一个快速函数,它会根据初始状态检测新创建的变量。
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
),而不是 updated/overwritten 变量.
您可以为此使用 exist
。大致:
assert( ~exist('varName', 'var'), 'Variable exists!');
script1(in1, in2);
assert( ~exist('varName', 'var'), 'Variable exists!');
script2(in1, in2);
assert( ~exist('varname', 'var'), 'Variable exists!');
当断言失败时,表示变量已创建。