Sum only consecutive positive numbers and place the sum in a new vector in specific positions
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi!
I have this variable P1 (attached) and i want to make the sum of ONLY consecutive positive values and place the sum in a new vector (out) in the position that you can see in Figure. In there is only one value you can place it in the same position of P1, otherwise, place it in the lowest consecutive positive position. For the other values of out i want zero.
I tried with this but it is not doing what i want...
Thanks in advance!!!
lo = P1 > 0;
h5 = cumsum(diff([0;lo(:)]) == 1).*lo(:);
out = accumarray(h5 + 1,P1);
2 Kommentare
Antworten (1)
Thiago Henrique Gomes Lobato
am 22 Mär. 2020
Try this:
lo = P1 > 0;
Dfference = diff([lo(:);0]);
Ends = find(Dfference==-1); % -1 are the positions where a sequence ends
Start = find(Dfference==1)+1; % 1 are the positions where a sequence starts -1
% loop only over the founded sequences
out = zeros(size(P1));
for idx=1:length(Start)
out(Ends(idx)) = sum(P1(Start(idx):Ends((idx))));
end
7 Kommentare
Thiago Henrique Gomes Lobato
am 5 Apr. 2020
Add those changes:
if length(Ends)>length(Start)
Start = [Ends(1);Start];
end
SP = zeros(size(P1));
for idx=1:length(Start)
End = min(Ends(idx)+2,length(P1));
SP(Ends(idx):End) = sum(P1(Start(idx):Ends((idx)))); % this is the part of code you missed in the previous answer
end
Siehe auch
Kategorien
Mehr zu Delaunay Triangulation 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!