4
votes

When using MATLAB through the GUI, I can interrupt a computation by pressing Ctrl-C.

Is there a way to do the same programmatically when using MATLAB through the MATLAB Engine C API?

On Unix systems there is a solution: send a SIGINT signal. This will not kill MATLAB. It'll only interrupt the computation. I am looking for a solution that works on Windows.


Clarifications (seeing that the only answerer misunderstood):

I am looking for a way to interrupt any MATLAB calculation, without having control over the MATLAB code that is being run. I'm looking for the programmatic equivalent of pressing Ctrl-C in at the MATLAB command window, on Windows systems. This is for a Mathematica-MATLAB interface: I need to forward interrupts from Mathematica to MATLAB. As mentioned above, I already have a working implementation on Unix; this question is about how to do it on Windows.

2

2 Answers

1
votes

One way would be to make the MATLAB Engine session visible, prior to executing long computations. That way if you want to interrupt execution, you just bring the visible command window into focus and hit Ctrl-C.

This can be done using the engSetVisible function

Here is a quick example I tried using MATLAB COM Automation. The process should be similar since MATLAB Engine is implemented using COM on Windows (pipes are used on Unix instead).

The scripting is done in Powershell:

# create MATLAB automation server
$m = New-Object -ComObject matlab.application
$m | Get-Member

# make the command window visible
$m.Visible = $true

# execute some long computation: pause(10)
$m.Feval('disp', 0,[ref]$null, 'Press Ctrl-C to interrupt...')
$m.Feval('pause', 0,[ref]$null, 10)

# close and cleanup
$m.Quit()
$m = $null
Remove-Variable m

During the pause, you can break it by hitting Ctrl+c in the command window:

cmd-window

0
votes

There isn't a direct way: all of those routines have to be unwound and their workspaces cleaned up, which might invoke exit handlers, and so on.

The closest I can think of is to have your main routine have a try/catch and then when you wish to abort, error() the particular string that the catch is keyed for, and when you detect it, bail out cleanly from your main routine.