Read first lines of txt files with textread

25 visualizaciones (últimos 30 días)
Elzbieta
Elzbieta el 3 de Nov. de 2024 a las 17:05
Editada: dpb el 4 de Nov. de 2024 a las 14:20
Hello,
How to get only first 16 lines od the txt files with textread command?
field=textread(file,'%s')%,'delimiter','\n',)
Thank you
ELzbieta

Respuestas (2)

Stephen23
Stephen23 el 3 de Nov. de 2024 a las 17:36
Editada: Stephen23 el 3 de Nov. de 2024 a las 17:36
"How to get only first 16 lines od the txt files with textread command?"
As the TEXTREAD documentation explains, the optional third input specifies how many times to apply the format to the file data:
So you would specify the third input as 16:
.. = textread(filename,format,16)

dpb
dpb el 3 de Nov. de 2024 a las 17:37
Editada: dpb el 4 de Nov. de 2024 a las 14:20
N=3;
field=textread(file,'%s',N,'delimiter',newline,'whitespace','');
See textread for details of syntax including that all input parameters other than the name-value pairs must precede any named parameter. Ignoring whitespace is also probably critical; there is an example in the doc (or at least there was once't upon a time; it seems to have come and gone over the years) for the purpose.
However, would be remiss to not point out that while it's unlikely textread will ever actually be removed, it has been deprecated in favor of textscan or the other newer i/o functions such as readlines. I will agree that it is somewhat handy that textread doesn't need the extra hassle of opening and closing a file handle as does textscan and readlines doesn't have the option to only read N lines; you get the whole file. Of course, it's trivial-enough to then delete all but the wanted N and performance is likely not noticeably different unless a file were to be really, really, really big...like too big to fit in memory big.

Community Treasure Hunt

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

Start Hunting!

Translated by