Looping matrice index at a specific interval, probably with mod
조회 수: 6 (최근 30일)
이전 댓글 표시
Hey,
I have the following code. And without changing loop index j or putting if-else statements, I want to make my calculation work. What I want to do is,
I want to get 1. and 2. then 4. and 5. elements of a matrix and calculate a value. Then 2. and 3. and 5. and .6. Finally 3. and back to 1. and 6. and back to 4. I already handle the first part, going to 1. after 3. but the second part 6. to 4. is a problem. And also I will generalize this for different matrice sizes, j up to 4, 5 etc. All recommendations are appreciated.
Thanks.
A = zeros(3,3);
B = rand(3,6);
% B = [b1 b2 b3 b4 b5 b6]
% A = [((b1-b2)^2+(b4-b5)^2) ... ((b3-b1)^2+(b6-b4)^2)]
for i=1:3
for j=1:3
A(i,j) = (B(i, j) - B(i, mod(j,3)+1))^2 ...
+ (B(i, j+3) - B(i, mod(j+3,6)+1))^2;
end
end
댓글 수: 0
채택된 답변
Cris LaPierre
2021년 1월 18일
You could do something like this. This loop just creates an array showing the results. Each row would be the indices to use for a particular loop.
for i=1:10
ind1 = 1+mod(i-1,3);
ind2 = 4+mod(i-1,3);
out(i,:) = [1+mod(i-1,3) 1+mod(i,3) 4+mod(i-1,3) 4+mod(i,3)];
end
out
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!