How to read a text file having strings and numeric data?

10 views (last 30 days)
I have a 'txt' file with strings and numbers like this:
PATH VARIABLE SUMMARY
S UY EPTOX EPTOZ
0.0000 -0.53581E-01 0.10604E-03-0.32000E-04
1.0000 -0.54013E-01 0.10653E-03-0.32322E-04
2.0000 -0.54450E-01 0.10702E-03-0.32638E-04
3.0000 -0.54893E-01 0.10747E-03-0.32752E-04
etc...
PATH VARIABLE SUMMARY
S UY EPTOX EPTOZ
42.000 -0.76168E-01 0.12966E-03-0.22470E-04
43.000 -0.76806E-01 0.13042E-03-0.21690E-04
44.000 -0.77447E-01 0.13119E-03-0.20854E-04
etc...
I need to read only numeric data as an array. I don't foreknow number of string lines in file and their format (!). I tried 'dlmread', but it terminates with an error.
In Mathcad, for example, I use 'READPRN', which ignores any text and reads numeric data from file without any problems. So now I have to read my files in Mathcad, export them to EXCEL and then read in MATLAB with 'xlsread'.
  4 Comments
Stephen23
Stephen23 on 6 Aug 2018
@Denis Perotto: does the file always have four columns of numeric data? Or can the number of columns change?
Denis Perotto
Denis Perotto on 6 Aug 2018
Well, I have about 14 files with constant number of columns (3, 4 or 5). I do foreknow this number, so I can modify my code for each case.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 6 Aug 2018
out = [];
[fid,msg] = fopen('test0.txt','rt');
assert(fid>=3,msg)
while ~feof(fid)
str = fgetl(fid)
vec = sscanf(str,'%f',[1,Inf])
num = numel(vec);
if num
out(end+1,1:num) = vec;
end
end
fclose(fid);
Giving this:
>> out
out =
0.00000 -0.05358 0.00011 -0.00003
1.00000 -0.05401 0.00011 -0.00003
2.00000 -0.05445 0.00011 -0.00003
3.00000 -0.05489 0.00011 -0.00003
42.00000 -0.07617 0.00013 -0.00002
43.00000 -0.07681 0.00013 -0.00002
44.00000 -0.07745 0.00013 -0.00002
The test file is attached.

More Answers (0)

Products


Release

R2016b

Community Treasure Hunt

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

Start Hunting!