Search code examples
matlabpublish

Programmatically determine if a script is being published or executed normally


Prior to release R2016a, publishing is the way in MATLAB to document the results of a script. I find that when I run a script manually, I often place pause commands throughout my script. Is there a simple way to determine if a script is getting published or not? Then, I can wrap my pauses in a bit of code like:

if isNotPublishing
    pause();
end

My google foo has failed me in finding a solution to this.


Solution

  • An easy way to do this is to see if publish is in the call stack. dbstack will return an array of structs indicating which functions were called in what order to get to the point at which we call dbstack. We can use the name property to tell us the names of all of these functions and look to see if publish is among them. If it is, then we assume that the script was called via publish.

    stack = dbstack;
    isBeingPublished = ismember('publish', {stack.name});
    

    Or if you want that to be a one-liner

    isBeingPublished = ismember('publish', cellfun(@(x)x.name, dbstack, 'UniformOutput', 0));
    

    This should work whether you publish your script using the Publish toolbar or from the command line with

    publish('myscript.m')
    

    If you wanted to get really fancy, you could overload pause (or write your own version, mypause) that does this check for you. This works because within your new pause function, dbstack will still contain publish because you called it from your script which was ultimately evaluated by publish. If you create this function, then you wouldn't need all of that logic within your code and could just call mypause() instead.

    function mypause(varargin)
        stack = dbstack;
        if ~ismember('publish', {stack.name});
            builtin('pause', varargin{:})
        end
    end