Effacer les filtres
Effacer les filtres

Adding each row to previous row in a vector-Not Cumulative

3 vues (au cours des 30 derniers jours)
Hajik zagori
Hajik zagori le 20 Juil 2011
Hi , I've looked everywhere to find the solution for this but I couldn't find the answer. Here 's the problem. How to add each row in a vector with just the previous row? For example here is the process on this vector: A=[2 1 7 9 4] and the answer should be this vector: C=[3 8 16 13]
Thanks in advance.

Réponse acceptée

Sukuchha
Sukuchha le 20 Juil 2011
A=[2 1 7 9 4]; B = A(1:end-1)+diff(cumsum(A));
  1 commentaire
Jan
Jan le 20 Juil 2011
diff(cumsum(A)) ?! An expensive method to get: A(2:end). But in addition there is the danger of rounding errors, e.g. diff(cumsum([1e16, 1, 5])) is [0, 4] ! Therefore I strongly recommend not to use this.

Connectez-vous pour commenter.

Plus de réponses (3)

Jan
Jan le 20 Juil 2011
Easier and faster:
B = A(1:end-1) + A(2:end)
  2 commentaires
Sukuchha
Sukuchha le 21 Juil 2011
Jan, your method is better ! i feel like stupid now ! I need to remember always solve problems in a simplier way !
Jan
Jan le 21 Juil 2011
@Sukuchha: Often a direct translation of the human language is helpful. You've formulated your algorithm very clear already: "add each row in a vector with just the previous row". So you did solve the biggest part of the problem already. Most of the questions in this forum are much less clear.

Connectez-vous pour commenter.


Paulo Silva
Paulo Silva le 20 Juil 2011
C=arrayfun(@(x)plus(A(x),A(x-1)),2:numel(A))
or with a for loop
C=zeros(1,size(A,2)-1);
for x=2:size(A,2)
C(x-1)=A(x)+A(x-1);
end
C

Hajik zagori
Hajik zagori le 20 Juil 2011
I used Sukuchha method and it worked.Thanks Sukuchha. But I should also thank Paulo Silva.

Community Treasure Hunt

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

Start Hunting!

Translated by