How to find cumulative sum from from-to matrix?

1 回表示 (過去 30 日間)
Real A
Real A 2022 年 5 月 10 日
回答済み: DGM 2022 年 5 月 10 日
If A is from-to matrix and B is route
A =[0 10 20 30; 40 0 50 60; 70 80 0 90; 100 110 120 0],
B = [1 2 3 4;2 4 3 1]
How to find cumulative sum
C = [0 (0+10) (0+10+50) (0+10+50+90); 0 (0+60) (0+60+120) (0+60+120+70)]
C = [0 10 60 150; 0 60 180 250]

採用された回答

DGM
DGM 2022 年 5 月 10 日
From the other comment:
A = [0 10 20 30; 40 0 50 60; 70 80 0 90; 100 110 120 0];
B = [1 2 3 4;2 4 3 1];
% x (1,2) (2,3) (3,4) x (2,4) (4,3) (3,1)
%C = [0 (0+10) (0+10+50) (0+10+50+90); 0 (0+60) (0+60+120) (0+60+120+70)]
%C = [0 10 60 150; 0 60 180 250]
% each column of BB is a row,col subscript pair into A
% each page of BB corresponds to each row of B
BB = repelem(B,1,2);
BB = reshape(permute(BB(:,2:end-1),[3 2 1]),2,[],size(B,1));
% convert to linear indices
BB = permute(sub2ind(size(A),BB(1,:,:),BB(2,:,:)),[3 2 1]);
% do sum and pad
C = cumsum(A(BB),2);
C = [zeros(size(C,1),1) C]
C = 2×4
0 10 60 150 0 60 180 250

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by