How to install jupyter kernel for Matlab

In this tutorial, I will describe the steps to create a kernel for Matlab on Levante. get the matlab_kernel working in Jupyterhub on Levante.

Prerequisites

  • conda environment with python 3.9

  • matlab_kernel package

  • matlab python engine (from the matlab module)

  • python bindings

Note

For some reasons, there will be no centralized kernel for Levante in jupyterhub.

Matlab release

Check this table first when you create the conda environment.

To check the available Matlab modules on Levante:

module list matlab

which (currently) returns:

  • matlab/R2021b-gcc-11.2.0

Instructions

Please follow these steps to install and enable the matlab_kernel in Jupyterhub.

1. Conda env

Create a conda environment to install matlab_kernel package.

module load python3
conda create -n matlab python=3.9
source activate matlab

2. Matlab Kernel

In the conda env:

python -m pip install matlab_kernel
python -m matlab_kernel install --user

A kernel specification kernel.json is now available under .local/share/jupyter/kernels/matlab.

You need to edit that file and change the path to python, it should point to the python from the conda environment.

{"argv": ["/home/../../.conda/envs/matlab/bin/python", "-m",

3. Python engine and bindings

I will be using Matlab R2021b

(matlab) [k@l40106 ~]$ cd /sw/spack-levante/matlab-R2021b-klsayl/extern/engines/python/
(matlab) [k@l40106 python]$ python setup.py build -b $HOME
running build
running build_py
(matlab) [k@l40106 python]$

This will create a directory lib/matlab in your home directory.

4. Move/copy the directory to the conda env

Now, you move/copy the lib/matlab into path/to/your/conda_env/lib/python3.9/site-packages/matlab

(matlab) [k@l40106 python]$ cd
(matlab) [k@l40106 ~]$ mv lib/matlab/ .conda/envs/matlab/lib/python3.9/site-packages/matlab

Note

You can delete the lib/matlab from your HOME directory if everything work!

Testing

../../_images/matlab.png
  • start jupyterhub session

  • create a new notebook with matlab kernel

  • disp('hello from MATLAB')

hello from MATLAB

Or try this notebook.

Troubleshooting

ImportError:
Matlab engine not installed:
See https://www.mathworks.com/help/matlab/matlab-engine-for-python.htm

This means you missed step 2.

References

[1] https://github.com/Calysto/matlab_kernel

[2] https://am111.readthedocs.io/en/latest/jmatlab_install.html

[3] http://www.jmlilly.net/jupyter-matlab