How can I import data selectively from a text file?

2 views (last 30 days)
I have a text file in the following format:
START filename.txt, 6.9 Mw, 14.5 km, ndata = 5496, dt = 0.010, PGA = 0.5235g, unit = g
1 0.00 -1.819686e-03
2 0.01 3.291146e-04
3 0.02 3.273409e-03
and so on
I would to like a import the third column. When i use x=filename(:,3), it obviously throws an error because of the first line. Its important that i keep the first line. I figured out a way to do it by pasting the data into an excel sheet and then importing, but i was wondering if i can somehow import directly from the text file.
Thanks!
  2 Comments
Jan
Jan on 13 Apr 2015
Please explain, what you want as output. "Keeping" the first line is not clear enough.
Amit Yalwar
Amit Yalwar on 13 Apr 2015
when i use the following code
load filename.txt
x=filename(:,3)
it returned an error due to the higher number of columns on line 1 compared to the rest of the lines. If i erased line 1, it loaded the third column just fine. The solution you posted works for me. Thanks.

Sign in to comment.

Accepted Answer

Jan
Jan on 13 Apr 2015
Edited: Jan on 13 Apr 2015
fid = fopen(filename, 'r');
if fid == -1
error('Cannot open file: %s', filename);
end
firstline = fgetl(fid);
data = fscanf(fid, '%g', [3, inf]);
fclose(fid);
Now firstline contains the first line while data contains the rest.

More Answers (0)

Categories

Find more on Data Import and Export 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!