2

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!

Amro
  • 123,847
  • 25
  • 243
  • 454
trolle3000
  • 1,067
  • 2
  • 14
  • 27

2 Answers2

2
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).

Wood
  • 729
  • 3
  • 5
  • 1
    Your implementation may still break, depending on the number of lines in the file. Thanks – eat Apr 03 '11 at 17:54
0

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
gnovice
  • 125,304
  • 15
  • 256
  • 359