How to read specific lines from text file?
Afficher commentaires plus anciens
Hello, I have a little question. I have a text file that consists of four columns, and several lines, columns also have headers. And i woder how to read a specific line, i just want to read first line(with headers) and the third one, and export it to another file.
I'm lost and I don't know how to do this.
I'm sure that at the beginning I have to start with:
fid=fopen('filename.txt');
4 commentaires
dpb
le 12 Juin 2021
Unless the file is truly huge, just read the whole thing (readtable or one of his friends) and just keep the lines of interest will be faster and simpler to code.
Jan
le 12 Juin 2021
How do you determine, which lines you want to read? If you search for a specific value, you have to read all lines, of course. Otherwise you cannot check the contents.
Réponses (1)
Scott MacKenzie
le 13 Juin 2021
No need for a loop. Since your data are rectangular and the data in each column are of the same type, you're best option is to use readtable combined with a logical expression to identify the rows of interest:
% read your data into a MATLAB table (includes header line)
T = readtable('corr.txt');
% identify rows of interest using logical expression
rowLogical = T{:,3} == 645;
% build new table containing header and only the rows of interest
Tnew = T(rowLogical,:);
% write new data in file
writetable(Tnew, 'idk.txt');
You can get fancy with logical expressions. For example, if you want to save all rows were the value in the Y column is > 600, then change the logical expression to
rowLogical = T{:,3} > 600;
For more examples on using logical expressions, see Find Array Elements That Meet a Condition
1 commentaire
dpb
le 13 Juin 2021
And, even more convenient with the table, you get the variable names for free along with the data so you can write logical expressions like
T = readtable('corr.txt');
WantedY = 645; % use variables, don't bury "magic" numbers inline in code
outfile='idk.txt'; % ditto, now can get new file by adding an input statement, not change code
Tn=T(T.Y==WantedY,:); % Scott's logic except use variable name(*) instead of position
writetable(T,outfile)
(*) And, you can write variable names as character variables, you don't have to hardcode them, necessarily, either.
Read the documenation on the table data class and the excellent tutorial material provided on how to reference data in tables..."let me count the ways!"
Catégories
En savoir plus sur Text Data Preparation dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!