jeff
jeff

Reputation: 13643

MATLAB force num2str to format

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.

Upvotes: 3

Views: 900

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

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]

Upvotes: 3

Related Questions