3

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.

Santhan Salai
  • 3,888
  • 19
  • 29
Trock
  • 308
  • 2
  • 6
  • you can use parfor (which runs parallel on gpu) to maximize speed but i think there is no way to not using for loop. – Hadi Jun 04 '15 at 00:37

1 Answers1

1

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,[])));
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • 1
    Had the same thing done at my end, but with two `bsxfun(@plus..)` instead for almost the same performance. – Divakar Jun 04 '15 at 04:29