Cumulative Summation down a matrix in loop keeping total per section

1 visualización (últimos 30 días)
Hello!
I have 2 matrix, I would like to sum Matrix B values running cummulative given condition. The condition is that it starts to sum once Matrix A = 1 and stops when Matrix A = -1 and it goes on and on all the way down to the end of the data set. Thanks for the help!
Matrix A Matrix B CumSum (New Matrix)
0
0
0
1 0
1 0.02 .02
1 -12.09 -12.07
1 6.61 -5.46
-1 1.1 -4.36
0 0
1 0
1 -6.8 -6.8
1 -26.87 -33.67
1 2.67 -31
1 -9.99 -40.99
1 9.28 -31.71
1 -3.17 -34.88
-1 8.6 -26.28
0
0
0

Respuesta aceptada

Abhijeet
Abhijeet el 11 de Jun. de 2022
Hello IDN,
I can understand that you want to calculate prefix sum of vector B based on condition provided by vector A. I have added a code sample for the same task below.
Assumption made
  • Size of matrix A and B are equal
  • Every -1 in matrix A is preceded by +1
A = [ 0 0 0 1 1 1 -1 0 0 1 1 -1]
B= [ 0 0 0 34 4 4 6 0 0 12 3 3]
sz =size(A)
% matrix to store the cummalative sum
cumSum = zeros(sz)
%flag variable to tell when to start add elements
startSum = true
for idx=1:sz(2)
if A(idx)==0
continue
elseif A(idx)==1
if startSum==true
cumSum(idx)=B(idx)
startSum=false
else
cumSum(idx)=B(idx)+cumSum(idx-1)
end
else
cumSum(idx)=B(idx)+cumSum(idx-1)
startSum=true
end
end

Más respuestas (1)

DGM
DGM el 11 de Jun. de 2022
Following the what's implied by the example:
somedata = readmatrix('https://www.mathworks.com/matlabcentral/answers/uploaded_files/1028400/Sum%20Sample.xlsx');
somedata = somedata(somedata(:,1)~=0,:); % get rid of padding rows
endmarkers = [0; find(somedata(:,1) == -1)];
nblocks = numel(endmarkers)-1;
S = cell(nblocks,1);
for k = 1:nblocks
% each block starts at endmarkers(k)+2 because the given example
% indicates that the first row where col1 is 1 is not considered when taking the sum
S{k} = cumsum(somedata(endmarkers(k)+2:endmarkers(k+1),2));
end
celldisp(S)
S{1} = 0.0200 -12.0700 -5.4600 -4.3600 S{2} = -6.8000 -33.6700 -31.0000 -40.9900 -31.7100 -34.8800 -26.2800
  1 comentario
IDN
IDN el 11 de Jun. de 2022
Thanks for taking the time to help me out. This is great but for this particular case i would like them to be lined up with the the Matrix B order. So i would like for it to keep its sequence down the rows (which includes the zeroes. Like the example below, the only issue with the example below is that i am not able to get it to work for some reason. Appreciate any further feedback!

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Productos


Versión

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by