MATLAB numel 和 length 函数之间的区别
我知道 length(x)
返回 max(size(x))
和 numel(x)
返回 x 的元素总数,但对于 1 × n 数组来说哪个更好呢?这很重要吗?或者在这种情况下它们可以互换吗?
编辑:只是为了好玩:
>就像在达到 100k 元素之前它们在性能方面是相同的。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于 1×N 数组,它们本质上是相同的。对于多维数组
M
,它们可以给出不同的结果:numel(M)
等价于prod(size(M))
。length(M)
相当于 <代码>最大(尺寸(M))。如果M
为空(即任意维度为0),则length(M)
为0。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 toprod(size(M))
.length(M)
is equivalent tomax(size(M))
. IfM
is empty (i.e. any dimension is 0), thenlength(M)
is 0.在这种情况下,它们返回相同的结果,没有区别。就性能而言,它取决于 MATLAB 中数组的内部工作原理。例如,如果有关于数组中有多少元素的元信息(无论形状如何),那么 numel 会尽可能快,而 max(size(x)) 似乎需要更多工作才能获得相同的东西(检索大小,然后找到其中的最大值)。在这种情况下,我习惯使用
numel
,但除了性能演讲(假设)之外,我想说它们是可以互换的。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.正如其他人所说,它们对于一维数组是相同的。
恕我直言,从代码可读性的角度来看
length
应该用于一维数组。这是关于“意向编程”,你看到代码就明白程序员在构思时的想法他的工作。因此,当我看到numel
时,我知道它是在矩阵上使用的。length
与numel
是我们团队多年来的讨论主题。前高级开发人员并不关心代码的可靠性,只关心正在完成的工作,并且仅在可读/格式不佳的代码中使用numel
。另一个人是数学家,仅在数字数组上使用length
对他来说是“真实”数组。对于元胞数组和结构体数组,他使用了numel
。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 seenumel
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 onlynumel
in otherwise not well readable/formatted code. Other guy is a matematician and usedlength
only on numeric arrays being for him "real" arrays. For cell arrays and struct arrays he usednumel
.