Borrar filtros
Borrar filtros

extract numbers from specific lines in text file

18 visualizaciones (últimos 30 días)
Petr Michalek
Petr Michalek el 28 de Nov. de 2022
Comentada: Askic V el 29 de Nov. de 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 comentario
Jiri Hajek
Jiri Hajek el 28 de Nov. de 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...

Iniciar sesión para comentar.

Respuesta aceptada

Askic V
Askic V el 28 de Nov. de 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 comentarios
Petr Michalek
Petr Michalek el 29 de Nov. de 2022
Your code works fine, thanks.
Askic V
Askic V el 29 de Nov. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Get Started with MATLAB en Help Center y File Exchange.

Productos


Versión

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by