Trock
Trock

Reputation: 318

Matlab: Efficiently Generating Subarrays from an array

I have an m x m matrix M that I am sampling different parts of to generate k sub-arrays into an n x n x k matrix N. What I am wondering is: can this be done efficiently without a for loop?

Here is 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, matrices M and N are fairly large and this operation is looped over thousands of times, so this inefficiency is taking a significant toll on the run-time.

Upvotes: 3

Views: 118

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112689

It can be vectorized using bsxfun twice. That doesn't mean it's necessarily more efficient, though:

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,[])));

Upvotes: 1

Related Questions