Read 1.0 as 1.0 with fscanf(fid, '%f').
8 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Dyuman Joshi
le 13 Juin 2023
Please attach the text file and your code. Use the paperclip button to do so.
Stephen23
le 13 Juin 2023
"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.
Réponse acceptée
Walter Roberson
le 13 Juin 2023
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 commentaire
Walter Roberson
le 13 Juin 2023
%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
Voir également
Catégories
En savoir plus sur Text Data Preparation dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!