I know that length(x)
returns max(size(x))
and numel(x)
returns the total number of elements of x, but which is better for a 1 by n array? Does it matter, or are they interchangeable in this case?
EDIT: Just for kicks:
Looks like they're the same performance-wise until you get to 100k elements.
length is the longest dimension (either row or column). size is both dimensions (row and column).
The numel function returns the number of elements in an array, which is equivalent to prod(size(objArray)) . That is, the product of the array dimensions.
L = length( X ) returns the length of the largest array dimension in X . For vectors, the length is simply the number of elements. For arrays with more dimensions, the length is max(size(X)) .
n = numel( A ) returns the number of elements, n , in array A , equivalent to prod(size(A)) .
For a 1-by-N array, they are essentially the same. For a multidimensional array M
, they can give different results:
numel(M)
is equivalent to prod(size(M))
.length(M)
is equivalent to max(size(M))
. If M
is empty (i.e. any dimension is 0), then length(M)
is 0.In that case they return the same and there's no difference. In term of performance, it depends on the inner working of arrays in MATLAB. E.g. if there are metainformations about how many elements are in the array (no matter the shape), then numel is as fast as possible, while max(size(x)) seems to need more work to obtain the same thing (retrieving sizes, and then finding the max among those). I am used to use numel
in that case, but performance speech (hypothetical) apart, I would say they are interchangeable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With