MetricPrefixStr - Print SI Prefix Formatted Numbers

by

 

Prints a SI prefix formatted string corresponding to a numeric vector.

MetricPrefixStr(xtickvec)
function str = MetricPrefixStr(xtickvec)
% Author:   Damon Bradley
% Purpose:  Print out formatted string using SI prefixes to clean up plots
% for quantities in the thousands and millions. This is useful for
% publication-quality plots.
%
% Version 1.0, March 28, 2013
%
% INPUTS: xtickvec - Any vector of numbers
% OUTPUTS: str - An array of strings with properly formatted numbers
%
% USAGE EXAMPLE:
%
% labels = MetricPrefixStr([1 10 100 33.64 1000 2000 40000 340000 7000000 1e14])
%
% labels = 
%
%    '1'    '10'    '100'    '33.64'    '1k'    '2k'    '40k'    '340k'    '7M'    '100T'
%
% class labels
% 
% ans =
%
% char

% Make sure xtickvec is always a row vector
xtickvec = xtickvec(:)';

grand_idx   = (xtickvec >= 1e3)  & (xtickvec < 1e6);
mill_idx    = (xtickvec >= 1e6)  & (xtickvec < 1e9);
bill_idx    = (xtickvec >= 1e9)  & (xtickvec < 1e12);
trill_idx   = (xtickvec >= 1e12) & (xtickvec < 1e15);
else_idx    = (xtickvec < 1e3)   | (xtickvec >= 1e15);

grand_vals  = xtickvec(grand_idx);
mill_vals   = xtickvec(mill_idx);
bill_vals   = xtickvec(bill_idx);
trill_vals   = xtickvec(trill_idx);
else_vals   = xtickvec(else_idx);

kstrings    = cellstr([num2str(grand_vals'/1e3,'%d') ...
                repmat('k', size(grand_vals'))]);
Mstrings    = cellstr([num2str(mill_vals'/1e6,'%d') ...
                repmat('M', size(mill_vals'))]);
Gstrings    = cellstr([num2str(bill_vals'/1e9,'%d') ...
                repmat('G', size(bill_vals'))]);
Tstrings    = cellstr([num2str(trill_vals'/1e12,'%d') ...
                repmat('T', size(trill_vals'))]);
            
Otherstrings = cellstr(num2str(else_vals','%g'));
                

xtickstrings(grand_idx) = kstrings;
xtickstrings(mill_idx)  = Mstrings;
xtickstrings(bill_idx)  = Gstrings; % lol
xtickstrings(trill_idx) = Tstrings;
xtickstrings(else_idx)  = Otherstrings;

xtickstrings = cellfun(@fliplr,deblank(cellfun(@fliplr,xtickstrings,... % remove blanks
    'uniformoutput',false)),'uniformoutput',false);

str = xtickstrings;

Contact us