extract numbers from specific lines in text file
14 views (last 30 days)
Show older comments
Hello,
I have a .txt file with mixed measurement data and text. There are lines with coordinates which look like like this:
(mm,mm,mm,deg): 45 250 0 0
I want to extract the numbers only. The lines are located regularly in the file at line numbers 207, 60232, 120257, etc., i.e. after every 60025 lines.
I have written the code, that reads the specific lines: (points is number of measured points and name is name of measurement file)
last_coord=(points-1)*60025+207;
coord_line=207:60025:last_coord;
coords=cell(1,points); range_coords=cell(1,points);
for i=1:points
range_coords{i}=[coord_line(i) 2 coord_line(i) 5];
coords{i}=readmatrix(name, 'Range', range_coords{i});
end
However, this code works only for first two readings of coordinates at lines 207 and 60232, for the third reading and onward I get [NaN,NaN,NaN,NaN].
I checked the file up to the sixth coordinates, the lines look the same as the example here and are located on the correct line number. Please help.
1 Comment
Jiri Hajek
on 28 Nov 2022
Hi, this behaviour could have several causes, so I'd suggest to try and debug the problem in a slightly greater detail. E.g. try to set the output typa as text by adding name-value argument to your readmatrix command. This way, you will be able to analyze the data supplied by the command...
Accepted Answer
Askic V
on 28 Nov 2022
Would something like this satisfy your need?
fid = fopen('coord.txt');
tline = fgetl(fid);
search_str = '(mm,mm,mm,deg):';
matrix = [];
while ischar(tline)
k = strfind(tline, search_str);
if ~isempty(k)
matrix = [matrix; str2num(tline(k + length(search_str) : end))]
end
% read next line
tline = fgetl(fid);
end
% close the file
fclose(fid);
I have used the attached txt file to test this code snippet.
2 Comments
Askic V
on 29 Nov 2022
Yes, but keep in mind it is not efficient, because matrix changes size on each iteration. Much better solution is to preallocate matrix at the begining. But if you don't have a lot of data, this solution could be fine also.
More Answers (0)
See Also
Categories
Find more on Get Started with MATLAB 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!