- Size of matrix A and B are equal
- Every -1 in matrix A is preceded by +1
Cumulative Summation down a matrix in loop keeping total per section
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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
0 comentarios
Respuesta aceptada
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
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
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)
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!