How to read a text file line by line?

2,156 views (last 30 days)
Jetson Ronald
Jetson Ronald on 9 Apr 2013
Edited: GreyHunter on 6 Oct 2020
I have a complicated text file,it runs row by row, first clumn is time and the next colum is corresponding acceleration, similarily it has 5 coulns of time and fivi colums of correcpoding acceleration, e.g. is givin below. How can I read this file using a matlab script?
0000 .0495 .0042 .0386 .0085 .0263 .0127 .0262 .0169 .0153
.0211 -.0079 .0254 -.0080 .0296 -.0312 .0338 -.0312 .0380 -.0545
.0423 -.0545 .0465 -.0763 .0507 -.0764 .0549 -.0996 .0592 -.0996
.0634 -.1229
Thank You
  1 Comment
Walter Roberson
Walter Roberson on 9 Apr 2013
The last line appears to have only one time/acceleration pair. Should that be treated specially? Or do you just want to matrix will times in one column and corresponding accelerations in the other?

Sign in to comment.

Answers (3)

Image Analyst
Image Analyst on 9 Apr 2013
Edited: Image Analyst on 9 Apr 2013
Use fgetl(). From the help:
Read and display the file fgetl.m one line at a time:
fid = fopen('fgetl.m');
tline = fgetl(fid);
while ischar(tline)
tline = fgetl(fid);
You might also want to look at the dlmread() function.

Ahmed A. Selman
Ahmed A. Selman on 18 Apr 2013
Try selecting one dimension a time for each line, e.g.,
time=fscanf(fID,'%g',[1 1:2:inf]);
acce=fscanf(fID,'%g',[1 2:2:inf]);
Jan on 18 Apr 2013
@Ahmed: Did you try the code? What do you expect as result of 1:2:inf? It must be a vector with infinite length, which must be stored in an infinitely large memory.
In addition, like Walter has explained already, fscanf reads the file sequentially, such that the idea of importing the variables one after the other does not match the was Matlab works.

Sign in to comment.

Ugur CAN KOR on 14 Jan 2018
How can I read this file? matlab code?
GreyHunter on 6 Oct 2020
How can I pick a specific line which is going to depend on the character?
for example. we have 2 collumns with numbers and one with characters( perhaps names) how you can pick one specific line 1 or more and store the into a matrix?

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!