adding next values in an array

47 ビュー (過去 30 日間)
Nikolas Spiliopoulos
Nikolas Spiliopoulos 2017 年 2 月 17 日
編集済み: Nikolas Spiliopoulos 2017 年 2 月 17 日
hi all, I have a question
I have a vector like this [1;2;3;-5;-6;2;3], when it's negative i would like to add in the next value and get something like that [1;2;3;-5;-11;-9;-6]. Which means when it's negative it starts adding the next value!
the thing is that i have an array with 48x258 dimensions, so the example above would be for each column!
thanks a lot!
  4 件のコメント
Alexandra Harkai
Alexandra Harkai 2017 年 2 月 17 日
編集済み: Alexandra Harkai 2017 年 2 月 17 日
In this case -5 is negative so the next element will be -6+(-5)=-11. Then -11 is negative so the next element will be 2+(-11)=-9. Which is negative so the next becomes 3+(-9)=-6 which is negative so would you want to do anything with it?
I could be totally wrong understanding your logic.
Nikolas Spiliopoulos
Nikolas Spiliopoulos 2017 年 2 月 17 日
not really, i just need the logic for n elements,
in my real case it wont be my last element negative. This is just an example to understand the logic. thanks!

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

採用された回答

Guillaume
Guillaume 2017 年 2 月 17 日
編集済み: Guillaume 2017 年 2 月 17 日
M = [1 2 3 -5 -6 2 3]' %demo data
M + cumsum([zeros(1, size(M, 2)); M(1:end-1, :)] .* (cumsum(M<0, 1)>1), 1)
Will do what you want on any sized matrix.
Explanation of above code:
  1. M<0 finds sign of M
  2. cumsum(M<0, 1) will be 1 or more at the first negative value in each column
  3. cumsum(M<0, 1)>1 will be one after the first negative value all the way down
  4. [zeros(1, size(M, 2)); M(1:end-1, :)] is M shifted down by one row
  5. 4.*5 filters the shifted M so that all positive values before the first negative values are 0 AND the first negative value is 0
  6. cumsum of 6 + M is the desired result
  1 件のコメント
Nikolas Spiliopoulos
Nikolas Spiliopoulos 2017 年 2 月 17 日
編集済み: Nikolas Spiliopoulos 2017 年 2 月 17 日
thanks for the answer!! however, is there any way to do it with i and j (using for)? cos I would like to check if the sum value is negative or positive. If positive i need to stop the procedure until the next negative value! is it possible? thanks!

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

その他の回答 (1 件)

Alexandra Harkai
Alexandra Harkai 2017 年 2 月 17 日
Considering the last element on a column will not be added to any other elements, you can loop through the whole thing:
function [a] = addNegatives(a)
for col = 1:size(a,2) % for each column
for k = 1:size(a, 1)-1 % don't do it for the last element
if a(k, col) < 0
a(k+1, col) = a(k, col) + a(k+1, col);
end
end
end
end

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by