Read a specific column of a text file
Show older comments
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 Comments
Jon
on 26 May 2011
Walter Roberson
on 26 May 2011
Are there are a fixed number of lines of data that you want? If not then what marks the end of it?
Jon
on 26 May 2011
Walter Roberson
on 26 May 2011
We need to know what distinguishes a header line from data ?
Answers (3)
Oleg Komarov
on 26 May 2011
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);
1 Comment
Claudia Teresa Canedo Rosso
on 1 Mar 2018
Thank you!!!
Fangjun Jiang
on 26 May 2011
0 votes
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 Comment
Fangjun Jiang
on 26 May 2011
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
on 26 May 2011
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.
Categories
Find more on Large Files and Big Data in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!