Vector with various IFs, adding up and counting down

1 回表示 (過去 30 日間)
dirk-jAn
dirk-jAn 2018 年 6 月 19 日
コメント済み: dirk-jAn 2018 年 8 月 18 日
I need to translate an Excel formula to whatsapp.
I have one vector X: [ 5 2 -4 -6 -2 1 4 2 -3 -6 -1 8 9 ]
Now, vector y needs to accumulate if vector x is negative and the opposite when positive until back to zero: [ 0 0 -4 -10 -12 -11 -7 -5 -8 -14 -15 -7 0 ]
I have been looking through Matlab functions but don't come far. Is there any easy way to do this on Matlab?
Many thanks in advance!

回答 (1 件)

Paolo
Paolo 2018 年 6 月 19 日
X = [ 5 2 -4 -6 -2 1 4 2 -3 -6 -1 8 9 ];
indx = find(X<0);
Y = [zeros(1,indx(1)-1) cumsum(X(indx(1):end))];
Y(Y>0) = 0;
Y =
Columns 1 through 11
0 0 -4 -10 -12 -11 -7 -5 -8 -14 -15
Columns 12 through 13
-7 0
  2 件のコメント
dirk-jAn
dirk-jAn 2018 年 8 月 16 日
Thanks Paolo. This answer indeed solves perfectly the example I gave. However, if the series are longer and come back into negative after some positive values, the positive values should not be added up, so a negative value should directly lead to a decrease below 0, e.g.:
X: [ 5 2 -4 -6 -2 1 4 2 -3 -6 -1 8 9 5 -6 -11]
should not be
[ 0 0 -4 -10 -12 -11 -7 -5 -8 -14 -15 -7 0 0 0 -10 ] as it is now, but should be:
[ 0 0 -4 -10 -12 -11 -7 -5 -8 -14 -15 -7 0 0 -6 -17]
In other words, positive numbers between series of negatives should be treated the same as the positive numbers at the very start.
Again thanks in advance for solving this.
dirk-jAn
dirk-jAn 2018 年 8 月 18 日
I think it is solved:
X = [ 5 2 -4 -6 -2 1 4 2 -3 -6 -1 8 9 5 -6 -11];
X(X(1)>0)=0;
Y=X;
for n=2:length(X)
if sum(Y(n-1:n)) > 0
Y(n)=0;
else
Y(n)=sum(Y(n-1:n));
end
end

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2015a

Community Treasure Hunt

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

Start Hunting!

Translated by