MATLAB: Looping matrice index at a specific interval, probably with mod

indexindexingMATLABmatrices

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

Best Answer

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