필터 지우기
필터 지우기

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

조회 수: 8 (최근 30일)
Denis Perotto
Denis Perotto 2018년 8월 6일
댓글: Denis Perotto 2018년 8월 6일
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
Stephen23
Stephen23 2018년 8월 6일
@Denis Perotto: does the file always have four columns of numeric data? Or can the number of columns change?
Denis Perotto
Denis Perotto 2018년 8월 6일
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.

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2018년 8월 6일
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.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

제품


릴리스

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by