pythonmatlabspydermatlab-deployment

MATLAB Python package and matlab.engine module in Anaconda Spyder


I am trying to deploy a certain function from MATLAB to Python. I used MATLAB library compiler to package the required function. I managed to do so and imported the package into my python environment (I am working on Spyder).

While trying to call the function in Python, one of the input arguments is originally a struct variable in MATLAB. Since there is no struct variables in python, I found a guide to convert a variable to MATLAB compatible struct in python. The guide requires me to install and import matlab.engine module.

This is where the troubles begin.

I succeeded in installing the matlab.engine module in anaconda. When I type

conda list

I can find:

matlabengine              23.2                     pypi_0    pypi

But when I try to import the module in Spyder:

import matlab.engine

I get the error:

ModuleNotFoundError: No module named 'matlab.engine'

This confused me. I thought that installing the module would give me access to it. I tried to import the matlab.engine module in the anaconda command prompt and it worked! For some reason Spyder has no access to it.

I continued to import my packaged module to the anaconda command prompt, and when I tried to initialize it I got:

SystemError: Error initializing MATLAB Runtime: Warning: Cannot initialize MATLAB Compiler-generated software component in MATLAB. MATLAB Compiler-generated software components cannot be used from within MATLAB.

To rule out that there is something wrong with my packaged function I restarted the anaconda prompt, imported only the packaged module and initialized it successfully. And then when I tried:

import matlab.engine

I got:

ModuleNotFoundError: No module named 'matlab.engine'

I guess my question is: What is going on?


Solution

  • You should either use a packaged MATLAB component, or use the MATLAB engine, but don’t try to mix them. If you use the MATLAB engine, just call the original MATLAB code that you packaged, no need to package stuff.

    If you want to package your MATLAB code in a Python module, so it’s usable by people without MATLAB, then make sure the inputs are simple values that can be initialized in plain Python. Write a stub function that has all the values of your struct as separate input arguments, combines all those values into a struct, and then calls the actual function.