How to find cumulative sum in matrix?

3 Ansichten (letzte 30 Tage)
Real A
Real A am 9 Mai 2022
Kommentiert: DGM am 10 Mai 2022
If I have A =[10 20 30 ;40 50 60;70 80 90], B = [1 2 3 ;2 3 1;3 2 1]
and i want to find cumulative sum from A in previous position follow seq. in B.
---> C = [(0) (0+10) (0+10+20); (0) (0+50) (0+50+60); (0) (0+90) (0+90+80)]
C = [0 10 30; 0 50 110; 0 90 170]
How to code this? thank you.

Akzeptierte Antwort

DGM
DGM am 9 Mai 2022
Bearbeitet: DGM am 9 Mai 2022
Here is one way:
A = [10 20 30; 40 50 60; 70 80 90];
B = [1 2 3; 2 3 1; 3 2 1];
nrows = size(A,1);
C = cumsum(A((1:nrows).' + nrows*(B-1)),2); % use linear indexing
C = [zeros(nrows,1) C(:,1:end-1)]
C = 3×3
0 10 30 0 50 110 0 90 170
  2 Kommentare
Real A
Real A am 10 Mai 2022
Thak you so much ,but I have another question
if A is from-to matrix and B is routing
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 am 10 Mai 2022
See if this is what you're after
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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Operating on Diagonal Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by