开发者

Difference between MATLAB's numel and length functions

开发者 https://www.devze.com 2023-01-04 14:51 出处:网络
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?

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:

Difference between MATLAB's numel and length functions

Looks like they're the same performance-开发者_JAVA技巧wise until you get to 100k elements.


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.


As other said they are same for one-dimensional array.

IMHO from code readability viewpoint length should be used on one-dimensional arrays. It is about "intentional programming", you see the code and understand what programmer had in mind when conceiving his work. So when I see numel I know it is used on a matrix.

length vs. numel was a discussion topic in our team over a number of years. Ex senior developer did not cared about code reability, only about work being done and used only numel in otherwise not well readable/formatted code. Other guy is a matematician and used length only on numeric arrays being for him "real" arrays. For cell arrays and struct arrays he used numel.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号