Extracting numbers from a txt file
23 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Ben Smith
el 17 de Jun. de 2022
Comentada: Ben Smith
el 17 de Jun. de 2022
I am struggling to extract all the numbers i need to out of a .txt file.
The file goes
# File created = Thursday, June 16, 2022 2:47:40 PM BST
# Data set = "testdata" 515 1 "C:\Users\ben\data"
# Spectral Region:
# F1LEFT = 13.912019729614258 ppm. F1RIGHT = -13.912050717676049 ppm.
# F2LEFT = 32.79998016357422 ppm. F2RIGHT = -17.17222595626548 ppm.
#
# NROWS = 512 ( = number of points along the F1 axis)
# NCOLS = 2048 ( = number of points along the F2 axis)
#
# In the following ordering is from the 'left' to the 'right' limits!
# Lines beginning with '#' must be considered as comment lines.
#
# row = 0
163.60546875
.
.
.
The ... is the other 512*2048 numbers.
raw = 'testdata.txt';
raw = readmatrix(raw);
Y = zeros(512,2048);
for i = 1:512
blockstart =2048*(i-1)+i;
blockend = 2048+blockstart-1;
Y(i,:) = raw(blockstart:blockend,1);
end
I currently use the above code to extract the long number chain into the rows and columns it should be. However, i dont know how to extract F1LEFT/RIGHT or F2LEFT/RIGHT or the values for NROWS/NCOLS. Currently i manually type them into their corresponding variable in my code. I tried the route of using strfind and extracting them like that but i couldnt get it to work. Any suggestions?
0 comentarios
Respuesta aceptada
Karim
el 17 de Jun. de 2022
If the header will always use the same structure, you can try something like the code below.
Hope it helps, best regards
% link to the text file
fileID = fopen('Example.txt');
% read the whole file, interpret each line as a string
MyText = textscan(fileID, '%s%[^\n\r]', 'Delimiter', '', 'WhiteSpace', '', 'ReturnOnError', false);
% convert the cell array into a string array, for easier indexing
MyText = string(strtrim(MyText{1}));
% Get specific data
currLine = contains(MyText, "F1LEFT");
currLine = split(MyText(currLine),' ');
F1LEFT = str2double( currLine(4) )
F1RIGHT = str2double( currLine(8) )
currLine = contains(MyText, "F2LEFT");
currLine = split(MyText(currLine),' ');
F2LEFT = str2double( currLine(4) )
F2RIGHT = str2double( currLine(8) )
currLine = contains(MyText, "NROWS");
currLine = split(MyText(currLine),' ');
NROWS = str2double( currLine(4) )
currLine = contains(MyText, "NCOLS");
currLine = split(MyText(currLine),' ');
NCOLS = str2double( currLine(4) )
% now get the data
raw = readmatrix('Example.txt');
raw = reshape(raw,NROWS,NCOLS);
size(raw)
Más respuestas (0)
Ver también
Categorías
Más información sobre Data Type Conversion en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!