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
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