Matlab sprintf formatting

2020-04-17 05:48发布

问题:

EDIT: I've reworded the question to be clearer.

Does anyone know a clever way to get sprintf to print "%.6f with trailing zeros elminated"? This is what I'm looking for:

sprintf('%somemagic ', [12345678 123.45])
ans = 1234578 123.45 

where %somemagic is some magical specifier. None of the formats seem to work.

% no trailing zeros, but scientific for big nums
sprintf('%g ', [12345678 123.45])
ans = 1.23457e+007 123.45 

% not approp for floats
sprintf('%d ', [12345678 123.45])
ans = 12345678 1.234500e+002 

% trailing zeros
sprintf('%f ', [12345678 123.45])
ans = 12345678.000000 123.450000

% cannot specify sig figs after decimal (combo of gnovice's approaches)
mat = [12345678 123.45 123.456789012345];
for j = 1:length(mat)
    fprintf('%s ', strrep(num2str(mat(j),20), ' ', ''));
end

I don't think there is a way to do it other than looping through each element and changing the specifier based off of mod(x,1)==0 or using regexp to remove trailing zeros. But you never know, the crowd is more clever than I.

My actual application is to print out the array elements in an html table. This is my current clunky solution:

for j = 1:length(mat)
    if mod(mat(j),1) == 0
        fprintf('<td>%d</td>', mat(j));
    else
        fprintf('<td>%g</td>', mat(j));
    end
end

回答1:

EDIT: Updated to address the edited question...

I don't think there's any way to do it with a particular format string for SPRINTF, but you could instead try this non-loop approach using the functions NUM2STR and REGEXPREP:

>> mat = [12345678 123.45 123.456789012345];       %# Sample data
>> str = num2str(mat,'<td>%.6f</td>');             %# Create the string
>> str = regexprep(str,{'\.?0+<','\s'},{'<',''});  %# Remove trailing zeroes
                                                   %#   and whitespace
>> fprintf(str);                                   %# Output the string

<td>12345678</td><td>123.45</td><td>123.456789</td>  %# Output


回答2:

The problem is that you're mixing an int with a float in an array. Matlab doesn't like that so it will convert your int to a float so that all elements in the array are of the same type. Look at doc sprintf: you're now forced to use %f, %e or %g on floats

Although I admit I like the STRREP method above (or below)



标签: matlab printf