Read and extract specific values from a textfile
Mostrar comentarios más antiguos
Hi, I am trying to extact values at diffrent positions from a file with different type of lines.
Example of some lines:
t= 0, CDL data, Dh 11.84, Dv -2.56, Gh 0.78, Gv 0.88
t= 2, CDL data, Dh 45.91, Dv -6.22, Gh -0.80, Gv 0.51
t= 62, CDL data, Dh 26.69, Dv -4.88, Gh -5.00, Gv 1.00
t= 124, CANT, P00, cosC 8.0000, sinC 3.0000
t= 142, CDL data, Dh -96.25, Dv -57.28, Gh 6.00, Gv -4.03
t= 1755, CANT, P00, cosC 5.0018, sinC 9.0081
t= 2022, CDL data, Dh 5.69, Dv -5.02, Gh 0.06, Gv -0.95
I want to read out vales after "Gh ", "Gv ", and "CANT, P00, cosC" and ", sinC ". .
I managed to extract time t = even if its annoying it changes position you have to account for that (no esier way to do this?), but the other ones are empty.
My code:
clear all
fileList = 'data.txt';
Gv = [];
Gh = [];
CANT = [];
t = [];
fid = fopen(fileList);
textLine = fgetl(fid);
blockCounter = 1;
while ischar(textLine)
%disp(textLine ) % Dsiplay text line in command window.
% Find time.
timeLocation = strfind(textLine, 't= ');
if timeLocation == 1
t(blockCounter) = sscanf(textLine, 't= %f')
end
timeLocation = 0;
timeLocation = strfind(textLine, 't= ');
if timeLocation == 1
t(blockCounter) = sscanf(textLine, 't= %f')
end
% Find Gv, Gh, CANT
GhLocation = strfind(textLine, 'Gh ');
if GhLocation == 1
Gh(blockCounter) = sscanf(textLine, 'Gh %f');
Gv(blockCounter) = sscanf(textLine, ', Gv %f');
% Now let's prepare for the next block.
blockCounter = blockCounter + 1;
end
CANTLocation = strfind(textLine, 'CANT, P00, ');
if CANTLocation == 1
CANT(blockCounter) = sscanf(textLine, 'CANT, P00, %f');
% Now let's prepare for the next block.
blockCounter = blockCounter + 1;
end
textLine = fgetl(fid);
end
fclose(fid);
Any help appreciated.
2 comentarios
Stephen23
el 28 de En. de 2022
@Happy PhD: please do both of these:
- upload a sample data file by clicking the paperclip button.
- show the expected output for the uploaded file.
Respuestas (1)
The numeric values below are in two matrices, you can use indexing to extract the t, Gh, etc. vectors.
format short G
str = fileread('test.txt')
tkn = regexp(str,'t=\s+(\d+)[^\n]+?Gh\s+(\S+),\s+Gv\s+(\S+)','tokens');
tGhGv = str2double(vertcat(tkn{:}))
tkn = regexp(str,'t=\s+(\d+)[^\n]+?cosC\s+(\S+),\s+sinC\s+(\S+)','tokens');
tCANT = str2double(vertcat(tkn{:}))
Categorías
Más información sobre Text Data Preparation en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!