extract numbers from specific lines in text file

14 次查看(过去 30 天)
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 个评论
Jiri Hajek
Jiri Hajek 2022-11-28
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...

请先登录,再进行评论。

采纳的回答

Askic V
Askic V 2022-11-28
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 个评论
Askic V
Askic V 2022-11-29
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by