matlabpre-allocation

Why can an empty array have a non-null dimension?


If we write, for example:

x = int8.empty(0,5)

whos x outputs:

% Name    Size    Bytes    Class    Attributes
% x       0x5     0        int8     

Thus, we obtain a 0x5 empty array of class int8.

What is the purpose of preallocating an empty array containing a non-null dimension if its memory size is 0 bytes ?

In which case

x = int8.empty(0,5)

is more useful than

x = int8.empty(0,0)

Does int8.empty(0,5) still preallocate 5 "slots" of memory ?


Solution

  • I've run in to a practical use case for 0-by-n vectors: with Matlab's new declarative property and argument constraints, you can say things like "x must be an N-by-1" or "z must b n-by-3" by declaring it as (:,1) or (:,3). This allows you to represent the empty set in a conformant way.

    There are also formal reasons for doing so: A function or operation may be defined in terms of the dimensionality of its inputs, such as "takes an m-by-n array and returns a k-by-n array where k = somefunction(m or its values)", and in degenerate cases where k turns out to be zero, an empty array with some nonzero dimensions allows operations like this that still strictly adhere to their contracts.

    In practical terms, for basic operations like concatenation and such, all empty arrays are usually interchangeable, and will usually Just Work or at most produce a warning.