- upload a sample data file by clicking the paperclip button.
- show the expected output for the uploaded file.
Read and extract specific values from a textfile
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Stephen23
le 28 Jan 2022
@Happy PhD: please do both of these:
Réponses (1)
Stephen23
le 28 Jan 2022
Modifié(e) : Stephen23
le 28 Jan 2022
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{:}))
0 commentaires
Voir également
Catégories
En savoir plus sur Text Data Preparation dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!