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
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!