How to determine whether code will execute as a function or use cell mode

I like to use cell mode , not break points when recording / debugging.

How would you determine at runtime if the executable code is currently executing as a function or using cell mode?

Bonus points If you can find functionone that knows that it was called from another function or from a cell.

An example of when this might be useful is that you want to load data in different ways during function execution or if you want to create plotters for debugging. It becomes painful to comment on certain lines when switching between execution as a hundredth or function.

function doSomethingAwesome(inputs)
%%

if executingAsCell == true
  clear
  importData
end


% process stuff

if executingAsCell == true
   plot(myAwesomeResults)
end

: : , script ?

+5
1

- dbstack(), @Junuxx:

if isempty(dbstack)
   %# true if you evaluated the cell while not in debug mode

, , /, dbstack

   function doSomething
   if length(dbstack)==1
      %# the function has been invoked from a cell or the command line
      %# (unless you're in debug mode)

, , :

   function doSomething

   if length(dbstack)==1
      javaHistory=com.mathworks.mlservices.MLCommandHistoryServices.getSessionHistory;
      lastCommand = javaHistory(end).toCharArray'; % ' added for SO code highlighting
      if strfind(lastCommand,'doSomething')
         %#  Probably invoked via command line
      else
         %#  Probably invoked via executing a cell

, , - line -argument dbstack , , .

+2

All Articles