Detect variable overflow in matlab code

8 ビュー (過去 30 日間)
Stefan
Stefan 2021 年 2 月 11 日
回答済み: Mohammad Sami 2021 年 3 月 10 日
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 Center および File ExchangeLogical についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by