adding next values in an array
Afficher commentaires plus anciens
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 commentaires
Alexandra Harkai
le 17 Fév 2017
Modifié(e) : Alexandra Harkai
le 17 Fév 2017
What would you like to do when the last element of a column is negative?
Nikolas Spiliopoulos
le 17 Fév 2017
Alexandra Harkai
le 17 Fév 2017
Modifié(e) : Alexandra Harkai
le 17 Fév 2017
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
le 17 Fév 2017
Réponse acceptée
Plus de réponses (1)
Alexandra Harkai
le 17 Fév 2017
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
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!