How do I cycle elements through each index of patches of a matrix without explicitly iterating through each patch?
The iterative way I can think to perform this cycling is with MATLAB's circshift
function. I could iterate through each MxN patch in my matrix, and perform a circular shift on the elements of that patch.
(NOTE: circshift
takes an array and moves the first (or k-th) index to the back, shifting everything forward to make room. With a matrix, you just vectorize it, shift it, and reshape back, taking advantage of MATLAB's column-major linear indexing)
That would be great if I were to iterate through every MxN window of my larger (j*M x k*N for integers j,k) matrix. However, I'd like to be able to avoid for loops and take advantage of MATLAB's vectorized code to do this in one fell swoop.
One full iteration through an example (2x2 patches in some matrix B) would be:
B = --> B = --> B = --> B =
[ 5 6 7 8 ] --> [ 5 6 7 8 ] --> [ 6 5 8 7 ] --> [ 6 5 8 7 ]
[ 5 6 7 8 ] --> [ 6 5 8 7 ] --> [ 6 5 8 7 ] --> [ 5 6 7 8 ]
[ 5 6 7 8 ] --> [ 5 6 7 8 ] --> [ 6 5 8 7 ] --> [ 6 5 8 7 ]
[ 5 6 7 8 ] --> [ 6 5 8 7 ] --> [ 6 5 8 7 ] --> [ 5 6 7 8 ]
Any ideas how to make this shift work without explicitly iterating through every patch? I feel like linear indexing is the key here, but I'm not sure why. I also don't care about the order of rotation as long as every patch element ends up in every patch index.
Thanks in advance!
EDIT: Here's a copy-and-paste-able toy implementation using for loops to demonstrate what I'm looking for. The only for loop that should be included in an answer is the k
-iterator (controls how many shifts ultimately need to be made)
A = repmat(1:4, 4, 1); % Input matrix
% k represents the total number of shifts to be made
for k = 1:4
% Iterate through each patch
for i = 1:2:size(A,1)
for j = 1:2:size(A,2)
tmp = A(i:i+1,j:j+1); % Isolate specific patch
% Circularly shift the vectorized patch, reshape it to a matrix
% and insert it back into the original matrix
A(i:i+1,j:j+1) = reshape(circshift(tmp(:),1), 2, 2);
end
end
display(A) % Display each completely shifted iteration
end