MATLAB - Interrupting function execution
MATLAB itself does not provide any way of arbitrarily interrupting/pausing a function at mid-execution to examine the internal function stack/variables. It is a pity since such a mechanism would be an extremely valuable debugging tool.
Finally, I realized that this is not as impossible as it seems. In fact, it is EXTREMELY simple! All that is required are four lines of code in any script/function:
The system command is used to run system console commands. Here, a simple check is made for the existence of the file 'sometoken' in the current directory. If the file exists, statcode is set to zero and the if condition is satisfied. The keyboard command is then executed which causes MATLAB to pause execution and return control to the command line! In order to continue execution, 'sometoken' must be deleted/removed from the current directory and the command return must be issued.
The best place for this code is perhaps in any loop that might exist in the MATLAB script/function. Then, to cause execution to pause, one simply needs to create a file 'sometoken' in the current directory.
Finally, I realized that this is not as impossible as it seems. In fact, it is EXTREMELY simple! All that is required are four lines of code in any script/function:
[statcode, result] = system('ls sometoken');
if statcode == 0
keyboard
end
The system command is used to run system console commands. Here, a simple check is made for the existence of the file 'sometoken' in the current directory. If the file exists, statcode is set to zero and the if condition is satisfied. The keyboard command is then executed which causes MATLAB to pause execution and return control to the command line! In order to continue execution, 'sometoken' must be deleted/removed from the current directory and the command return must be issued.
The best place for this code is perhaps in any loop that might exist in the MATLAB script/function. Then, to cause execution to pause, one simply needs to create a file 'sometoken' in the current directory.
2 Comments:
Thanks for this excellent idea.
But I had to use some other command becasue 'ls' wasn't working on my computer.
My alternative is:
pausecmd = dir('sometoken');
if size(pausecmd,1) > 1
delete('sometoken')
keyboard
end
As you can see I added an extra line to automatically delete the created file.
Thanks for the comment/enhancement!
Post a Comment
<< Home