Data types and preallocation

2 views (last 30 days)
Daniel Shub
Daniel Shub on 24 Aug 2012
Apart from historical reasons, is there a good reason that the default data type is double. It seems like memory allocation could be substantially improved at the cost of more dynamic recasting. From an efficiency stand point, I am not sure it is worth it, but couldn't
x = zeros(N, M);
be created as a sparse matrix instead of a huge memory hogging matrix of doubles. Similarly, it seems to me that
x = ones(N, M);
should probably get allocated as a logical matrix and that
x = 1:N;
should be some type of integer.
How often do people use a numeric data type that isn't double. The most frequent case I can think of is image processing where integer data types are common.
Do people ever do something as silly as
for ii = int8(1:10)

Answers (1)

Titus Edelhofer
Titus Edelhofer on 24 Aug 2012
Hi Daniel,
interesting question, I'll comment on two of the points from my perspective. Regarding the "zeros": here the user has to decide indeed, whether the matrix will continue to have lot's of zeros, or is it going to fill up anyway.
Sparse matrices are cool, but if you have let's say more than 50% entries non zero, the time and memory overhead compared to the full matrix is huge!
So: if your matrix is going to stay sparse, use sparse, if not, use zeros. But how should MATLAB know before?
The ones: exactly for this reasoning you can write since a couple of versions of MATLAB
x = false(N,M);
y = true(N,M);
Titus
  1 Comment
Daniel Shub
Daniel Shub on 24 Aug 2012
I think what I am saying is if you care about the data type, then you should have to specify it. If I want to preallocate a double, then I should do something like zeros(N, M, 'double'), similarly if I need to preallocate a logical matrix false(N, M). If I don't specify the data type, then MATLAB should dynamically recast the variable as needed.

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!