Home > OS >  How to disable Matlab Integer Overflow saturation
How to disable Matlab Integer Overflow saturation

Time:08-06

I want to test a piece of function and from 127, it is normal for me that 127 1 = -128. But for Matlab, no... it saturates my value even though it is a desired behavior on my code.

There are explanations to disable this option on Simulink but what about for a script? I don't know how to disable this feature.

CodePudding user response:

Overflow is not part of Matlab hypotheses. You need to implement this behaviour in your script using the modulo function (mod). For example:

>> a=127; mod(a 128,256)-128

ans =

   127

>> a=128; mod(a 128,256)-128

ans =

  -128

CodePudding user response:

If you really want to use the int8 overflow and not simulate it with the "mod" function, you can use the typecast function.

First you need to convert your variable into an int (otherwise it is by default a double in Matlab). Then you cast it to an int8 and you keep only the first byte:

>> a=127; getfield(typecast(int64(a),'int8'),{1})

ans =

  int8

   127

>> a=128; getfield(typecast(int64(a),'int8'),{1})

ans =

  int8

   -128

CodePudding user response:

Since you use 127 and -128 as the examples, I assume you are working with int8 variable types. To get the modulo behavior you want, you could use a simple C mex routine to do the arithmetic (since your C compiler will in all likelihood optimize this overflow condition away as simple modulo behavior), or in m-code you can convert to a larger type and do the arithmetic yourself (assumes your machine uses 2's complement storage for integer types). E.g.,

a8 = int8(127); % sample data
b8 = int8(1); % sample data
a16 = int16(a8); % convert to larger type
b16 = int16(b8); % convert to larger type
c16 = a16   b16 % do the addition in larger type
    c16 = int16
        128
c8s = typecast(c16,'int8') % typecast back to int8 (assume 2's complement storage)
    c8s = 1x2
       -128    0
c8 = c8s(1) % pick either c8s(1) or c8s(2) depending on endian of your machine
    c8 = int8
       -128

If you are working with arrays of numbers instead of scalars, then you could put this in a loop or vectorize the last line as either c8s(1:2:end) or c8s(2:2:end)

  • Related