Detect variable overflow in matlab code

18 次查看(过去 30 天)
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?

采纳的回答

Mohammad Sami
Mohammad Sami 2021-3-10
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Modeling 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by