How to identify the script that produced a specific workspace variable?

I recently had a similar problem, so I hacked a quick function together, which will detect newly created variables, based on an initial state.

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

To use this, first initialize the function with argument 1 to get the variables currently in the workspace: findNewVariables(1). Then run some code, script, whatever, which will create some variables in the workspace. Then call the function again, and store its output as follows: new_vars = findNewVariables(2). new_vars is a cell array that contains the names of the newly created variables.

Example:

% 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);

Which will result in:

>> new_vars

new_vars =

  3×1 cell array

    {'b'}
    {'c'}
    {'d'}

Note, this will only detect newly created variables (hence a clear is required at the start of the script), and not updated/overwritten variables.


You could use exist for this. Roughly:

assert( ~exist('varName', 'var'), 'Variable exists!');

script1(in1, in2);
assert( ~exist('varName', 'var'), 'Variable exists!');

script2(in1, in2);
assert( ~exist('varname', 'var'), 'Variable exists!');

When the assertion fails, it means that the variable was created.