How can I use fprintf to print in scientific format, always starting with 0.XXXXXXE-0Y in case of a positive number, or -.XXXXXXE-0Y in the case of a negative number.
Example: a=-0.07639297; fprintf('%E',a);
This will print the number as: -7.639297E-02
However, I want to have it as: -.7639297E-01
Thanks!

답변 (1개)

Star Strider
Star Strider 2015년 11월 10일

0 개 추천

You have to ‘adjust’ the format a bit, but it can be done as a string:
a=-0.07639297;
expstr = @(x) [x*10.^floor(-log10(abs(x))) floor(log10(abs(x))+1)];
Result = sprintf('%.7fE%+04d', expstr(a))
Result =
-0.7639297E-001
Tweak the format in the sprintf call to your liking.

댓글 수: 4

Enrico Tapavicza
Enrico Tapavicza 2015년 11월 10일
Thank you, this is already close to what I want, but how can I remove the zero before the point to get: -.7639297E-001 ?
Thanks!
It’s possible, but the code looks really kludgy:
a=-0.07639297;
expstr = @(x) [x*10.^floor(-log10(abs(x))) floor(log10(abs(x))+1)];
exvct = expstr(a);
sgn = '- +';
Result = sprintf('%c.%7dE%+04d', sgn(sign(a)+2),abs(exvct(1)/10^(exvct(2)-7)),exvct(2))
Result =
-.76392970E-001
If you’re going to use this frequently, it would be best to wrap it in an external function, add a precision variable to make it robust to your needs (the ‘7’ values in this code would be the precision variables to adjust), and experiment with it to get the result you want. The format descriptor itself is a string, so you can create a separate sprintf call to create it, then pass it to the sprintf call that produces ‘Result’ here. ‘Result’ is a string variable, not numeric, so print it in your own fprintf call using '%s'.
Enrico Tapavicza
Enrico Tapavicza 2015년 11월 11일
All right, thank you very much!
Star Strider
Star Strider 2015년 11월 11일
My pleasure!
The sincerest expression of thanks here on MATLAB Answers is to Accept the Answer that most closely solves your problem.

댓글을 달려면 로그인하십시오.

카테고리

질문:

2015년 11월 10일

댓글:

2015년 11월 11일

Community Treasure Hunt

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

Start Hunting!

Translated by