Sum per 2 elements in vector

17 visualizzazioni (ultimi 30 giorni)
Ann-Lara Aernoudts
Ann-Lara Aernoudts il 25 Gen 2021
Risposto: Abdel il 18 Set 2023
Hello,
I am trying to sum my vector by 2 elements.
An example:
I have:
A= [1;2;3;4;5;6]
What I want:
A_new = [3;7;11]
Is there any way to easily code this?
I know one way via a for-loop but I was wondering if there was a more efficient way.
Thanks in advance!

Risposta accettata

Stephen23
Stephen23 il 25 Gen 2021
Modificato: Stephen23 il 25 Gen 2021
A = [1;2;3;4;5;6];
B = A(1:2:end) + A(2:2:end)
B = 3×1
3 7 11
or more generally:
B = sum(reshape(A,2,[]),1).'
B = 3×1
3 7 11
or
B = reshape(A,2,[]).' * ones(2,1)
B = 3×1
3 7 11
or
B = cellfun(@sum,mat2cell(A,2*ones(1,3),1))
B = 3×1
3 7 11
  1 Commento
Ann-Lara Aernoudts
Ann-Lara Aernoudts il 25 Gen 2021
Perfect, that works!
I'll use the more general code.
Thank you!

Accedi per commentare.

Più risposte (1)

Abdel
Abdel il 18 Set 2023
The sum of the last two elements in (call the result ans6)

Categorie

Scopri di più su Operating on Diagonal Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by