【问题标题】:Best way to retrieve the number of elements in a vector in matlab在matlab中检索向量中元素数量的最佳方法
【发布时间】:2016-11-17 09:36:13
【问题描述】:

我想知道在速度方面在matlab中检索向量中元素数量的最佳方法是什么:

是吗:

  1. length(A)

  1. size(A,1)

【问题讨论】:

  • 还有numel,速度非常快。请查看this 问题进行简短讨论

标签: matlab size dimensions


【解决方案1】:

两者都没有。为此,您希望始终使用numellength 只返回最长的维度(这可能会让二维数组感到困惑),size(data, dimension) 要求您知道它是行向量还是列向量。 numel无论是行向量、列向量还是多维数组都会返回元素个数。

我们可以通过编写快速基准测试轻松测试这些性能。我们将使用各种方法获取大小N 次(为此我使用了 10000)。

function size_test

    nRepeats = 10000;

    times1 = zeros(nRepeats, 1);
    times2 = zeros(nRepeats, 1);
    times3 = zeros(nRepeats, 1);

    for k = 1:nRepeats
        data = rand(10000, 1);
        tic
        size(data, 1);
        times1(k) = toc;
        tic
        length(data);
        times2(k) = toc;
        tic
        numel(data);
        times3(k) = toc;
    end

    % Compute the total time required for each method
    fprintf('size:\t%0.8f\n', sum(times1));
    fprintf('length:\t%0.8f\n', sum(times2));
    fprintf('numel:\t%0.8f\n', sum(times3));
end

在我的机器上运行时会产生:

size:   0.00860400
length: 0.00626700
numel:  0.00617300

因此,numel 除了是最强大的之外,还比其他替代方案稍快。

话虽如此,除了确定数组中元素的数量之外,您的代码中可能还有许多其他瓶颈,因此我将专注于优化这些。

【讨论】:

  • 我发布了相同的答案,但后来我删除了它。 OP 写了vector 而不是matrix。我想他是在考虑矩阵的一维是一!
  • @Sardar_Usama 没关系。不管怎样,答案总是numel
  • length(A)size(A,1)size(A,2) 如果矩阵的维度之一是 1,也会执行相同的操作。这就是我的意思
  • @Sardar_Usama 我知道它们都产生相同的结果,但numel 是正确/最可靠的方法。
  • @Sardar_Usama 添加了一个基准来展示numel 的实际性能优势。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多