我最近遇到了类似的问题,因此我一起破解了一个快速函数,该函数将基于初始状态检测新创建的变量。
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
Run Code Online (Sandbox Code Playgroud)
要使用此功能,请首先使用参数初始化函数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);
Run Code Online (Sandbox Code Playgroud)
这将导致:
>> new_vars
new_vars =
3×1 cell array
{'b'}
{'c'}
{'d'}
Run Code Online (Sandbox Code Playgroud)
注意,这只会检测新创建的变量(因此clear
在脚本开始时需要a ),而不是更新/覆盖的变量。