Read a specific column of a text file

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

Just to be clear my text file looks something like this:
headers
data
headers
DATA I WANT TO READ
more headers
more data
How do I ignore the data that comes before and after the data I want to read?
Are there are a fixed number of lines of data that you want? If not then what marks the end of it?
no the number of lines aren't fixed. The header for the next section of data marks the end of the data.
We need to know what distinguishes a header line from data ?

Sign in to comment.

Answers (3)

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 on 26 May 2011
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

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.

Sign in to comment.

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

Asked:

Jon
on 26 May 2011

Community Treasure Hunt

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

Start Hunting!