MATLAB: Possible to vectorize matrix split and stack

matrixvectorize

Let's say that I have a 2D matrix that I want to divide into sections that have the same numbers of rows and columns, then stack the slices and store the result in a 3D matrix. I have included below a bit of test code using a for-loop that does this successfully, but is there a way to fully vectorize this splitting operation?
This is a task that is repeated many times in my code and is the only task in the workflow that isn't vectorized. I'm using GPUs and the Parallelization Toolbox for speed, so I was hoping to speed up this operation as well if possible. Thanks in advance.
My test code:
% my test matrix
a= rand(6,6);
% my "coordinates", stored in "b"
% lets assume I know exactly how large each "frame" taken out of my test
% matrix should be, which in this case will be a 4x4 pixel block
%

% first value is beginning row index
% second value is ending row index
% third value is beginning column index
% fourth value is ending row index
%
% each row will contain the coordinates for a "frame",
% so here I have specified 2 the coordinates for 2 frames.
b = [[1,4,1,4];
[2,5,2,5]];
% number of arrays to extract - same as # rows in b
num = size(b,1);
% initialize the final, stacked array
% size is known, as stated before
c = zeros( 4 ,4,num );
% extraction loop
for frame_num=1:num
c(:,:,frame_num) = a( b(frame_num,1):b(frame_num,2) , b(frame_num,3):b(frame_num,4) );
end

Best Answer

m=4; n=4; %desired block size
Q=reshape(1:numel(a), size(a));
t=Q(1:m,1:n)-1;
idx=sub2ind(size(a), b(:,1), b(:,3)).';
c=reshape( a( bsxfun(@plus,idx,t(:))) , m ,n ,[]);