MATLAB Language Common mistakes and errors Using `length` for multidimensional arrays

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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:

  1. The total number of elements in the vector.
  2. The largest dimension of the vector.

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:

  1. size(A) - returns a row vector whose elements contain the amount of elements along the corresponding dimension of A.
  2. numel(A) - returns the number of elements in A. Equivalent to prod(size(A)).
  3. 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.



Got any MATLAB Language Question?