Variable overflow doesn't work

20 次查看(过去 30 天)
Petr Jedlicka
Petr Jedlicka 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 中查找有关 Operators and Elementary Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by