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?

 Accepted Answer

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 Comments

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?
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.

Sign in to comment.

More Answers (0)

Products

Release

R2023b

Tags

Asked:

on 4 Jun 2024

Commented:

on 4 Jun 2024

Community Treasure Hunt

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

Start Hunting!