Difference between MATLAB's numel and length functions

Doresoom picture Doresoom · Jun 25, 2010 · Viewed 25.6k times · Source

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.

Answer

gnovice picture gnovice · Jun 25, 2010

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.