Converting matlab.double to python compatible format

조회 수: 31 (최근 30일)
Lyle Collins
Lyle Collins 2023년 5월 4일
댓글: Lyle Collins 2023년 5월 8일
The documentation on this page states that data of type:
MATLAB Input Argument Type —
1-by-N Vector
double (real)
Gets converted to:
Resulting Python Type
array.array('d')
Consequently, I thought this python code would work:
import matlab.engine
import array
me = matlab.engine.start_matlab()
array.array('d', me.rand(1, 2))
However, this returns:
TypeError: must be real number, not matlab.double
What is the most pythonic way to convert a standard matlab double array into a python fundamental data type? (e.g. list or array.array)

답변 (1개)

Selena Mastrodonato
Selena Mastrodonato 2023년 5월 4일
This syntax py.array.array('d', rand(1,2)) should work.
py.array.array('d', rand(1,2))
ans =
Python array: 0.6970 0.3219 Use details function to view the properties of the Python object. Use double function to convert to a MATLAB array.
Or if you want a Python list: py.list(rand(1,2))
py.list(rand(1,2))
ans =
Python list with values: [0.3941618631519793, 0.8464541453090321] Use string, double or cell function to convert to a MATLAB array.
  댓글 수: 3
Selena Mastrodonato
Selena Mastrodonato 2023년 5월 5일
Hi Lyle, thank you for providing more informations.
You could try this command: me.rand(1, 2)[0].toarray(), you'll obtain array('d', [0.8147236863931789, 0.9057919370756192]).
Instead, if you want a python list you could use numpy, so try this: numpy.array(me.rand(1, 2)[0].toarray()) and you'll obtain [0.81472369 0.90579194].
If you have a multidimensional matrix, try to iterate over it to format data as you wish.
Lyle Collins
Lyle Collins 2023년 5월 8일
Thanks @Selena Mastrodonato! Much appreciated!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by