Azzera filtri
Azzera filtri

extract numbers from specific lines in text file

11 visualizzazioni (ultimi 30 giorni)
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)
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});
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 Commento
Jiri Hajek
Jiri Hajek il 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...

Accedi per commentare.

Risposta accettata

Askic V
Askic V il 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))]
% read next line
tline = fgetl(fid);
% close the file
I have used the attached txt file to test this code snippet.
  2 Commenti
Askic V
Askic V il 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.

Accedi per commentare.

Più risposte (0)




Community Treasure Hunt

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

Start Hunting!

Translated by