1- function val = correctType(val , type )
1+ function val = correctType(val , type , allowDowncast )
22% CORRECTTYPE upcasts if type is smaller than minimum
33% Will error if type is simply incompatible
44% Will throw if casting is impossible
55
66% check different types and correct
7- switch (type )
8- case {' float64' ' float32' ' float' }
9- if ~isfloat(val )
10- val = double(val );
11- end
12- case ' int'
13- if ~isinteger(val )
14- val = int64(val );
15- end
16- case ' uint'
17- if ~isinteger(val )
18- val = uint64(val );
19- end
20- case ' numeric'
21- if ~isnumeric(val )
22- val = double(val );
23- end
24- case ' logical'
25- if ~islogical(val )
26- val = logical(val );
27- end
7+
8+ if startsWith(type , ' float' ) && ~isfloat(val )
9+ val = double(val );
10+ elseif startsWith(type , ' int' ) && ~isinteger(val )
11+ val = int64(val );
12+ elseif startsWith(type , ' uint' ) && ~isinteger(val )
13+ val = uint64(val );
14+ elseif strcmp(type , ' numeric' ) && ~isnumeric(val )
15+ val = double(val );
16+ elseif strcmp(type , ' bool' ) && ~islogical(val )
17+ val = logical(val );
2818end
2919
3020% check different types sizes and upcast to meet minimum (if applicable)
31- if strcmp(type , ' float64' ) && strcmp(class(val ), ' single' )
32- val = double(val );
33- if (~strcmp(type , ' int' ) && startsWith(type , ' int' )) || ...
21+ if any(strcmp(type , {' float64' ' float32' })
22+ if issingle(val )
23+ val = double(val );
24+ elseif allowDowncast && strcmp(type , ' float32' )
25+ val = single(val );
26+ end
27+ elseif (~strcmp(type , ' int' ) && startsWith(type , ' int' )) || ...
3428 (~strcmp(type , ' uint' ) && startsWith(type , ' uint' ))
3529 pattern = ' int%d ' ;
3630 if startsWith(type , ' u' )
3933 typsz = sscanf(type , pattern );
4034 valsz = sscanf(class(val ), pattern );
4135
42- if valsz < typsz
43- val = eval([type ' (val)' ]);
36+ if valsz < typsz || ( nargin > 2 && allowDowncast )
37+ val = eval([type ' (val)' ]);
4438 end
4539end
4640end
0 commit comments