Borrar filtros
Borrar filtros

How to truncate textscan reading

1 visualización (últimos 30 días)
ES_Thorny
ES_Thorny el 29 de Jul. de 2019
Editada: dpb el 1 de Ag. de 2019
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

Respuesta aceptada

dpb
dpb el 29 de Jul. de 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 comentarios
ES_Thorny
ES_Thorny el 1 de Ag. de 2019
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 el 1 de Ag. de 2019
Editada: dpb el 1 de Ag. de 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...

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by