Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between MATLAB's numel and length functions

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:

alt text

Looks like they're the same performance-wise until you get to 100k elements.

like image 595
Doresoom Avatar asked Jun 25 '10 16:06

Doresoom


People also ask

What is the difference between the Matlab functions length (~) and size?

length is the longest dimension (either row or column). size is both dimensions (row and column).

What does Numel function do in Matlab?

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.

What does length function do in Matlab?

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)) .

How do you find the number of elements in an array in Matlab?

n = numel( A ) returns the number of elements, n , in array A , equivalent to prod(size(A)) .


2 Answers

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.
like image 154
gnovice Avatar answered Oct 09 '22 05:10

gnovice


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.

like image 31
ShinTakezou Avatar answered Oct 09 '22 05:10

ShinTakezou