Why does NUM2STR ignore the width specifier in MATLAB 7.8 (R2009a)?

10 Ansichten (letzte 30 Tage)
When I use a format specifier with NUM2STR, it ignores the width specifier. For example the following code returns '1.345' instead of ' 1.345'.
s = num2str(1.345, '%10.3f')

Akzeptierte Antwort

MathWorks Support Team
MathWorks Support Team am 14 Jul. 2009
This is expected behavior. The documentation of the NUM2STR function states the following:
"num2str removes any leading spaces from the output string."
To work around this issue, use the SPRINTF function instead. Please see the following examples.
% Example 1.
s = sprintf('%10.3f', 1.345)
% Example 2.
y = [1.0 10.0 100.0]
sprintf('%10.2f\n', y)
% Example 3.
a=[1111.111 22.2222 33.33; 444.4 555.55 66.0];
for i=1:2
y=sprintf('%-7.3e \t %-6.4e \t %-5.1e',a(i,1),a(i,2),a(i,3))
end
% Example 4.
A = pi*100*ones(1,5);
sprintf(' %f \n %.2f \n %+.2f \n %12.2f \n %012.2f \n', A)
Which outputs the following:
ans =
314.159265 % Display in fixed-point notation (%f)
314.16 % Display 2 decimal digits (%.2f)
+314.16 % Display + for positive numbers (%+.2f)
314.16 % Set width to 12 characters (%12.2f)
000000314.16 % Replace leading spaces with 0 (%012.2f)

Weitere Antworten (0)

Kategorien

Mehr zu Startup and Shutdown finden Sie in Help Center und File Exchange

Produkte


Version

R2009a

Community Treasure Hunt

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

Start Hunting!

Translated by