MATLAB Answers

0

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

Asked by abraham rodriguez on 5 Sep 2018
Latest activity Edited by abraham rodriguez on 5 Sep 2018
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?

  0 Comments

Sign in to comment.

1 Answer

the cyclist 님의 답변 5 Sep 2018
the cyclist 님이 편집함. 5 Sep 2018

test = [1 2 3];
N = numel(test);
idx = [1:N; [2:N,1]];
consecutiveSum = sum(test(idx));

  0 Comments

Sign in to comment.