MATLAB: How to export a function as a Python package and use it in Python

exportfunctionlibraryMATLABpackagepython

I have used Library Compiler to create a Python package. I am able to import the package in Python interpreter, but I am not sure how to call the function from the package.
How can I call functions from the package?

Best Answer

Below is a short guide on how to do it with a sample function "makesqr.m" which is attached to this answer.
Compiling the library
Compile the attached sample file "makesqr.m" with the following MATLAB command:
>> mcc -W python:makesqr -T link:lib -v makesqr.m
Install MATLAB Runtime (MCR)
Read "readme.txt", it mentions to install MATLAB Runtime (MCR) using "mcrinstaller". Ensure that the MCR is available in the PATH environmental variable, it should be similar to "C:\Program Files\MATLAB\MATLAB Runtime\v97\runtime\win64".
Set up the Python environment
To do that it is necessary to install "pysdk" package, which is MATLAB Runtime for Python. Open command prompt, go to the directory of "matlabroot/toolbox/compiler_sdk/pysdk_py" (replace "matlabroot" with the path to your MATLAB) and install the Python package:
python setup.py install
Then in the command prompt, go the directory which contains "makesqr.m". This directory also contains "setup.py" and the actual compiled Python package "MagicSquarePkg". Stay in this directory and install the compiled Python package:
python setup.py install
Finally the example can be run in Python
Then you can use Python to interpret "example.py" which is attached to this answer.
python example.py
It outputs the following:
[[17.0,24.0,1.0,8.0,15.0],[23.0,5.0,7.0,14.0,16.0],[4.0,6.0,13.0,20.0,22.0],[10.0,12.0,19.0,21.0,3.0],[11.0,18.0,25.0,2.0,9.0]]
Samples can be generated
Starting with MATLAB R2019a release, it is possible to provide samples to the library compiler. Then compiler will generate these sample files in Python. These are MATLAB scripts which use the exported function, e.g. "makesqr". For more information, please see the documentation page in https://www.mathworks.com/help/compiler_sdk/gs/create-a-python-application-with-matlab-code.html#mw_c9db15a0-f2ee-478b-8014-b31e5b271ebc.
Explanation of example.py
The "example.py" starts by importing the compiled package "MagicSquarePkg" and also the runtime package "matlab".
Then it initializes the package, and allows calling the compiled function "makesqr". In order to call it with correct parameters, a variable with a correct data type is created using "matlab" package. At the end the initialized package is terminated.
import MagicSquarePkg
import matlab
my_MagicSquarePkg = MagicSquarePkg.initialize()
xIn = matlab.double([5.0], size=(1, 1))
yOut = my_MagicSquarePkg.makesqr(xIn)
print(yOut, sep='\n')
my_MagicSquarePkg.terminate()