-
Notifications
You must be signed in to change notification settings - Fork 3
/
convertUnit.m
58 lines (48 loc) · 1.65 KB
/
convertUnit.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
function [value, unit] = convertUnit(value, oldUnit, varargin)
persistent p
if ~isempty(p) || true
p = inputParser;
p.FunctionName = 'convertUnit';
p.addRequired('value', @isnumeric);
p.addRequired('oldUnit', @ischar);
p.addOptional('newUnit', 'base', @ischar);
end
%Get Quantity Object
persistent ureg
if isempty(ureg)
ureg = py.pint.UnitRegistry;
ureg.load_definitions(fullfile(Datamaster.getPath, 'UnitDefine.txt'));
end
%Parse Input
parse(p, value, oldUnit, varargin{:});
value = p.Results.value;
oldUnit = p.Results.oldUnit;
newUnit = p.Results.newUnit;
%If dimensionless -> Return
if strcmp(oldUnit, '')
return
elseif strcmp(oldUnit, newUnit)
unit = oldUnit;
else
%Remove Unicode Characters from oldUnit
oldUnit = strrep(oldUnit, '°', 'deg'); %Remove Degree symbol
oldUnit = strrep(oldUnit, '·', '*'); %Remove Times symbol
oldUnit = strrep(oldUnit, 'psi a', 'psi'); %Remove Times symbol
%Put array into numpy array for conversion
value = py.numpy.array(value);
%Convert to Pint Quantity
valueOld = ureg.Quantity(py.numpy.array(value), oldUnit);
%Convert Quantity to desired Unit
if strcmp(newUnit, 'base')
%Convert to base unit
valueNew = valueOld.to_base_units();
else
%Convert to New Unit
valueNew = valueOld.to(newUnit);
end
%Extract Unit String
unit = valueNew.units.char;
%Extract Magnitude to array
newValue = py.numpy.array(valueNew.magnitude.tolist);
value = double(py.array.array('d', py.numpy.nditer(newValue)));
end