how do i put MATLAB complex array to python?
28 views (last 30 days)
Show older comments
Yasushi Yamakawa
on 10 Jul 2024
Commented: Yasushi Yamakawa
on 10 Jul 2024
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?
0 Comments
Accepted Answer
Amish
on 10 Jul 2024
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!
More Answers (0)
See Also
Categories
Find more on Call Python from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!