Matlab: efficiently creating subarrays from an array
I have a matrix m x m
M
that I am sampling for different parts to generate sub-matrices k
into the matrix n x n x k
N
. I'm wondering: Could this be done efficiently without a for loop?
Here's a simple example:
M = [1:10]'*[1:10]; %//' Large Matrix indxs = [1 2;2 1;2 2]; N = zeros(4,4,3); %// Matrix to contain subarrays for i=1:3, N(:,:,i) = M(3-indxs(i,1):6-indxs(i,1),3-indxs(i,2):6-indxs(i,2)); end
In my actual code, the matrices M
and are N
quite large and this operation loops over a thousand times, so this inefficiency significantly affects the runtime.
source to share
It can be vectorized with bsxfun
twice. This does not mean that it is necessarily more efficient:
M = [1:10].'*[1:10]; %'// Large Matrix
indxs = [1 2;2 1;2 2];
r = size(M,1);
ind = bsxfun(@plus, (3:6).', ((3:6)-1)*r); %'// "3" and "6" as per your example
N = M(bsxfun(@minus, ind, reshape(indxs(:,1)+indxs(:,2)*r, 1,1,[])));
source to share