Remove 0 from scientific notation

15 visualizaciones (últimos 30 días)
Sam Zipper
Sam Zipper el 12 de Abr. de 2013
Hi all-
Kind of a nitpicky questions, but I'm using Matlab to convert output data from one piece of software to input data in another. I have a bunch of values I need to print in the form:
1.234e56
However, Matlab adds an extra 0 after the e by default, returning:
1.234e056
Is there any way to get rid of the first zero from the notation part of the output? I feel like I must be missing something obvious...
I am using fprintf to write the data, in the form:
fprintf(fileID, '%9.4e', data(row,col));
Thanks in advance. I am using R2011a.
-sam

Respuesta aceptada

Walter Roberson
Walter Roberson el 12 de Abr. de 2013
I can predict from the question that you are using MS Windows, as Linux and OS-X do not do this.
This behavior is buried too deep in the system for there to be any easy remedy, so the easiest thing to do is to process the string afterwards to remove the 0.
s = sprintf('%9.4e', data(row,col));
s = regexprep(s, '(e[+-])0(\d\d)', '$1$2');
fwrite(fileID, s);
Note: this code assumes that row and col are scalars so that only a single value is being formatted at a time. If that is not the case, then your original format had a problem that adjacent fields would run together (even with a 2 character exponent, a .4e format requires 10 characters for positive numbers and 11 characters for negative numbers). The regexprep is safe for either two digit or three digit exponents but only if there is at least one space between adjacent numbers such as a '%9.4e ' format.
  2 comentarios
Sam Zipper
Sam Zipper el 12 de Abr. de 2013
Hi Walter-
Thanks for your help. You are correct that I was using Windows. For some reason, sprintf returns only two numbers after the e, so I didn't even need to process that string. All I had to do was add it to my fprintf arguments, like so:
fprintf(fileID, sprintf('%9.4e', data(row,col)))
Thanks again!
-sam
Walter Roberson
Walter Roberson el 12 de Abr. de 2013
fwrite() would make more sense than fprintf() if the data is already formatted into strings.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

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

Community Treasure Hunt

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

Start Hunting!

Translated by