Variable overflow doesn't work

조회 수: 5 (최근 30일)
Petr Jedlicka
Petr Jedlicka 2016년 9월 19일
편집: John D'Errico 2016년 9월 19일
Hi, I am writing a program in Matlab, where I need variables to overflow(underflow), but Matlab doesn't allow it. For example when I write:
a = int8(-128)
a = a - 1
I will expact a == +127 but the variable retains the value -128. I need this feature to write a special type of digital filter. Does anybody know how to solve this problem and make Matlab variables overflow(underflow)?
Thanks.

답변 (3개)

John D'Errico
John D'Errico 2016년 9월 19일
편집: John D'Errico 2016년 9월 19일
Underflows ARE allowed. Just not the kind of underflow you want to see.
That is the behavior of an int8 variable. It underflows, but does not wrap, so it is an absorbing barrier. And, no, you cannot define the underflow behavior for variables. That would make for some interesting bugs I would guess, if you changed that behavior and something depended it being the default.
You can write your own class of course that works as you desire.

José-Luis
José-Luis 2016년 9월 19일
Specifically:
If you convert a number that is larger than the maximum value of an integer data type to that type, MATLAB sets it to the maximum value. Similarly, if you convert a number that is smaller than the minimum value of the integer data type, MATLAB sets it to the minimum value.
So what you have is the expected behavior.
You can always implement the behavior you want without too much fuzz:
val = -135;
offset = mod(sign(val) * (val - sign(val) * 128),257);
result = -sign(val) * 129 + sign(val) * offset

Adam
Adam 2016년 9월 19일
편집: Adam 2016년 9월 19일
Something like this would work, though I am sure there are neater ways. Obviously you would need to overload all the other operators though if you want it to be consistent - e.g. here it will just inherit plus, times, etc from int8 so you would have to program those yourself to get the desired behaviour.
classdef myint8 < int8
methods
function obj = myint8( val )
obj = obj@int8( val );
end
function res = minus( obj, valToSubtract )
res = double( obj ) - double( valToSubtract );
res = myint8( mod( res + 128, 256 ) - 128 );
end
end
end
>> a = myint8( -128 )
a =
myint8:
int8 data:
-128
>> a = a - 1
a =
myint8:
int8 data:
127
>>

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by