How count positive numbers, but when you get a negative, the sum stops. so then, sum the following sequence of positive numbers..

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2012년 10월 13일
편집: Andrei Bobrov 2012년 10월 13일
v = [1 1 -1 1 1 1 -1 -1 1];
z = v > 0;
id = find([true;diff(v.') ~= 0]);
k = diff([id;numel(v)+1]);
out = k(z(id));
or use Image Processing Toolbox
v = [1 1 -1 1 1 1 -1 -1 1]
z = v > 0;
s = regionprops(z, 'Area');;
out = [s.Area];
or
v = [1 1 -1 1 1 1 -1 -1 1];
v1 = [-v(1)*sign(v(1)),v,-v(end)*sign(v(end))];
out = strfind(v1,[1, -1])-strfind(v1,[-1 1]);

추가 답변 (2개)

Wayne King
Wayne King 2012년 10월 13일
편집: Wayne King 2012년 10월 13일
x = randn(100,1);
sum(x(x>0))
For an example with integers:
x = randi([-5 5],20,1);
sum(x(x>0))

댓글 수: 1

Thanks, but I just want to sum the sequence of positive numbers that are together, not all positive
Regards Claudio

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

sum(x(1 : find(x <= 0, 1)))
or
sum(x .* cumprod(x > 0))

댓글 수: 1

Thanks Walter, but I just want to sum the sequence of positive numbers that are together
Example
v =
1 1 -1 1 1 1 -1 -1 1
%sum the sequence of positive numbers that are together
sol =
2 3 1

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

카테고리

도움말 센터File Exchange에서 MATLAB에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

질문:

2012년 10월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by