3

I'm searching for the reverse of this request

So when I type num2str(foo,3), I get this :

foo=0.00781
foo=0.0313
foo=0.125
foo=0.5
foo=2
foo=8

However I want to make them all of the same length, so something like this :

foo=0.0078
foo=0.0313
foo=0.1250
foo=0.5000
foo=2.0000
foo=8.0000

-How- can I do this with num2str? (And I would really appreciate if it also works if mat2str)

Thanks for any help!

Edit :

I noticed that there is another -yet unsolved- part to this problem, which is for numbers greater than 10, or 100, 1000, etc.

So what if I want this : ?

foo=000.5000
foo=002.0000
foo=008.0000
foo=032.0000
foo=128.0000

i.e. adding leading zeros to a specified length? I tried '%3.3f' but it doesn't work.

Community
  • 1
  • 1
jeff
  • 13,055
  • 29
  • 78
  • 136

1 Answers1

3

For a single number

You can include a C-like format specifier in num2str:

>> num2str(.125, '%0.4f')
ans =
0.1250

Or use sprintf:

>> sprintf('%0.4f', .125)
ans =
0.1250

For matrices

Use num2str with a matrix input. Include the desired separator column (such a space) in the format specifier:

>> num2str([.125 .5; 2 8], '%0.4f ')
ans =
0.1250 0.5000
2.0000 8.0000

If you then want mat2str-like format, you just need to procress the resulting string to include ; (or just ;) at the end of each line and enclose with [, ]:

x = [.125 .5; 2 8]; 
s = num2str(x, '%0.4f ');
s = [s repmat('; ', size(s,1), 1)].';
s = ['[' s(1:end-2) ']'];

In the example, this gives

>> s
s =
[0.1250 0.5000; 2.0000 8.0000]

Leading zeros

If you want leading zeros to achieve a fixed number of characters, use a format specifier of the form '%08.4f'. This means 4 decimal places, 8 characters in total, which gives up to 3 leading zeros. For example,

x = [.125 .5; 2 8]; 
s = num2str(x, '%08.4f ');
s = [s repmat('; ', size(s,1), 1)].';
s = ['[' s(1:end-2) ']'];

gives

>> s
s =
[000.1250 000.5000; 002.0000 008.0000]
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • 1
    Thank you! I was doing this with fprintf, but I didn't know we could use C-like formatting in MATLAB functions too. Well, it only makes sense :) – jeff Aug 02 '15 at 11:15
  • Dear @Luis Mendo, (or any other future visitor), please see the edit to my question. Is there a way for leading zeros? – jeff Aug 02 '15 at 17:12
  • 1
    @halilpazarlama Sure! That's one of the [options of the format specifier](http://es.mathworks.com/help/matlab/ref/fprintf.html#inputarg_formatSpec). See edited answer – Luis Mendo Aug 02 '15 at 17:23