How to truncate textscan reading
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
dpb
2019-7-29
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 个评论
dpb
2019-8-1
编辑:dpb
2019-8-1
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...
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!