How to truncate textscan reading
1 view (last 30 days)
Show older comments
Dear all,
perhaps a simple question for you, but I don't understand properly how formatspec in textscan works.
I have to read the written value from a a TXT file, exactly written as 5.00000000159E-6. I would like to read it as 5E-6 i.e. I would like to truncate the last digits, which have no meaning.
I am using currently the format spec '%f'. How can I truncate the number in the way I want? Should I add a '%*f' specification? How should it work in my case?
Thanks for answering.
Regards,
E
0 Comments
Accepted Answer
dpb
on 29 Jul 2019
You can't on read.
Just round() the data to whatever precision you want after reading it in.
x=round(x,1,'significant');
See documentation for round() for details on syntax.
4 Comments
dpb
on 1 Aug 2019
Edited: dpb
on 1 Aug 2019
What specific documentation do you think shows that? You mean a counted %f field?
If so, what the example does not show is what happens with their example completely...
>> textscan('123.456','%7.2f')
ans =
1×1 cell array
{2×1 double}
>> ans{:}
ans =
123.4500
6.0000
>>
Probably NOT what the user expects.
'E' notation is even more surprising (or maybe not, depending upon expectations and how well one knows what C does first)...
>> d=cell2mat(textscan('1.23456E2','%9.2f'))
d =
1.0e+04 *
0.0001
4.5600
>> d(1),d(2)
ans =
1.2300
ans =
45600
>>
C really wasn't designed with numerical calculations in mind. It doesn't even support an 'e' format descriptor on input and has no provisions at all for complex numbers. Why TMW chose to not use the Fortran FORMAT model for MATLAB is understandable from the standpoint of programming ease to just use the C i/o libraries since they moved from the original FORTRAN implementation, but was a real step backwards in functionality and has cost them way more in support and hacks to work around the limitations in ML and their users in untold lost manhours trying to solve input issues, particularly the fixed-width field problem.
But, opportunity lost never to be regained...
More Answers (0)
See Also
Categories
Find more on Data Import and Export in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!