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?

 채택된 답변

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

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.
Sounds good!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

릴리스

R2023b

태그

질문:

2024년 6월 4일

댓글:

2024년 6월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by