Scaning a txt file

1 view (last 30 days)
Carolina Maria Clase Sousa
Commented: Mathieu NOE on 4 Feb 2021
Hello!
I want to read specific data from several txt files (result from a AVL simulation ) and later plot that information into a table and a 3D graphic. The problem is that the information in the txt file is not "organized". I want to get the values of the Engine speed, the BMEP and BSFC. Attached is one of the 17 txt files. They are all the same, only the values change in function of the engine speed.

Accepted Answer

Mathieu NOE
Mathieu NOE on 13 Jan 2021
hello Carolina
this code will scan the file and search for the targeted variables
you can expand (add more variables) if you wish
it will retrieve associated numerical data , whatever the dimensions (width) of the data
hope it helps
Filename = 'Case_1.txt';
fid = fopen(Filename);
tline = fgetl(fid);
while ischar(tline)
if contains(tline,'Engine Speed :')
tmp = strtrim(regexp(tline, '\s+', 'split')); %split by spaces
dd = regexp(tmp,'-?[0-9]+.[0-9]+', 'match'); % extract numeric parts only inside the cell (in case of mix with text)
str_temp = strjoin( cat(2,dd{:}), ',') ; % Transform a cell array of cell arrays into string / delimiter = blank or comma
Engine_Speed = str2num(str_temp); % convert string to num
end
if contains(tline,'BMEP [bar]')
tmp = strtrim(regexp(tline, '\s+', 'split')); %split by spaces
dd = regexp(tmp,'-?[0-9]+.[0-9]+', 'match'); % extract numeric parts only inside the cell (in case of mix with text)
str_temp = strjoin( cat(2,dd{:}), ',') ; % Transform a cell array of cell arrays into string / delimiter = blank or comma
BMEP = str2num(str_temp); % convert string to num
end
if contains(tline,'BSFC [g/kWh]')
tmp = strtrim(regexp(tline, '\s+', 'split')); %split by spaces
dd = regexp(tmp,'-?[0-9]+.[0-9]+', 'match'); % extract numeric parts only inside the cell (in case of mix with text)
str_temp = strjoin( cat(2,dd{:}), ',') ; % Transform a cell array of cell arrays into string / delimiter = blank or comma
BSFC = str2num(str_temp); % convert string to num
end
tline = fgetl(fid);
end
fclose(fid);
  3 Comments
Carolina Maria Clase Sousa
It worked!!! Thanks!
Mathieu NOE
Mathieu NOE on 4 Feb 2021
Glad it helped !

Sign in to comment.

More Answers (0)

Categories

Find more on Environment and Settings in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!