how do i put MATLAB complex array to python?

38 次查看(过去 30 天)
I want to python code in MATLAB.(use pyrunfile)
I can't put complex array into python.
I'm testing very simple code.
python core:(file :Test.py):
print(indat)
MATLAB(inline input):
adat=xxx
pyrunfile("./Test.py",indat=adat)
I got results under below.
Case A: input adat=1+0.1i (MATALB inline)
output (1+0.1j)
Case A is OK
Case B: input adat=[1,2,3]
output array('d', [1.0, 2.0, 3.0])
Case B is OK
Case C:input adat=[1+0.1i,2+0.2i,3+0.3i]
Output <memory at 0x000002562F9E9560>
Why?
what should i do put complex array into python?

采纳的回答

Amish
Amish 2024-7-10,5:43
Hi Yasushi,
It looks like you’re encountering an issue with passing complex arrays from MATLAB to Python using pyrunfile. The problem in Case C is likely due to how MATLAB handles complex arrays and how they are interpreted in Python.
To resolve this, you can convert the complex array in MATLAB to a format that Python can understand. Since each complex number can be represented as a tuple of its real and imaginary parts, you can you this and represent it in the form of tuples, that Python can understand. After passing it to Python, this can then be converted back to a complex array using "numpy".
Here is an example on how you can do this:
(MATLAB)
% Define the complex array
adat = [1+0.1i, 2+0.2i, 3+0.3i];
% Convert the complex array to a list of tuples
adat_tuples = arrayfun(@(x) [real(x), imag(x)], adat, 'UniformOutput', false);
% Pass the list of tuples to Python
pyrunfile('Test.py', 'indat', adat_tuples);
(Python)
import numpy as np
# Convert the list of tuples back to a complex array
indat = [complex(real, imag) for real, imag in indat]
# Print the complex array
print(indat)
Hope this helps!

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Call Python from MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by