How to truncate textscan reading

1 次查看(过去 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

采纳的回答

dpb
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 个评论
ES_Thorny
ES_Thorny 2019-8-1
I accepted the answer, but in the MATLAB documentation it seems it is possible to neglect some digits also with the command textscan ... maybe it is just if the number is written in decimal notation?
dpb
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 CenterFile Exchange 中查找有关 Data Import and Export 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by