What's the best way to read an ASCII/txt file containing a few lines of text and then the data I want to load into a matrix?

조회 수: 41 (최근 30일)
I will have files converted to something like this:
Pad 1:1 /This is what the converter writes out /Not sure if it will have the same number of comments every time /information /more text
0.0 14.666
0.2 134.567
0.3 1567.435
... ...
and so forth. I want to read only the numerical data into a matrix to later work with and prefer it to not be a hack job, and something that will consistently read in many files. Thanks!
- Mark

채택된 답변

Cedric
Cedric 2013년 10월 8일
편집: Cedric 2013년 10월 8일
If you always have the same number of header lines, use TEXTSCAN and set the parameter 'HeaderLines' to a relevant value, e.g. 2 if you have two lines of header in each file.
In the example that you provided, it seems that you have have a line of text, an empty line, and then numbers, so you should be able to work with something like:
fid = fopen( 'myFile.txt', 'r' ) ;
data = textscan( fid, '%f%f', 'HeaderLines', 2 ) ;
fclose( fid ) ;
  댓글 수: 6
Mark
Mark 2013년 10월 8일
Thank you for the help. I ended up checking for the comment delimiter and using fgetl until it hit the data. From there textscan just read the rest of the text file and only put in numbers. Thanks again
Cedric
Cedric 2013년 10월 8일
편집: Cedric 2013년 10월 8일
You're welcome, just be careful not to loose the first line of data; if it was read by FGETL, it won't be read by TEXTSCAN as the file pointer was moved by FGETL after this line. This is why I have the concatenation in my last solution.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by