Extracting numbers from a text file
Show older comments
Hi I am looking to extract the numbers 6249, 6249, 1.05785E+03, 6250, 1.05207E+03 from the following which is an excerpt from a text file:
Element S.Max. Prin
Label @Loc 1
---------------------------------
*6249 1.05785E+03
6250 1.05207E+03*
Minimum 1.05207E+03
At Element 6250
Maximum 1.05785E+03
At Element 6249
I have written a code which successfully extracts the min and max and was trying to modify that code to extract the previously mentioned numbers but I am not getting the required results. The code I am currently using is:
fid = fopen('Results.txt','rt'); %open the file
while isempty(findstr(line,'---------------------------------')),
line=fgetl(fid);
end
while isempty(findstr(line,'Minimum')),
line=fgetl(fid);
MinH1 = sscanf(line,' %f %f')
end
any advice would be greatly appreciated
3 Comments
Henry Giddens
on 8 Sep 2016
Edited: Henry Giddens
on 8 Sep 2016
Hi
I think you have a few problems.
In the first two lines of results from the text file, there is a '*' in front of the number 6249 (and after the last one, although this is actually converted correctly with you code) which isn't taken into account in the sscanf line. The string '*6249' cant be converted to a number using:
sscanf('*6249','%f')
You will need to take this into account when trying to convert the text to numbers. 'textscan' may be more useful for you.
Secondly, every time you loop through the while loop, the results in MinH1 are overwritten. I don't know if this is supposed to be intentional...
Finally, the sscanf function is executed on the 'Minimum' line , overwriting the results from the previous iteration. This is because you check the condition of the previous line before getting the new line.
dpb
on 8 Sep 2016
Are the asterisks actually in the file or are they fignewtons of your posting to illustrate the area you were interested in parsing?
Jacob Williams
on 8 Sep 2016
Answers (1)
dpb
on 8 Sep 2016
Presuming the asterisks aren't actually in the file,
fid=fopen('Results.txt','rt'); %open the file
data=cell2mat(textscan(fid,'%2f',2,'headerlines',3,'collectoutput',1));
should do the trick
If they are there, you'll need to write explicit format string incorporating them as literals to skip them.
2 Comments
Jacob Williams
on 8 Sep 2016
dpb
on 8 Sep 2016
You didn't answer the questions regarding the file format...
Categories
Find more on Text Data Preparation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!