Computing mean of Python numeric vector in MATLAB
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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
eng.eval('mean(foo)')
I keep encountering the following error at 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 another error, "TypeError: unsupported Python data type: numpy.ndarray".)
Could anyone here help to troubleshoot? Thanks in advance!
0 Commenti
Risposte (1)
Shrinidhi KR
il 7 Mag 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)')
print(eng.eval('mean(foo)'))
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.
0 Commenti
Vedere anche
Categorie
Scopri di più su Call MATLAB from Python in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!