Remove 0 from scientific notation

16 ビュー (過去 30 日間)
Sam Zipper
Sam Zipper 2013 年 4 月 12 日
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

採用された回答

Walter Roberson
Walter Roberson 2013 年 4 月 12 日
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 件のコメント
Sam Zipper
Sam Zipper 2013 年 4 月 12 日
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 2013 年 4 月 12 日
fwrite() would make more sense than fprintf() if the data is already formatted into strings.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeEntering Commands についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by