Note the date, folks. I am using this excuse to be a bit light-hearted today. I saw the following quote on someone's door here at MathWorks.
MATLAB gives you the benefit of the double.
This made me smile and I realized that there are some ways in which MATLAB uses doubles that might not always be obvious to users.
X = 17
X = 17
When the value of X is displayed, as 17, there is no decimal point or other indication that X is not strictly an integer. Despite that, X is a double precision variable. I have at least a couple of ways to find this information programmatically.
Name Size Bytes Class Attributes X 1x1 8 double
ans = double
By default, MATLAB variables are double precision arrays. In the olden days, these were the only kind of arrays in MATLAB. Back then even character arrays were stored as double values.
There are other ways to store integers in MATLAB these days. Let me list a few:
First I'll convert the double to a string and display it.
str17 = num2str(X)
str17 = 17
Notice that the display looks different than that for X. There is no leading white space for character arrays (unless it's part of the string itself).
Now let's look at the display for some integer types.
u8 = uint8(X) i8 = int8(X)
u8 = 17 i8 = 17
Notice here that you can't distinguish the type based on the display of the values. The default numeric display in MATLAB tries to display the maximum amount of information compactly.
Because the default type is double, we have found it really convenient to allow some interaction between double scalar values and other numeric array types. The way I like to state the behavior is that, for arithmetic operators, MATLAB does the calculations as if the arrays are doubles, and then respects the memory savings of the non-double storage class. What this means, for example, is that I can take a grayscale image and halve the values like so, causing the new image to be darker.
p = imread('pout.tif'); class(p) imshow(p)
ans = uint8
pHalf = p * 0.5; class(pHalf) imshow(pHalf)
ans = uint8
Have you had cases where you either took advantage of the interactions of integers and doubles in MATLAB, or where integers and floating point integers gave you a surprise? Let me know here.