Read 1.0 as 1.0 with fscanf(fid, '%f').
조회 수: 8 (최근 30일)
이전 댓글 표시
When I read numbers from a text file using fscanf(fid, '%f'), MATLAB always returns the numbers as intergers if the numbers are ending with .0 (like 1.0 to 1) when format shortG is used.
They are same values, but I need the numbers as they are in the file for some reason.
Below is the content of test.txt as an example:
"1.0 2.1 3.0"
And if I run this MATLAB code:
format short G
fid = fopen('test.txt', 'r');
result = fscanf(fid, '%f')
The result is
result =
1
2.1
3
댓글 수: 2
Dyuman Joshi
2023년 6월 13일
Please attach the text file and your code. Use the paperclip button to do so.
Stephen23
2023년 6월 13일
"but I need the numbers as they are in the file for some reason."
No numeric class stores formatting information.
You are confusing how numeric data are displayed with what data are actually stored in memory. Not the same things at all.
채택된 답변
Walter Roberson
2023년 6월 13일
This is not possible in MATLAB. "format short g" instructs matlab to use specific output rules for display that are not compatible with your goals.
Note that it is only display that is affected. %f format reads as double precision. The values are double precision in storage. The "format" command chooses between rules for how different data types are to be displayed
You should probably be controlling the display exactly how you want it by using fprintf or compose()
댓글 수: 1
Walter Roberson
2023년 6월 13일
%create file
S = "1.0 2.1 3.0";
filename = fullfile(tempdir, "test.txt");
fid = fopen(filename, 'w');
fprintf(fid, "%s\n", S);
fclose(fid)
%crosscheck
dbtype(filename)
%read data
format short G
fid = fopen(filename, 'r');
result = fscanf(fid, '%f')
class(result)
class(result(1))
format short eng
result
Observe that the class() of result(1) is double, not one of the integer classes. Observe that if you change the format then how the data displays changes.
num2hex(result)
If you care to look up the details of the representation of IEEE 754 Double Precision floating point numbers, you will see that the 3ff followed by all zeros is the exact floating point representation of 1.0
추가 답변 (1개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Text Data Preparation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!