Matlab is implicitly casting to the lower type. Can you change it?

Look at this:
x = int16(1)
y = x*1.5
% y is an int16 and equals 2...
That is a horrible behavior! If someone gives you a function returning an integer (like number of something) and decides to make a cast to int16 or unint16 before returning, and you use this function for your calculations, you may be producing completely wrong results without knowing it. Is there an option to change to implicit "upward" casting like in C (so that the example above gives a double of 1.5)? Or should I cast all integers to doubles before using them?

Answers (1)

I believe there is a matlab Blog where this is discussed. This is intentional, the reasoning being that if you've chosen to make your variables single instead of the default double, it's for a reason (memory) so you'd want it to stay single instead of being converted to double if multiplied by a double.
I do agree that it is bonkers since the implicit conversion is lossy and the complete opposite of many language where the default is to only allow lossless implicit conversion (as in C), however that's what it has always been in matlab and it's not likely to change.
No there is no option to have widening implicit conversions. On the other hand, it's unlikely that you'll be manipulating integer types without knowing it since by default everything in matlab is double. Networking code and image processing usually involve integers but then you do know that you're using them.

Categories

Asked:

on 12 Jul 2018

Commented:

on 13 Jul 2018

Community Treasure Hunt

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

Start Hunting!