Number format

3 次查看(过去 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 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by