MATLAB: how to read every Nth line of a text file?

20,917
fid = fopen('data.text')
while ~feof(fid)
  results = textscan(fid, '%f %f %f %f', 1,'headerlines',1);
  //Processing...

  for i = 1:2
    fgets(fid)
  end
end

fgets reads until the end of a line, and returns the text on that line. So, just call it twice to skip two lines (discarding the return value of the function).

Share:
20,917

Related videos on Youtube

trolle3000
Author by

trolle3000

Physics and math student. Unicorn courtesy of balpha on meta.stackoverflow.com.

Updated on August 29, 2020

Comments

  • trolle3000
    trolle3000 over 3 years

    I have some data that's formatted as follows:

    dtau     E_av        variance    N_sims      Time
    0.001   0.497951    0.000211625 25      Sun Apr  3 18:18:12 2011
    
    dtau     E_av        variance    N_sims      Time
    0.002   0.506784    0.000173414 25      Sun Apr  3 18:18:58 2011
    

    Now I want to read the first 4 columns (anything but the time) of every third line into MATLAB using textscan; after using fid = fopen('data.text'), I basically have to loop this:

    results = textscan(fid, '%f %f %f %f', 1,'headerlines',1);
    

    Any ideas? Cheers!

  • eat
    eat about 13 years
    Your implementation may still break, depending on the number of lines in the file. Thanks

Related