在MATLAB中考虑连续矩阵块的最大值

Nic*_*ing 5 matlab matrix vectorization

鉴于矩阵:

a =
   1   1   2   2
   1   1   2   2
   3   3   4   4
   3   3   4   4
Run Code Online (Sandbox Code Playgroud)

我想得到以下四个2x2矩阵:

a1 =
   1   1
   1   1

a2 =
   2   2
   2   2

a3 =
   3   3
   3   3

a4 =
   4   4
   4   4
Run Code Online (Sandbox Code Playgroud)

从那里,我想取每个矩阵的最大值,然后将结果重新整形为2x2结果矩阵,如下所示:

r =
   1   2
   3   4
Run Code Online (Sandbox Code Playgroud)

结果最大值相对于其在初始矩阵中的原始位置的位置是重要的.

目前,我正在使用以下代码来完成此任务:

w = 2
S = zeros(size(A, 1)/w);
for i = 1:size(S)
  for j = 1:size(S)
    Window = A(i*w-1:i*w, j*w-1:j*w);
    S(i, j) = max(max(Window));
  end
end
Run Code Online (Sandbox Code Playgroud)

这有效,但似乎必须有一种不涉及迭代(矢量化)的方法.

我尝试使用reshape像这样: reshape(max(max(reshape(A, w, w, []))), w, w, []) 但是它需要最大的错误值并返回:

ans =
   3   4
   3   4
Run Code Online (Sandbox Code Playgroud)

有没有办法在没有迭代的情况下完成此任务或以其他方式改进我的迭代方法?

Rod*_*uis 2

Not very general, but it works for a:

b = [a(1:2,:) a(3:4,:)];
reshape(max(reshape(b, 4,[])), 2,2).'
Run Code Online (Sandbox Code Playgroud)

The general version of this is a bit *ahum* fuglier:

% window size
W = [2 2];

% number of blocks (rows, cols)
nW = size(a)./W;


% indices to first block
ids = bsxfun(@plus, (1:W(1)).', (0:W(2)-1)*size(a,1));

% indices to all blocks in first block-column
ids = bsxfun(@plus, ids(:), (0:nW(1)-1)*W(1));

% indices to all blocks
ids = reshape(bsxfun(@plus, ids(:), 0:nW(1)*prod(W):numel(a)-1), size(ids,1),[]);

% maxima
M = reshape(max(a(ids)), nW)
Run Code Online (Sandbox Code Playgroud)

It can be done a bit more elegantly:

b = kron(reshape(1:prod(nW), nW), ones(W));    
C = arrayfun(@(x) find(b==x), 1:prod(nW), 'uni', false);    
M = reshape(max(a([C{:}])), nW)
Run Code Online (Sandbox Code Playgroud)

but I doubt that's gonna be faster...