MATLAB: Write a function called integerize that takes as its input a matrix A of integers of type double, and returns the name of the “smallest” signed integer class to which A can be converted without loss of information. If no such class exists, the text

integerize

function integerize(A)
int8(A<2^7-1);
int16(A<2^15-1);
int32(A< 2^31-1);
int64(A<2^63-1);
end

Best Answer

EDIT: see Guillermo Varela Carbajal's answer below for a really neat solution.
Try something like this:
function typ = integerize(A)
if A >= intmin('int8') & A <= intmax('int8')
typ = 'int8';
elseif A >= intmin('int16') & A <= intmax('int16')
typ = 'int16';
elseif A >= intmin('int32') & A <= intmax('int32')
typ = 'int32';
elseif A >= intmin('int64') & A <= intmax('int64')
typ = 'int64';
else
typ = 'NONE';
end
end
and tested:
>> integerize([128,127;-127,0])
ans = int16
Just for the sake of discussion, here is a function where the list of accepted classes are specified as an input argument (as long as the order from smallest to largest is kept):
function typ = integerize(A,C)
for k = 1:numel(C)
typ = C{k};
if A >= intmin(typ) & A <= intmax(typ)
return
end
end
typ = 'NONE';
end
and tested:
>> integerize(A,{'int8','int16','int32','int64'})
ans = int16
>> integerize(A,{'int8','int32','int64'})
ans = int32
>> integerize(A,{'int8','int64'})
ans = int64
>> integerize(A,{'int8'})
ans = NONE