This notebook contains snippets of code that are useful when working with MATLAB in IPython Notebooks.
Displaying images from MATLAB¶
Passing variables into cells using the
%%matlab magic requires
h5py which is tricky to install. If you only need to pass in simple variables (strings) you can instead pass it in using Python string formatting and
mlab.run_code. Unfortunately, this means we don’t benefit from
pymatbridge automatically rendering figures. The class below is just a helper Python class to make it simpler to show the resulting figures from MATLAB commands.
import base64, os os.environ['http_proxy'] = '' class ImageOut(object): def __init__(self, img): with open(img) as f: data = f.read() self.image = base64.b64encode(data) def _repr_png_(self): return self.image
from pymatbridge import Matlab mlab = Matlab() mlab.start() r = mlab.run_code(''' plot([1,2,3]); ''') ImageOut( r['content']['figures'] )
Starting MATLAB on http://localhost:60894 visit http://localhost:60894/exit.m to shut down same .....MATLAB started and connected!
Pass widget variables into %%matlab magic¶
If you want to use widget controls in IPython notebooks you might find yourself wanting to pass those values into matlab cells using %%matlab magic. This snippet shows how you can use a callback function together with
interact to automatically update global vars, and then pass these into the matlab session using
Note: you need hdf5 and h5py installed for this to work
Starting MATLAB on http://localhost:60938 visit http://localhost:60938/exit.m to shut down same ...MATLAB started and connected!
def widget_callback(**kwargs): for k,v in kwargs.items(): globals()[k] = v
Note: We define the variable first above, and pass the output var in as an default value. This means the widget wont reset if the cell is re-run, but will instead keep the current value. To reset the value just run the cell above.
from IPython.html.widgets import interact from IPython.html import widgets i = interact(widget_callback, myvar=widgets.IntSliderWidget(min=1, max=50, step=1, value=myvar, description="Reference spc:"), )
%%matlab -i myvar myvar
myvar = 13
- Pathomx: Example Analysis
- Partial Least Squares Discriminant Analysis (PLS-DA)
- Getting Started with Pathomx
- Speed up MATLAB on MacOS X
- Gremlins in the Machine: Creating custom tools for the Pathomx data analysis platform
Get my latest Python projects, tips & tutorials direct to your Inbox.