A common mistake MATLAB coders have, is using the length
function for matrices (as opposed to vectors, for which it is intended). The length
function, as mentioned in its documentation, "returns the length of the largest array dimension" of the input.
For vectors, the return value of length
has two different meanings:
Unlike in vectors, the above values would not be equal for arrays of more than one non-singleton (i.e. whose size is larger than 1
) dimension. This is why using length
for matrices is ambiguous. Instead, using one of the following functions is encouraged, even when working with vectors, to make the intention of the code perfectly clear:
size(A)
- returns a row vector whose elements contain the amount of elements along the corresponding dimension of A
.numel(A)
- returns the number of elements in A
. Equivalent to prod(size(A))
.ndims(A)
- returns the number of dimensions in the array A
. Equivalent to numel(size(A))
.This is especially important when writing "future-proof", vectorized library functions, whose inputs are not known in advance, and can have various sizes and shapes.