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

Asked by Claudio Iturra on 13 Oct 2012
Latest activity Commented on by Claudio Iturra on 13 Oct 2012

Example

v =

     1     1    -1     1     1     1    -1    -1     1
%sum the sequence of positive numbers that are together

sol =

     2     3     1

Regards Claudio

0 Comments

Claudio Iturra

Tags

No tags are associated with this question.

Products

No products are associated with this question.

3 Answers

Answer by Andrei Bobrov on 13 Oct 2012
Edited by Andrei Bobrov on 13 Oct 2012
Accepted answer
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]);

1 Comment

Claudio Iturra on 13 Oct 2012

Thanks

Andrei Bobrov

You are the Best ¡

Andrei Bobrov
Answer by Wayne King on 13 Oct 2012
Edited by Wayne King on 13 Oct 2012
x = randn(100,1);
sum(x(x>0))

For an example with integers:

x = randi([-5 5],20,1);
sum(x(x>0))

1 Comment

Claudio Iturra on 13 Oct 2012

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

Regards Claudio

Wayne King
Answer by Walter Roberson on 13 Oct 2012
sum(x(1 : find(x <= 0, 1)))

or

sum(x .* cumprod(x > 0))

1 Comment

Claudio Iturra on 13 Oct 2012

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
Walter Roberson

Contact us