How to add every nth element of an array to the nth+1 element?

I wonder if there is a short expression for the task above. For example if I had an array like this
a = [1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8, 9]
How can I add, let's say every 3rd element to every 4th element to get an array like this ?
a = [1, 2, 3+3, 4, 5+5, 6, 7+7, 8, 9]
I can do this with some ugle lines of code, but what if you got a more elegant way?

 Respuesta aceptada

a = [1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8, 9];
a(3:3:end-1) = a(3:3:end-1)+a(4:3:end);
a(4:3:end) = []
a = 1x9
1 2 6 4 10 6 14 8 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

4 comentarios

haha, this is exactly the same solution that I got, but for me this looks really inconvenient.
Or do you really need to index like that?
Voss
Voss el 4 de Jun. de 2024
Editada: Voss el 4 de Jun. de 2024
Generating a vector of indices using the colon operator is the standard way to get every nth element or every nth+1 element. I can't think of a better way.
Maybe storing the indices would make the code a little neater/clearer in your opinion:
a = [1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8, 9];
idx = 3:3:numel(a)-1;
a(idx) = a(idx)+a(idx+1);
a(idx+1) = []
a = 1x9
1 2 6 4 10 6 14 8 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Or maybe you prefer this:
a = [1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8, 9];
tmp = a(4:3:end);
a(4:3:end) = [];
a(3:2:end-1) = a(3:2:end-1)+tmp
a = 1x9
1 2 6 4 10 6 14 8 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Allright thanks. I'll just create a function to make it cleaner and hide the operations.
Sounds good!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Productos

Versión

R2023b

Etiquetas

Preguntada:

el 4 de Jun. de 2024

Comentada:

el 4 de Jun. de 2024

Community Treasure Hunt

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

Start Hunting!

Translated by