Looping matrice index at a specific interval, probably with mod

7 次查看(过去 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

采纳的回答

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