필터 지우기
필터 지우기

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

조회 수: 6 (최근 30일)
Niklas Kurz
Niklas Kurz 2024년 6월 4일
댓글: Voss 2024년 6월 4일
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?

채택된 답변

Voss
Voss 2024년 6월 4일
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
Niklas Kurz
Niklas Kurz 2024년 6월 4일
Allright thanks. I'll just create a function to make it cleaner and hide the operations.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by