【问题标题】:How to sum all other rows in MATLAB如何对MATLAB中的所有其他行求和
【发布时间】:2012-11-11 11:39:27
【问题描述】:

我还在学习 MATLAB 的一些高级功能。

我有一个二维矩阵,我想对所有行求和,除了 i。

例如

1 1 1
2 2 2
4 4 4

说 i = 2,我想得到这个:

5 5 5

我可以通过对所有行求和,然后减去第 i 行来做到这一点,但我想知道是否有更快的方法使用 MATLAB 的索引/选择语法。

【问题讨论】:

    标签: matlab matrix sum


    【解决方案1】:

    似乎对所有行求和,然后减去第 i 行,要快得多:

    A=rand(500);
    n = randi(500);
    tic
    for i=1:1e3
    %sum(A([1:n-1 n+1:end], :));
    sum(A)-A(n,:);
    end
    toc
    
         Elapsed time is 0.162987 seconds.
    
    A=rand(500);
    n = randi(500);
    tic
    for i=1:1e3
    sum(A([1:n-1 n+1:end], :));
    end
    toc
    
         Elapsed time is 1.386113 seconds.
    

    【讨论】:

    • 你有一台相当快的电脑,奈特。你在用什么?我有一个 i7 2.8GHz,我的结果比你的慢 4 倍。这让我很担心 :)
    【解决方案2】:

    增加以前作者的性能考虑。 nate 的解决方案更快,因为它不使用第二种方法的复杂矩阵索引。复杂矩阵/向量索引is very inefficient in MATLAB。我怀疑这与引用问题中描述的索引问题相同。

    考虑以下简单测试,遵循之前的框架:

    A=rand(500);
    n = randi(500);
    tic
    for i=1:1e3
        B=sum(A(:, :));
    end
    toc
    Elapsed time is 0.747704 seconds.
    
    tic
    for i=1:1e3
        B=sum(A(1:end, :));
    end
    toc
    Elapsed time is 5.476109 seconds.   % What ???!!!
    
    tic
    id = [1:n-1 n+1:500];
    for i=1:1e3
        B=sum(A(id, :));
    end
    toc
    Elapsed time is 5.449064 seconds.
    

    【讨论】:

      【解决方案3】:

      好吧,你可以这样做:

      >> A = [ 1 1 1
               2 2 2
               4 4 4];
      >> n = 2;
      >> sum(A([1:n-1 n+1:end], :))
      ans = 
          5 5 5
      

      然而,正如 Nate 已经指出的那样,尽管它看起来不错,但它实际上比仅减去我建议不要使用它的单行要慢得多 :)

      【讨论】:

      • @nate: 嗯...现在为什么会SO慢得多?这是一个数量级,即使您解开索引的创建...
      • 它很慢,因为 MATLAB 中的索引效率低下 :)
      • @angainor:是的,前几天我看到了您的问题/分析...您是否向 TMW 提交了性能错误?缓慢似乎完全没有必要......
      • 我在 matlab 中心有 reposted the question。希望TMW的人愿意回答。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 2019-05-05
      • 1970-01-01
      • 2014-05-07
      • 2019-04-11
      • 2013-04-11
      • 2021-10-14
      相关资源
      最近更新 更多