Search code examples
matlabfunctionvariablesscriptingworkspace

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


I am learning about an existing code, which produces lots of different variables. My goal is to identify the variable in the workspace and localize the script that produced this variable.

I need to localize the script, because in the code I have a script that calls the other three scripts. For this reason it is difficult to identify the script that produced a specific variable. Besides, the three codes are very long.

How can I identify the source script based just on the workspace variables?


Solution

  • 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.