Number format

조회 수: 5 (최근 30일)
Poul Reitzel
Poul Reitzel 2012년 4월 10일
Dear Matlab Community
I am facing a problem to convert a row of numbers to a string in a specific format. The problem is best illustrated by an example:
I convert the following vector
a = [-0.0127 -0.1711 -0.0327 -0.0015 0.0035 -0.0186]
to a string using num2str(a). However, I want the numbers in engineering format, i.e. written as a product of a number and an exponent. I achieve this by writing
num2str(a,'%6.3E'), producing:
-1.266E-002 -1.711E-001 -3.274E-002 -1.492E-003 3.493E-003 -1.864E-002
But I want the format to be like this:
-0.1266E-003 -0.1711E-002 -0.3274E-003 -0.1492E-004 0.3493E-004 -0.1864E-003
Is there a way to do this?
Thanks in advance! Poul

답변 (2개)

Thomas
Thomas 2012년 4월 10일
a = [-0.0127 -0.1711 -0.0327 -0.0015 0.0035 -0.0186]
format shortE
a
a =
-1.2700e-02 -1.7110e-01 -3.2700e-02 -1.5000e-03 3.5000e-03 -1.8600e-02
Try it: this works
a = [-0.0127 -0.1711 -0.0327 -0.0015 0.0035 -0.0186]
for i=1:length(arg)
sgn(i) = sign(arg(i));
expnt(i) = fix(log10(abs(arg(i))));
mant(i) = sgn(i) * 10^(log10(abs(arg(i)))-expnt(i));
if abs(mant(i)) < 1
mant(i) = mant(i);
expnt(i) = expnt(i)-2;
end
end
d=[mant;expnt];
out=sprintf('%fe%+04d\n',d)
Ans
out =
-0.127000e-003
-0.171100e-002
-0.327000e-003
-0.150000e-004
0.350000e-004
-0.186000e-003
  댓글 수: 1
Poul Reitzel
Poul Reitzel 2012년 4월 10일
The deal is I want the class to be 'char', while having the numbers written with a zero followed by a dot followed by the digits and an exponent, e.g.
-0.1266E-003 -0.1711E-002 -0.3274E-003 -0.1492E-004 0.3493E-004 -0.1864E-003

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


Jan
Jan 2012년 4월 10일
I suggest to search in the forum. Then you find: Answers: engineering-notation
function Str = EngineersStyle(x)
Exponent = 3 * floor(log10(x) / 3);
y = x ./ (10 .^ Exponent);
D = [y(:), Exponent(:)].';
Str = sprintf('%fe%+04d ', D);
Str(end) = [];
end
I cannot test this currently.
  댓글 수: 2
Poul Reitzel
Poul Reitzel 2012년 4월 10일
I will have a look at it tomorrow at work, thank you!
Poul Reitzel
Poul Reitzel 2012년 4월 11일
It is not quite (per my question) what I was looking for, but I will take it from here!

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

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by