Robochameleon  v1.0
formatPrefixSI.m
Go to the documentation of this file.
1 
2 function [s,mantissa,factor,unit,exponent,prefix] = formatPrefixSI(x,numspec,unitspec,base,nonSI)
3 
4 if nargin<5 % Use traditional units: c, d, da, h.
5  nonSI = false;
6 end
7 
8 if nargin<4 || isempty(base); % Reference base for the number (if not 10^0)
9  base = 0;
10 elseif ~isscalar(base)
11  error('Number base must be a real scalar');
12 elseif base
13  base = log10(base);
14 end
15 
16 if nargin<3 % Unit
17  unitspec = '';
18 end
19 
20 if nargin<2 || isempty(numspec) % Number format specification
21  numspec = '%1.2f';
22 end
23 
24 % Formats numbers with units
25 % E.g. 10e12 -> 10 T
26 if ~isscalar(x)
27  error('Input number must be a scalar.');
28 elseif x==0 || isinf(x);
29  exponent = 0;
30 else
31  exponent = log10(x)+base;
32 end
33 
34 if isnan(exponent)
35  exponent = 0;
36 elseif exponent<-24
37  exponent = -24;
38 end
39 
40 EXPONENT = [-24 -21 -18 -15 -12 -9 -6 -3 -2 -1 0 1 2 3 6 9 12 15 18 21 24];
41 PREFIX = {'y' 'z' 'a' 'f' 'p' 'n' 'u' 'm' 'c' 'd' '' 'da' 'h' 'k' 'M' 'G' 'T' 'P' 'E' 'Z' 'Y'};
42 if ~nonSI
43  [~,idx] = intersect(EXPONENT,[-2 -1 1 2]);
44  EXPONENT(idx) = [];
45  PREFIX(idx) = [];
46 end
47 
48 idx = find(EXPONENT<=exponent,1,'last');
49 exponent = EXPONENT(idx);
50 
51 idx = find(EXPONENT==exponent,1);
52 prefix = PREFIX{idx};
53 
54 factor = 10^(base-exponent);
55 mantissa = x*factor;
56 unit = [prefix unitspec];
57 s = sprintf([numspec ' ' unit],mantissa);
Superclass: basic building block to hold functions.
Definition: unit.m:27
function formatPrefixSI(in x, in numspec, in unitspec, in base, in nonSI)
Formats a number for printing using SI prefixes.