MATLAB: Convert a txt file with complex numbers to a matrix

complex numberload read txt

Hello, I would like to read this file into Matlab, but give an error.
the file is something like that:
0,0,0,1,8250,0.2,1,"96117.399999999994+12805.799999999999i" 0.49,0,0,3,8250,0.2,1,"99047.899999999994+13444.200000000001i"
and the error are: Unknown text on line number 1 of ASCII file Input_WY_data.dat "96117.399999999994+12805.799999999999i"
or Error using dlmread (line 147) Mismatch between file and format character vector. Trouble reading 'Numeric' field from file (row number 1, field number 8) ==> "96117.399999999994+12805.799999999999i"\n
Someone knows how can I read without the "?

Best Answer

Why did someone put double quotes around perfectly good complex numbers?
Here are three ways to approach the problem:
1. use dlmread and specify the delimiter:
M = dlmread('temp2.csv',',"');
2. remove double quotes using MATLAB:
% Read text, get rid of double quotes, save text:
str = fileread('temp1.csv');
str = strrep(str,'"','');
[fid,msg] = fopen('temp2.csv','w');
assert(fid>=3,msg)
fprintf(fid,'%s',str);
fclose(fid);
% Read numeric data (including complex values)
M = csvread('temp2.csv');
2. double quotes as delimiters:
opt = {'Delimiter',',"','MultipleDelimsAsOne',true,'CollectOutput',true};
fmt = repmat('%f',1,8);
[fid,msg] = fopen('temp1.csv','rt');
assert(fid>=3,msg)
C = textscan(fid,fmt,opt{:});
fclose(fid);
M = C{1};