MATLAB Answers

How can I extract a certain numerical value from a text file?

1 view (last 30 days)
Matt Waters
Matt Waters on 18 Nov 2019
Commented: Matt Waters on 18 Nov 2019
I have run a model in a different program which has produced a large number of .txt files of output data.
I would like Matlab to open each file in turn and extract the value underneath "RF2" which is -4.2694476E+08 in the example below:
THE FOLLOWING TABLE IS PRINTED FOR NODES BELONGING TO NODE SET ASSEMBLY_SET-RF
NODE FOOT- RF1 RF2 RM3
NOTE
1 -1.3405922E+07 -4.2694476E+08 0.0000000E+00
MAXIMUM -1.3406E+07 -4.2694E+08 0.000
AT NODE 1 1 1
The number of interest is on Line 4379 of every text file. I have no problems getting the Matlab code to open each file, but I can't seem to get it to extract the correct number. I would like to jump to Line 4379, get the program to disregard the 1 and the -1.3405922E+07 and ONLY take the -4.2694476E+08. The value of this number of interest is different for each file so I can't just get MATLAB to search for "-4.2694476E+08" each time. The number is ALWAYS in the same place for each of the files.
Would anyone be able to point me to a way of getting MATLAB to extract this number? Many thanks

Accepted Answer

Jeremy
Jeremy on 18 Nov 2019
Edited: Jeremy on 18 Nov 2019
I have written a similar function - something along the lines of
fopen(fid)
while feof ~= 1
str = fgetl(fid);
if strcmp(str,'string of the previous line that never changes') == 1
% The previous two lines will sift through the code line by line
% and stop when it gets to the line above the data I want
str = fgetl(fid);
[s1 s2] = strtok(str);
[s3 s4] = strtok(s2);
[s5 s6] = strtok(s4);
% strtok will break the line apart word by word
data = str2double(s5); % when you have the number you want, convert it from a string
% If the line your number is on only has numerical data, just use fscanf
data = fscanf(fid,'%e',4)
end
end
fclose(fid)
Maybe there is a more efficient way to do this. But for output files that are not formatted well for functions like readtable, this was the way I did it in college
You can just use fscanf if the line you need to read only has numerical data. Or sscanf to take a string out of the way and then fscanf to read the numbers.

More Answers (0)

Tags

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!