Use MATLAB Arrays in Python
To use MATLAB® arrays in Python®, you can either install the Python engine before running your packaged application, as described in Install MATLAB Engine API for Python, or use
import mypackage before import matlab in the following
programs.
The MATLAB Engine API for Python provides a Python package named matlab that enables you to call MATLAB functions from Python. The matlab package provides constructors to create MATLAB arrays in Python. It can create arrays of any MATLAB numeric or logical type from Python sequence types. Multidimensional MATLAB arrays are supported. For a list of other supported array types, see Pass Data Between MATLAB and Python.
Examples
Create a MATLAB array in Python, and call a MATLAB function on it. Assuming that you have a package named
mypackageand a method calledmysqrtinside the package, you can usematlab.doubleto create an array of doubles given a Python list that contains numbers. You can call the MATLAB functionmysqrtonx, and the return value is anothermatlab.doublearray as shown in the following program:import matlab import mypackage pkg = mypackage.initialize() x = matlab.double([1,4,9,16,25]) print(pkg.mysqrt(x))The output is:
[[1.0,2.0,3.0,4.0,5.0]]
Create a multidimensional array. The
magicfunction returns a 2-D array to Python scope. Assuming you have method calledmysqrtinsidemypackage, you can use the following code to call that method:import matlab import mypackage pkg = mypackage.initialize() x = matlab.double([1,4,9,16,25]) print(pkg.mymagic(6))The output is:
[[35.0,1.0,6.0,26.0,19.0,24.0],[3.0,32.0,7.0,21.0,23.0,25.0], [31.0,9.0,2.0,22.0,27.0,20.0],[8.0,28.0,33.0,17.0,10.0,15.0], [30.0,5.0,34.0,12.0,14.0,16.0],[4.0,36.0,29.0,13.0,18.0,11.0]]