Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 204
Trock Avatar asked Sep 15 '26 18:09

Trock


1 Answers

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,[])));
like image 80
Luis Mendo Avatar answered Sep 17 '26 14:09

Luis Mendo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!