how to read complex file data to matrix

4 ビュー (過去 30 日間)
vincent lin
vincent lin 2020 年 1 月 17 日
編集済み: per isakson 2020 年 1 月 18 日
I have a.txt file, with complex data. the format is
1.958138021e-02 0.64646110658609712285 + 0.093290941560866688653j
1.958139648e-02 0.32117256288141476928 - 0.061542254916540022058j
1.958141276e-02 -0.22359569118086644601 + 0.3585713533321416846j
1.958142904e-02 -0.22397218216792619261 + 0.082213621398327246803j
1.999960938e-02 0
1.999962565e-02 0
1.999964193e-02 0
1.999965820e-02 0
2.000000000e-02 0.10412797744247889731 + 0.0081123700776114041067j
There's space between + and -. how can I read this file into a matrix with seperated I part and Q part.
like
1.958138021e-02 0.64646110658609712285 0.093290941560866688653
...
1.999960938e-02 0 0
2.000000000e-02 0.10412797744247889731 0.0081123700776114041067
  2 件のコメント
stozaki
stozaki 2020 年 1 月 17 日
Could you attach a real text file?
vincent lin
vincent lin 2020 年 1 月 17 日
yes. a.txt added

サインインしてコメントする。

採用された回答

per isakson
per isakson 2020 年 1 月 17 日
Following Walter's advise
%%
chr = fileread('a.txt');
%%
chr = strrep( chr, ' + ', '+' );
chr = strrep( chr, ' - ', '-' );
cac = textscan( chr, '%f%f' );
%%
M = cat( 2, cac{1}, real(cac{2}), imag(cac{2}) );
>> M(1:3,:)
ans =
0 0.10413 0.0081124
1.6276e-08 -0.04608 -0.073765
3.2552e-08 -0.038321 0.076231
  1 件のコメント
vincent lin
vincent lin 2020 年 1 月 17 日
編集済み: per isakson 2020 年 1 月 18 日
thank you. This works and is fast. I find there's another code by reading line by line. It works but is very slow. Your method is faster
fid = fopen ('a.txt','r');
ii = 1;
while ~feof(fid)
acorrente(ii, :) = str2num(fgets(fid));
ii = ii + 1;
end
fclose(fid);
data = [real(acorrente(:,1)) real(acorrente(:,2)) imag(acorrente(:,2))];

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2020 年 1 月 17 日
Sometimes easiest is to read the file as a character vector, use regexp to remove the space around the sign of the imaginary part, and then textscan. textscan and other numeric formats can read complex values when there is no space.
Or read the file as string and regexp to change lines that do not end in j to append + 0j on them. With all lines having the same format you can easily textscan to extract real and imaginary separately.

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by