Number format
5 views (last 30 days)
Show older comments
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
0 Comments
Answers (2)
Thomas
on 10 Apr 2012
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
Jan
on 10 Apr 2012
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.
See Also
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!