Skip to content

Instantly share code, notes, and snippets.

@bastibe
Created March 13, 2017 15:23
Show Gist options
  • Save bastibe/580406a2b41a5af2080f0971b725a70f to your computer and use it in GitHub Desktop.
Save bastibe/580406a2b41a5af2080f0971b725a70f to your computer and use it in GitHub Desktop.
IPython magic to call Matlab using Transplant
import os
import sys
sys.path.append(os.path.dirname(os.path.realpath(__file__))+'/transplant')
from transplant_master import Matlab, TransplantError
from IPython.display import HTML, Image, display
from IPython import get_ipython
_matlab = Matlab()
def matlab(line, cell=None):
global _matlab
if _matlab is None or 'restart' in line:
_matlab = Matlab()
if cell is None:
return
try:
_matlab.evalin('base', cell, nargout=0)
except TransplantError as err:
if len(err.stack) > 1:
trace = ('Error using <a href="file://{file}">{name}</a>'
' (line {line})<br>'.format(**err.stack[0])
+ err.original_message + '<br>')
for frame in err.stack[1:-1]:
with open(frame['file']) as f:
line = f.readlines()[frame['line']-1]
trace += ('<br>Error in <a href="file://{file}">{name}</a>'
' (line {line})<br>'.format(**frame)
+ line)
else:
trace = err.original_message
display(HTML('<div style="color:darkred">'+
trace+'</div>'))
if 'inline' in line:
figures = _matlab.get(0, 'children')
if not isinstance(figures, list):
figures = [figures]
for figure in figures:
_matlab.saveas(figure, '_temp.png', 'png')
display(Image('_temp.png', width=800))
os.remove('_temp.png')
elif 'draw' in line:
_matlab.drawnow()
_matlab.drawnow()
elif 'ui' in line:
while _matlab.length(_matlab.get(0, 'children')) > 0:
children = _matlab.get(0, 'children')
if isinstance(children, list):
_matlab.uiwait(children[0], 1)
else:
_matlab.uiwait(children, 1)
ip = get_ipython()
ip.register_magic_function(matlab, 'line_cell')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment