How can the generated complex numbers represented by j instead of i?

12 views (last 30 days)
I need to import data into python. However, imaginary number does not use i in python
  2 Comments
Stephen23
Stephen23 on 10 Jun 2020
You can save the data in a .mat file and then use numpy/scipy loadmat.
Lz Lu
Lz Lu on 18 Jun 2020
Sorry,I first need to import the data into a csv file before I can proceed to the next step

Sign in to comment.

Answers (2)

the cyclist
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.

Jason Ellison
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
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);

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!