Read a specific column of a text file

조회 수: 6 (최근 30일)
Jon
Jon 2011년 5월 26일
I have a text file that contains thousands of data values with a lot of headers. All I want to do is read a specific column of values that occurs about halfway through the file. How do I read the column while ignoring all the data before and after the column? The column may change in length.
  댓글 수: 4
Jon
Jon 2011년 5월 26일
no the number of lines aren't fixed. The header for the next section of data marks the end of the data.
Walter Roberson
Walter Roberson 2011년 5월 26일
We need to know what distinguishes a header line from data ?

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

답변 (3개)

Oleg Komarov
Oleg Komarov 2011년 5월 26일
For example read just the third column skipping everything else
fid = fopen(C:\...\yourfilename.txt)
data = textscan(fid, '%*s %*s %f %*[^\n]','HeaderLines',1);
fid = fclose(fid);

Fangjun Jiang
Fangjun Jiang 2011년 5월 26일
Can you try to read your text file into MS Excel and save it as .xls file or .csv file then use the xlsread() function?
  댓글 수: 1
Fangjun Jiang
Fangjun Jiang 2011년 5월 26일
Oleg and Walter's solution below should work. Walter's solution has made it generic to any number of headers and columns.
If you are doing this one time, you might want to do it interactively. click File>Import Data..., or run uiload then follow steps.

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


Walter Roberson
Walter Roberson 2011년 5월 26일
To account for the varying column number:
NumHeaders = 17; %for example
NumDataLines = 1234; %for example
ColNum = 8; %for example
fmt = [ repmat('%*s',1,ColNum-1), '%f%[^\n'] ];
fid = fopen('C:\...\yourfilename.txt', 'rt');
data = textscan(fid, fmt, NumDataLines, 'HeaderLines', NumHeader);
fclose(fid);
Then data{1} will contain the values.

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by