MATLAB: What is the opinion of matlabs “extra rounding improvements”

castMATLABround

Hi, during my work with matlab I have noticed that matlab always tries to improve some basic functionality of other programming languages. Some examples.
a = cast(0.5,'int32') % a = 1

a = cast(-1.5,'uint32') % a = 0
a = int32(1)/int32(2) % a = 1
The division can of course be solved by idivide, but the issues with cast remains. Also this definitely shows that matlab cannot properly do integer operations since the decimals are obviously used by the /.
Is there some way to do a cast that works as it should in matlab? What is the general opinion of matlabs " IMPROVED " behaviour?

Best Answer

MATLAB uses "saturation" arithmetic when converting to the integer data types. Any value that is larger than the integer type can hold is converted to the largest value that can be held, and any value that is less than the integer type can hold is converted into the smallest value that can be held. As the smallest value that unsigned integer types can hold is 0, negative values get transformed into 0.
If you examine the behavior of other languages such as C, you will find that casting a signed value into an unsigned integer does depend upon sign. If you do not want it to, then take abs() before doing the type conversion.
Whether integer operations round or truncate does not matter much to me; in cases where it matters, I can document and (if needed) I can code around it.