Extracting numbers from a text file
이전 댓글 표시
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
Henry Giddens
2016년 9월 8일
편집: Henry Giddens
2016년 9월 8일
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
2016년 9월 8일
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
2016년 9월 8일
답변 (1개)
dpb
2016년 9월 8일
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
Jacob Williams
2016년 9월 8일
dpb
2016년 9월 8일
You didn't answer the questions regarding the file format...
카테고리
도움말 센터 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!