This blog has moved! Redirecting...
You should be automatically redirected. If not, visit http://scrolls.mafgani.net/ and update your bookmarks.

Friday, March 02, 2007

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:


[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:

Anonymous Anonymous said...

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.

5:39 PM  
Blogger DarkKnight said...

Thanks for the comment/enhancement!

6:29 PM  

Post a Comment

<< Home