pythonmatlabportingmatlab-engine

Computing mean of Python numeric vector in MATLAB


I am trying to compute the mean of a Python numeric vector in MATLAB. To clarify, I am using Python but am trying to rely on some MATLAB-specific functions by running MATLAB in a Python environment. I am using matlab.engine to do this:

##### (From my Python script) #####
# Simple MATLAB experiment
import numpy as np
!pip install matlab
import matlab.engine
eng = matlab.engine.start_matlab()

data = np.arange(5)
data_list = data.tolist()
eng.workspace['foo'] = data_list
eng.eval('mean(foo)')

I keep encountering the following error after the last line:

"File /Applications/MATLAB_R2018b.app/toolbox/matlab/datafun/mean.m, line 127, in mean Invalid data type. First argument must be numeric or logical."

To my understanding, this is owing to MATLAB somehow not recognizing the type of objects stored in data_list when data_list is being ported over to the engine workspace (as foo). I've tried (1) specifying the dtype when creating the object data, and (2) removing data.tolist() and porting data over directly, but both methods do not fix the issue. (Method 2 produces a different error, "TypeError: unsupported Python data type: numpy.ndarray".)

I am using MATLAB R2018b and Python 3.6.

Could anyone here help to troubleshoot? Thanks in advance!


Solution

  • When you call the MATLAB engine function, the list is being converted to a cell.

    When you pass Python® data as input arguments to MATLAB® functions, the MATLAB Engine for Python converts the data into equivalent MATLAB data types.

    As documented here.

    You can confirm that the data type is cell in MATLAB

    >>> eng.eval('class(foo)')
    'cell'
    

    Now that you know the datatype, simply convert the data:

    >>> eng.eval('mean(cell2mat(foo))')
    2.0