How can I skip lines when loading a text file?
Afficher commentaires plus anciens
Is there a way to use load to load a text file but skip a few lines which contain headers and other info and just load numerical data in columns that come after the headers?
Réponses (1)
Sven
le 1 Fév 2012
0 votes
Hi Baba, try importdata:
importdata(FILENAME, DELIM, NHEADERLINES) loads data from ASCII file FILENAME, reading numeric data starting from line NHEADERLINES+1.
5 commentaires
Baba
le 1 Fév 2012
Sven
le 1 Fév 2012
Yes, that's the default behaviour of importdata. Copied from the help:
Using a text editor, create a space-delimited ASCII file with column headers called myfile.txt:
Day1 Day2 Day3 Day4 Day5 Day6 Day7
95.01 76.21 61.54 40.57 5.79 20.28 1.53
23.11 45.65 79.19 93.55 35.29 19.87 74.68
60.68 1.85 92.18 91.69 81.32 60.38 44.51
48.60 82.14 73.82 41.03 0.99 27.22 93.18
89.13 44.47 17.63 89.36 13.89 19.88 46.60
Import the file, specifying the space delimiter and the single column header, and view columns 3 and 5:
M = importdata('myfile.txt', ' ', 1);
for k = [3, 5]
disp(M.colheaders{1, k})
disp(M.data(:, k))
disp(' ')
end
Sven
le 1 Fév 2012
In the MATLAB docs the above data has multiple spaces between some of the data.
Shania Hurst
le 7 Nov 2016
Modifié(e) : Shania Hurst
le 7 Nov 2016
Using importdata with nheaderlines specified works for almost every file for me, but for some reason, I have one file that instead of skipping the first 20 lines as I want, instead imports ONLY the first 20 lines. I have no idea what would cause this to happen, does any one know of any circumstance in which this would happen? The file is a .txt file and has nearly 85k lines of data. The command I used is d = importdata('data.txt',' ',20);
Walter Roberson
le 7 Nov 2016
Shania Hurst, I suggest you consider using readtable() with HeaderLines . (readtable() might even be able to figure out for itself how many header lines are there.)
Catégories
En savoir plus sur Text Files dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!