How can the generated complex numbers represented by j instead of i?
12 views (last 30 days)
Show older comments
I need to import data into python. However, imaginary number does not use i in python
2 Comments
Answers (2)
the cyclist
on 18 Jun 2020
If z is your complex variable in MATLAB, save the real part
real(z)
and the imaginary part
imag(z)
separately, and re-construct them in python.
0 Comments
Jason Ellison
on 25 Apr 2023
Hi!
I had this problem recently too. I fixed it in Python instead of MATLAB. Here is my solution.
# this one imports a csv and compares it to the output of the function above. This is quite painful in python.
# First, you need to open the file and read the lines into a variable.
with open('./csv_files/S2_M12_transmissionFrom1x_shiftn3_lfl2_rfl2_alpha0p5_matlab.csv') as f:
lines = f.readlines()
# initialize array
known = zeros((len(lines),), dtype='complex')
# then, in a loop, you need to
k = 0 # this will index the known array
for line in lines:
# 1. find where the 'i' character is.
m = re.search('i', line)
n = m.span()
# 2. replace 'i' with 'j'
number_in_string = line[0:n[0]]+'j'
# 3. convert to complex and put it in an array
known[k] = complex(number_in_string)
k = k+1
1 Comment
Jason Ellison
on 25 Apr 2023
I have an alternative answer in MATLAB as well ...
fid = fopen("filename.csv", 'w');
n = length(data);
for i = 1:n
if i~=n
% write all but the last line like this
fprintf(fid, '%d+%dj,',real(data(i)), imag(data(i)));
else
% on the last line, don't put a comma
fprintf(fid, '%d+%dj',real(data(i)), imag(data(i)));
end
end
fclose(fid);
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!