Sum only consecutive positive numbers...

Hi all, I need help. So, I have this vector:
l = [1 2 -3 4 -5 6 7 -8 9 10 11 12];
I need sum only consecutive positive numbers. when picking up a negative number, put NaN. So, the results correct is:
a = [3 NaN 4 NaN 13 NaN 42];
Thank you!
Best regards.

回答 (3 件)

ANKUR KUMAR
ANKUR KUMAR 2017 年 10 月 30 日

1 投票

A = [1 2 -3 4 -5 6 7 -8 9 10 11 12];
A(A<=0)=nan;
nansum(A)

2 件のコメント

Walter Roberson
Walter Roberson 2017 年 10 月 30 日
No, this gives a grand total of the positive values, rather than giving the required output vector.
ANKUR KUMAR
ANKUR KUMAR 2017 年 10 月 30 日
Ops, Sorry. I misread the question.

サインインしてコメントする。

Image Analyst
Image Analyst 2017 年 10 月 30 日

0 投票

Here's one way:
m = [1 2 -3 4 -5 6 7 -8 9 10 11 12]
dm = [1. diff(m)]
mask = (m > 0) & (dm >= 0)
props = regionprops(mask, m, 'Area', 'MeanIntensity');
sums = [props.Area] .* [props.MeanIntensity]
% Add in nan's
sums = [sums; nan(1, length(sums))]
sums = sums(:)'
% Get rid of last nan.
sums = sums(1:end-1)
Andrei Bobrov
Andrei Bobrov 2017 年 10 月 30 日
編集済み: Andrei Bobrov 2017 年 10 月 30 日

0 投票

l = [1 2 -3 4 -5 6 7 -8 9 10 11 12];
lo = l > 0;
h = cumsum(diff([0;lo(:)]) == 1).*lo(:);
S = accumarray(h + 1,l);
out = nan(numel(S)*2-1,1);
out(1:2:end) = S;
or
l = [1 2 -3 4 -5 6 7 -8 9 10 11 12];
lo = l > 0;
h = diff([~lo(1),lo])~=0;
out = accumarray(cumsum(h(:)),l);
out(out < 0) = nan;

カテゴリ

ヘルプ センター および File ExchangeResizing and Reshaping Matrices についてさらに検索

タグ

質問済み:

2017 年 10 月 30 日

コメント済み:

2017 年 10 月 30 日

Community Treasure Hunt

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

Start Hunting!

Translated by