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

柔情痞子 提交于 2019-11-30 16:28:52
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).

Since you know you will have 5 column labels (i.e. strings) followed by 4 numeric values followed by 5 strings (e.g. 'Sun', 'Apr', '3', '18:18:12', and '2011'), you can actually read all of your numeric data into a single N-by-4 matrix with one call to TEXTSCAN:

fid = fopen('data.text','r');                    %# Open the file
results = textscan(fid,[repmat(' %*s',1,5) ...   %# Read 5 strings, ignoring them
                        '%f %f %f %f' ...        %# Read 4 numeric values
                        repmat(' %*s',1,5)],...  %# Read 5 strings, ignoring them
                   'Whitespace',' \b\t\n\r',...  %# Add \n and \r as whitespace
                   'CollectOutput',true);        %# Collect numeric values
fclose(fid);                                     %# Close the file
results = results{1};                            %# Remove contents of cell array
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!