如何确定代码是作为函数执行还是使用单元格模式执行

sla*_*ton 5 debugging matlab

在编写/调试函数时,我喜欢使用单元格模式而不是断点.

如何在运行时确定当前正在执行的代码是作为函数执行还是使用单元格模式?

奖励积分如果您能够想出function它是从另一个函数或单元格中调用的.

这可能有用的一个示例是,您希望在执行函数期间以不同方式加载数据,或者是否要创建用于调试的绘图仪.在作为单元格或函数执行时切换时,注释掉特定行会变得很痛苦.

function doSomethingAwesome(inputs)
%%

if executingAsCell == true
  clear
  importData
end


% process stuff

if executingAsCell == true
   plot(myAwesomeResults)
end
Run Code Online (Sandbox Code Playgroud)

注意,这不是我之前的问题的重复: 如何确定代码是作为脚本或函数执行?

Jon*_*nas 2

最简单的方法是dbstack()按照@Junuxx的建议使用:

if isempty(dbstack)
   %# true if you evaluated the cell while not in debug mode
Run Code Online (Sandbox Code Playgroud)

类似地,一个函数可以通过检查dbstack的长度来知道它是从另一个函数调用还是从base/cell调用

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

函数实际上可以区分它是从命令行调用还是从单元格调用,因为后者不会写入历史记录:

   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
Run Code Online (Sandbox Code Playgroud)

如果您想确定是否处于调试模式,一种可能是使用linedbstack 中的 - 参数,并检查明显调用函数所在行是否存在对当前正在执行的函数的调用。