How to read every nth line of a file

28 views (last 30 days)
time,n0v_soma,n1v_soma,n2v_soma,n3v_dend
0,-70,-70,-66.5,-66.5
0.027,-69.9703,-69.9794,-66.4966,-66.4966
0.054,-69.9685,-69.9533,-66.4933,-66.4933
0.081,-69.9283,-69.9322,-66.49,-66.4899
0.108,-69.9588,-69.9385,-66.4866,-66.4866
0.135,-69.9422,-69.8965,-66.4833,-66.4833
0.162,-69.9058,-69.8943,-66.48,-66.48
0.189,-69.8465,-69.8618,-66.4767,-66.4766
0.216,-69.8505,-69.8258,-66.4734,-66.4733
0.243,-69.7855,-69.8011,-66.4701,-66.47
0.27,-69.7913,-69.7594,-66.4668,-66.4667
0.297,-69.7228,-69.7291,-66.4636,-66.4634
0.324,-69.6841,-69.7006,-66.4603,-66.4601
0.351,-69.6907,-69.7157,-66.4571,-66.4569
0.378,-69.6584,-69.7295,-66.4538,-66.4536
0.405,-69.5766,-69.7279,-66.4506,-66.4503
0.432,-69.5668,-69.6756,-66.4474,-66.447
0.459,-69.5396,-69.6777,-66.4442,-66.4437
0.486,-69.511,-69.6717,-66.441,-66.4404
0.513,-69.4808,-69.6523,-66.4378,-66.4371
0.54,-69.4632,-69.6325,-66.4346,-66.4339
0.567,-69.4605,-69.6169,-66.4314,-66.4306
0.594,-69.4398,-69.6346,-66.4282,-66.4273
0.621,-69.4638,-69.6245,-66.4251,-66.424
0.648,-69.4429,-69.5968,-66.4219,-66.4207
0.675,-69.4134,-69.5639,-66.4187,-66.4174
0.702,-69.3973,-69.5655,-66.4156,-66.4141
0.729,-69.3973,-69.5668,-66.4125,-66.4108
0.756,-69.3611,-69.6189,-66.4093,-66.4075
My file looks something like this. I want to read every 10th line of this and skip the header.
so
my array should look like this
C=[0.216,-69.8505,-69.8258,-66.4734,-66.4733;0.486,-69.511,-69.6717,-66.441,-66.4404;0.756,-69.3611,-69.6189,-66.4093,-66.4075];
and so on

Accepted Answer

Walter Roberson
Walter Roberson on 13 Jul 2016
Sometimes it is just easier to loop reading and discarding most lines and storing the ones you want.
But if you need it done in one step:
per_line = 5;
every_nth_line = 10;
fmt = [repmat('*%f', 1, per_line*(every_nth_line-1)), repmat('%f', 1, per_line)];
fid = fopen('YourFile.txt', 'rt');
datacell = textscan(fid, fmt, 'delimiter', ',\n', 'HeaderLines', 1, 'CollectOutput', 1);
fclose(fid);
C = datacell{1};
  3 Comments
Walter Roberson
Walter Roberson on 13 Jul 2016
Sorry, minor typo. Change
fmt = [repmat('*%f', 1, per_line*(every_nth_line-1)), repmat('%f', 1, per_line)];
to
fmt = [repmat('%*f', 1, per_line*(every_nth_line-1)), repmat('%f', 1, per_line)];
Shivik Garg
Shivik Garg on 14 Jul 2016
Edited: Shivik Garg on 14 Jul 2016
It worked. Thanks a lot for you help

Sign in to comment.

More Answers (0)

Categories

Find more on Large Files and Big Data in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!