extract numbers from specific lines in text file
14 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Petr Michalek
am 28 Nov. 2022
Kommentiert: Askic V
am 29 Nov. 2022
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 Kommentar
Jiri Hajek
am 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...
Akzeptierte Antwort
Askic V
am 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 Kommentare
Askic V
am 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Get Started with MATLAB finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!