Looping matrice index at a specific interval, probably with mod

조회 수: 6 (최근 30일)
Dogan Akcakaya
Dogan Akcakaya 2021년 1월 18일
편집: Dogan Akcakaya 2021년 1월 18일
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

채택된 답변

Cris LaPierre
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
out = 10×4
1 2 4 5 2 3 5 6 3 1 6 4 1 2 4 5 2 3 5 6 3 1 6 4 1 2 4 5 2 3 5 6 3 1 6 4 1 2 4 5
  댓글 수: 1
Dogan Akcakaya
Dogan Akcakaya 2021년 1월 18일
Thanks Cris. That'a good solution. By the way, I found another one. Taking mod same as first one, then adding an extra 3, total 4.
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) + 4))^2;
end
end

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by