Read a specific column of a text file

5 Ansichten (letzte 30 Tage)
Jon
Jon am 26 Mai 2011
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 Kommentare
Jon
Jon am 26 Mai 2011
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 am 26 Mai 2011
We need to know what distinguishes a header line from data ?

Melden Sie sich an, um zu kommentieren.

Antworten (3)

Oleg Komarov
Oleg Komarov am 26 Mai 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);

Fangjun Jiang
Fangjun Jiang am 26 Mai 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 Kommentar
Fangjun Jiang
Fangjun Jiang am 26 Mai 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.

Melden Sie sich an, um zu kommentieren.


Walter Roberson
Walter Roberson am 26 Mai 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.

Community Treasure Hunt

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

Start Hunting!

Translated by