필터 지우기
필터 지우기

Read 1.0 as 1.0 with fscanf(fid, '%f').

조회 수: 8 (최근 30일)
SHC
SHC 2023년 6월 13일
편집: SHC 2023년 6월 14일
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
Dyuman Joshi 2023년 6월 13일
Please attach the text file and your code. Use the paperclip button to do so.
Stephen23
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
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
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)
ans = 0
%crosscheck
dbtype(filename)
1 1.0 2.1 3.0
%read data
format short G
fid = fopen(filename, 'r');
result = fscanf(fid, '%f')
result = 3×1
1 2.1 3
class(result)
ans = 'double'
class(result(1))
ans = 'double'
format short eng
result
result = 3×1
1.0000e+000 2.1000e+000 3.0000e+000
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)
ans = 3×16 char array
'3ff0000000000000' '4000cccccccccccd' '4008000000000000'
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개)

SHC
SHC 2023년 6월 14일
편집: SHC 2023년 6월 14일
Because what I wanted was a string not the number, so I used sprintf to get the desired result.
format short G
fid = fopen('test.txt', 'r');
result = fscanf(fid, '%f');
fclose(fid)
result(1)
a = sprintf('%.1f', result(1))
a =
'1.0'

카테고리

Help CenterFile Exchange에서 Text Data Preparation에 대해 자세히 알아보기

태그

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by