如何识别产生特定工作区变量的脚本?

Jua*_*ñoz 9 variables workspace scripting matlab function

我正在学习一个现有代码,该代码会产生许多不同的变量。我的目标是在工作空间中识别变量并本地化生成此变量的脚本。

我需要对脚本进行本地化,因为在代码中,我有一个调用其他三个脚本的脚本。因此,很难识别产生特定变量的脚本。此外,这三个代码很长。

如何仅根据工作区变量来识别源脚本?

rin*_*ert 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
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 ),而不是更新/覆盖的变量。