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

221 views Asked by At

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 ?

2

There are 2 answers

1
Andrew Janke On BEST ANSWER

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.

9
Edric On

The simplest answer I can think of is continuity - so that my code doesn't have to write a special case if something turns out to need zero rows or columns. Consider this slightly silly function:

function out = getAllRowsGt5(someMatrix)
rowIdxs = find(sum(someMatrix, 2) > 5);
out = zeros(numel(rowIdxs), size(someMatrix, 2));
for idx = 1:numel(rowIdxs)
    out(idx,:) = someMatrix(rowIdxs(idx), :);
end
end

Sure, there are simpler ways of implementing that in MATLAB. But the point is that I want to preallocate the result based on the values in the input. This code has well-defined post-conditions:

size(out, 2) == size(someMatrix, 2)

and it doesn't have to special-case the situation where nothing matched my condition. Neither of those would be true if there was a limitation on the shape of empty arrays allowed by MATLAB.