demos matlab

Snippets (MATLAB)

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.

python
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
python
from pymatbridge import Matlab
mlab = Matlab()
mlab.start()
r = mlab.run_code('''
plot([1,2,3]);
''')
ImageOut( r['content']['figures'][0] )
python
Starting MATLAB on http://localhost:60894
 visit http://localhost:60894/exit.m to shut down same
.....MATLAB started and connected!

png

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 -i.

Note: you need hdf5 and h5py installed for this to work

python
%load_ext pymatbridge
python
Starting MATLAB on http://localhost:60938
 visit http://localhost:60938/exit.m to shut down same
...MATLAB started and connected!
python
def widget_callback(**kwargs):
    for k,v in kwargs.items():
        globals()[k] = v
python
myvar=5

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.

python
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:"),
)
python
%%matlab -i myvar
myvar
python
myvar =
                   13
python

Over 10,000 developers have bought Create GUI Applications with Python & Qt!
Create GUI Applications with Python & Qt6
More info Get the book

Downloadable ebook (PDF, ePub) & Complete Source code

To support developers in [[ countryRegion ]] I give a [[ localizedDiscount[couponCode] ]]% discount on all books and courses.

[[ activeDiscount.description ]] I'm giving a [[ activeDiscount.discount ]]% discount on all books and courses.