Loren on the Art of MATLAB

Turn ideas into MATLAB


Loren on the Art of MATLAB has been archived and will not be updated.

Double or Nothing? No Joking!

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.


What Type is X?

X = 17
X =

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 =

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.

Other Integers

There are other ways to store integers in MATLAB these days. Let me list a few:

  • characters: char
  • signed integers, e.g., int8
  • unsigned integers, e.g., uint8

Display the Values Stored in Various Types

First I'll convert the double to a string and display it.

str17 = num2str(X)
str17 =

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 =
i8 =

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.

Some Behaviors

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');
ans =
pHalf = p * 0.5;
ans =


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.

Published with MATLAB® 7.10

  • print


댓글을 남기려면 링크 를 클릭하여 MathWorks 계정에 로그인하거나 계정을 새로 만드십시오.