> ## Content Index
> Fetch the complete content index at: https://mfitzp.ghost.io/llms.txt
> Use this file to discover other available public pages before exploring further.

# Snippets (MATLAB)
- URL: https://mfitzp.ghost.io/snippets-matlab/
- Published: 2014-05-28T00:00:00.000Z
- Updated: 2024-03-29T22:29:40.000Z
- Description: This notebook contains snippets of code that are useful when working with MATLAB in IPython Notebooks.
- Author: Martin Fitzpatrick
- Tags: #Import 2026-08-24 14:26

## 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] )

```

```
Starting MATLAB on http://localhost:60894
 visit http://localhost:60894/exit.m to shut down same
.....MATLAB started and connected!

```

![png](https://blog.martinfitzpatrick.com/static/demos/matlab-snippets/matlab-snippets_3_1.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`.

💡

You need hdf5 and h5py installed for this to work

```
%load_ext pymatbridge

```

```
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

```

```
myvar=5

```

ℹ️

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:"),
)

```

```
%%matlab -i myvar
myvar

```

```
myvar = 13

```