MATLAB numel 和 length 函数之间的区别

发布于 2024-09-06 21:23:55 字数 228 浏览 3 评论 0原文

我知道 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:

alt text

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

昨迟人 2024-09-13 21:23:55

对于 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 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.
以往的大感动 2024-09-13 21:23:55

在这种情况下,它们返回相同的结果,没有区别。就性能而言,它取决于 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.

做个ˇ局外人 2024-09-13 21:23:55

正如其他人所说,它们对于一维数组是相同的。

恕我直言,从代码可读性的角度来看 length 应该用于一维数组。这是关于“意向编程”,你看到代码就明白程序员在构思时的想法他的工作。因此,当我看到 numel 时,我知道它是在矩阵上使用的。

lengthnumel 是我们团队多年来的讨论主题。前高级开发人员并不关心代码的可靠性,只关心正在完成的工作,并且仅在可读/格式不佳的代码中使用 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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文