I have a problem
1 次查看(过去 30 天)
显示 更早的评论
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 'NONE' is returned. For example, if the smallest element of A is -100 and the largest is +100, then the function would return 'int8'. As another example, if there is an element of A equal to -1e20, then the function would return 'NONE'.
My code is;
if maxA<=((2^7)-1) && minA>=-(2^7);
x='int8';
elseif maxA<=((2^15)-1) && maxA>((2^7)-1) && minA>=-(2^15) && minA< -(2^7);
x='int16';
elseif maxA<=((2^31)-1) && maxA>((2^15)-1) && minA >=-(2^31) && minA <-(2^15);
x='int32';
elseif maxA<=((2^63)-1) && maxA>((2^31)-1) && minA >=-(2^63) && minA< -(2^31);
x='int64';
elseif maxA<= ((2^8)-1) && minA >= 0;
x = 'uint8';
elseif maxA<= ((2^16)-1) && maxA >((2^8)-1);
x = 'uint16';
elseif maxA<= ((2^32)-1) maxA > ((2^16)-1) ;
x = 'uint32';
elseif maxA<= ((2^64)-1) && maxA > ((2^32)-1) ;
x = 'uint64';
else
x=NONE;
end
end
But it is not correct. Where is my error?
采纳的回答
Jan
2017-11-6
编辑:Jan
2017-11-6
It is asked for "signed integer". Then uint32 is not an option, because it is unsigned.
x = 'NONE'; % requires quotes
The operator is missing in:
elseif maxA<= ((2^32)-1) maxA > ((2^16)-1) ;
^^
In addition this does not restrict the minA part.
You do not have to exclude e.g. the int8 range, if it was excluded already:
if maxA<=((2^7)-1) && minA>=-(2^7);
x = 'int8';
elseif maxA<=((2^15)-1) && maxA>((2^7)-1) && minA>=-(2^15) && minA< -(2^7);
x='int16';
Easier:
if maxA <= 2^7 - 1 && minA >= -2^7
x = 'int8';
elseif maxA <= 2^15 - 1 && minA >= -2^15
x = 'int16';
I'd prefer a loop:
TypeList = {'int8', 'uint8', 'int16', 'uint16', ...
'int32', 'uint32', 'int64', 'uint64'};
x = 'NONE';
for k = 1:numel(TypeList)
if isequal(double(A), double(cast(A, TypeList{k})))
x = TypeList{k};
break;
end
end
Or:
minA = min(A(:));
maxA = max(A(:));
x = 'NONE';
for aType = {'int8', 'int16', 'int32', 'int64'}
aType = TypeList{k}
if minA >= intmin(aType) && maxA <= intmax(aType)
x = aType;
break;
end
end
Or
minA = min(A(:));
maxA = max(A(:));
x = 'NONE';
for k = [8,16,32,64]
if minA >= -2^(k-1) && maxA <= 2^(k-1)
x = sprintf('int%d', k);
break;
end
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Argument Definitions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!