Matlab:有效地从数组生成子数组



我有一个m x m矩阵M,我正在对其不同部分进行采样,以将k子数组生成n x n x k矩阵N。我想知道的是:这可以有效地完成没有for循环?

这里有一个简单的例子:

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

在我的实际代码中,矩阵MN相当大,并且该操作循环了数千次,因此这种低效率对运行时造成了很大的影响。

可以使用bsxfun进行两次矢量化。但这并不意味着它一定更有效率:

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

最新更新