MATLAB forces num2str to format

I'm looking for a backlink 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 the same, 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 it with num2str

? (And I would really appreciate it if it also works if mat2str

)

Thanks for any help!

Edit:

I noticed there is one more unresolved part for 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 the specified length? I tried '%3.3f'

it but it doesn't work.

+3


source to share


1 answer


For one 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 matrix input. Include the required 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 want the mat2str

-like format , you just need to process the resulting string to include ;

(or just ;

) at the end of each line and enclose it [

,]



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 reach a fixed number of characters, use the form format specifier '%08.4f'

. This means 4 decimal places, a total of 8 characters, 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]

      

+3


source







All Articles