Difference between script and matlab command windo

2019-03-02 18:12发布

I wonder what the difference is between entering a few lines in the command window, or letting a script execute them.

In the question Escape from nested try - catch statement I have an example function. I have put the selected code in a script and called it, however then it does not work properly. On the other hand, when I select the lines and hit f9, it works as expected.

The lines are:

dbclear all
dbquit
dbstop if caught error

I call the example function as such:

dbstop if caught error
mytestmain

And the example function is:

function mytestmain 
try
    mytestsub
catch
end

% Definition of subfunction, may or may not be in the same .m file
function mytestsub
try
    a=b; %Intentionally generate an error as b is not defined
catch
end

2条回答
The star\"
2楼-- · 2019-03-02 18:22

Depending on what you mean by "doesn't work", it could just be because the debugger is a special context and certain debugger commands - dbup, dbdown, and dbquit - only work when you're at a debugger "K>>" prompt. Once you call a script, you're no longer at the debugger prompt but in normal code execution - inside a nested M-code call stack - and they just don't work there. When you F9, it does the lines individually, so each one is done from the prompt.

As a workaround, if you really want to execute a sequence of debugger commands like this, you could write a little Java Swing widget to enter the text in to the command window just as though you were typing it in.

查看更多
仙女界的扛把子
3楼-- · 2019-03-02 18:33

I think it's related to MATLAB's just-in-time (JIT) compiler, which compiles functions before it runs them.

It seems that it compiles functions differently if dbstop is set or not (see here for reference). As it currently stands, MATLAB can not recompile a function while it is run (just try saving a changed function during a dbstop, and you will get a message informing you). As you can add and remove breakpoints during a dbstop I think you can also do so programmatically, but it should be impossible to "turn on" debugging if it wasn't turned on at "compile time"

So in your cases:

  • Using F9 it's just pasted and parsed as if you input it manually. So first dbstop is set, then mytestmain gets compiled and executed.
  • Running as a script will first compile the script and mytestmain and then execute it - so dbstop would be set after compilation and therefore not in effect.
查看更多
登录 后发表回答