Sum only consecutive positive numbers and place the sum in a new vector in specific positions

조회 수: 2 (최근 30일)
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);

답변 (1개)

Thiago Henrique Gomes Lobato
Thiago Henrique Gomes Lobato 2020년 3월 22일
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
EM geo
EM geo 2020년 3월 26일
편집: EM geo 2020년 3월 26일
@Thiago Henrique Gomes Lobato
I'm sorry I uploaded the wrong file. Try with this file and with this code (your code completed with all your suggestions).
lo = P1 > 0;
Dfference = diff([lo(:);0]);
Ends = find(Dfference==-1);
Start = find(Dfference==1)+1;
SP = zeros(size(P1));
for idx=1:length(Start)
SP(Ends(idx):Ends(idx)+3) = sum(P1(Start(idx):Ends((idx)))); % this is the part of code you missed in the previous answer
end
However result are not right. As you can see the first data is has P1 > 0 so I expected to have out = 39 and repeat it for the following two rows.
This in an example of how results should be:
%P1 %out
39 39 %here P1 is >0 so i expect to have out =39
-2 39
-2 39
-2 0
-2 0
-2 0
-2 0
-2 0
-2 0
-2 0
-2 0
60 0
39 99 %here I have 60 and 39 that are >0, so i want their sum (99) placed here
-2 99
-2 99
-2 0
-2 0
-2 0
-2 0
-2 0
-2 0
-2 0
-2 0
60 0
39 99
-2 99
-2 99
-2 0
-2 0
-2 0
-2 0
-2 0
-2 0
-2 0
-2 0
60 60
Thank you so much!!!!!!!!!
Thiago Henrique Gomes Lobato
Thiago Henrique Gomes Lobato 2020년 4월 5일
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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Delaunay Triangulation에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by