For Loop operating with last and first entry of array
조회 수: 1 (최근 30일)
이전 댓글 표시
If i have an array like this:
A=[1;5;6;8];
and i apply a simple for loop like this:
for k=1:4
B(k)=A(k)+A(k+1);
end
How can i write the code, so the last entry of my array A makes the operation with the first entry aswell, namely 8+1=9?
댓글 수: 0
답변 (1개)
David Fletcher
2018년 4월 4일
편집: David Fletcher
2018년 4월 4일
Like this?
A=[1;5;6;8];
B=A(1:length(A))+[A(2:length(A));A(1)]
B =
6
11
14
9
댓글 수: 2
David Fletcher
2018년 4월 4일
So you want it to operate as in the previous example but summing successive rows of a 2D matrix (and the last and first row) rather than the columns of the 1D matrix that you presented as your example?
Like this:
A=[1 1 1 1;2 2 2 2;3 3 3 3;4 4 4 4]
B=A(1:size(A),:)+[A(2:size(A),:);A(1,:)]
A =
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
B =
3 3 3 3
5 5 5 5
7 7 7 7
5 5 5 5
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!