Detect variable overflow in matlab code

19 views (last 30 days)
I have an applicaiton where I keep adding an integer value to an other integer. In the simple example below I keep adding temp to i. If i reach the maximum value of this integer matlab will saturate the result to be intmax('uint8'). But what I actually want is it not to saturate. For instance if i == uint8(255) and I add 1. Than the value of i should be 0. If this happends I want to run some different code.
i = uint8(0);
for j = 1:10000
temp = uint8(rand*10);
i = i + temp;
if i == intmax('uint8')
disp('max reached')
end
end
Now we do this by check if the sum would saturate the variable:
i = uint8(0);
for j = 1:10000
temp = uint8(rand*100);
if (i + temp) == intmax('uint8')
disp(['max reached ' num2str(i) ' ' num2str(temp)] )
i = temp - (intmax('uint8') - i);
disp(num2str(i))
else
i = i + temp;
end
end
This almost works but if the sum is exectly 255 we make a mistake of 1. Does anyone know if there is a function or a method to do this in an other way?

Accepted Answer

Mohammad Sami
Mohammad Sami on 10 Mar 2021
The following should work.
i = uint8(0);
for j = 1:10000
temp = randi(255,'uint8');
% test if temp is bigger then the difference between intmax and i
if temp > (intmax('uint8') - i)
disp(['max reached ' num2str(i) ' ' num2str(temp)] )
i = temp - (intmax('uint8') - i);
disp(num2str(i));
else
i = i + temp;
disp(num2str(i));
end
end

More Answers (0)

Categories

Find more on Modeling in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!