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

4 次查看(过去 30 天)
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