MATLAB Answers

Computing mean of Python numeric vector in MATLAB

21 views (last 30 days)
Alan Aw
Alan Aw on 11 Dec 2019
Answered: Shrinidhi KR on 7 May 2020
Hello, 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
I keep encountering the following error at the last line:
"File /Applications/, 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 another error, "TypeError: unsupported Python data type: numpy.ndarray".)
Could anyone here help to troubleshoot? Thanks in advance!

Answers (1)

Shrinidhi KR
Shrinidhi KR on 7 May 2020
Modify the code as follows:
import numpy as np
import matlab.engine
eng = matlab.engine.start_matlab()
data = np.arange(5)
data_list = data.tolist()
eng.workspace['d'] = eng.cell(data_list)
eng.workspace['foo'] = eng.eval('cellfun(@double,d)')
The data_list passed to Matlab workspace is of python list datatype which is cannot be used with mean function of Matlab, hence it throws an error saying it expects numeric or logical value.
It can be solved by converting the list to cell array and then using cellfun function to convert it to double numeric datatype which can then be passed to mean function.




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!