Variable overflow doesn't work
6 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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.
0 Commenti
Risposte (3)
John D'Errico
il 19 Set 2016
Modificato: John D'Errico
il 19 Set 2016
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.
0 Commenti
José-Luis
il 19 Set 2016
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
0 Commenti
Adam
il 19 Set 2016
Modificato: Adam
il 19 Set 2016
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
>>
0 Commenti
Vedere anche
Categorie
Scopri di più su Data Type Conversion in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!