【问题标题】:Summing matrices in matlab (with a twist)matlab中的求和矩阵(有一个扭曲)
【发布时间】:2020-10-01 11:56:30
【问题描述】:

我有一个矩阵 H,它的大小是 6×6。

我需要对三件事求和,首先我需要h_ii,然后我需要对包含元素i 的所有其他元素求和,除了h_ii。然后我需要所有其他不包含j

为了形象化,我们创建了下图,

所以从图中,

对于矩阵的每个对角线,h11h22、...、h66

我需要对橙色(包含所有ij 单元格的单元格)和黄色相加(不包含i 的单元格,jj 单元格)。

我试图对各个列和行求和,但这变得非常混乱。

理想情况下,我需要给出矩阵,它会产生h11 = Xh11_orange = Yh11_yellow = Z

【问题讨论】:

    标签: matlab matrix sum


    【解决方案1】:

    您可以使用这个矢量化版本:

    green = diag(H);
    orange = sum(H,1).' + sum(H,2) - 2* green;
    yellow = sum(H(:)) - orange - green;
    

    【讨论】:

    • 我觉得orange里面需要-2*green,不然就太brown了:P
    • 我认为您可以轻松地将其扩展为非对角元素; green=H; orange = sum(H,1)+sum(H,2)-2*green,通过在加号上使用隐式广播。比我的更好更快的解决方案,这应该被 IMO 接受。
    • 我认为 @flawr 的 cmets 应该被接受。因为提供了很好的建议并纠正了我的错误。它是用幽默的语言写的,我认为我们在大流行期间特别需要这种语言!
    【解决方案2】:
    h=magic(6);
    out = zeros(size(h,1),size(h,2),3);  % Initialise output
    out(:,:,1) = h;  % Copy the green
    
    for ii = 1:size(h,1)
        for jj = 1:size(h,2)
            % out(ii,jj,1) = h(ii,jj);  % Green bit
            % For orange, sum the row and column. Note the .' transpose,
            % otherwise implicit broadcasting on the plus will create a matrix.
            % Finally remove the green cell twice,
            % as you added it in both row and column
            out(ii,jj,2) = sum(h(ii,:)+h(:,jj).') - h(ii,jj)*2;
            % Sum everything for yellow, and subtract the orange and green
            out(ii,jj,3) = sum(h,'all') - out(ii,jj,2) - h(ii,jj)
        end
    end
    

    这将生成一个 3D 输出矩阵,即它与输入矩阵的大小相同,其中绿色、橙色和黄色部分各有 3 页。请参阅代码中的 cmets 了解其作用。

    感谢flawr your comment 提高黄色求和的速度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多