Info

此问题已关闭。 请重新打开它进行编辑或回答。

How do I do calculations with the last and first array member in a for loop?

1 次查看(过去 30 天)
for example, I want to show another matrix that its elements are the sum of consecutive members in the original array, and the last showing the sum of the last with the first element, without explicitly managing the last case.
test = [1 2 3];
consecutiveSum = [ test(1) + test(2) , test(2) + test(3) , test(3) + test(1) ];
How can I implement this in a for loop?

回答(1 个)

the cyclist
the cyclist 2018-9-5
编辑:the cyclist 2018-9-5
test = [1 2 3];
N = numel(test);
idx = [1:N; [2:N,1]];
consecutiveSum = sum(test(idx));

此问题已关闭。

产品


版本

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by