2016-06-14 83 views
1

假设我有以下的数组:高效的“窗口选择”数组块?

x = [a b 
    c d 
    e f 
    g h 
    i j]; 

欲沿阵列为“滑动的两排的窗口”(每次一行)逐步生成以下的数组:

y = [a b c d e f g h 
    c d e f g h i j]; 

什么是最有效的方法来做到这一点?我不想使用cellfunarrayfunfor循环。

回答

3

如果没有图像处理工具箱,你可以做到这一点使用简单的索引:

x = 
    1  2 
    3  4 
    5  6 
    7  8 
    9 10 

y = x.';      %% Transpose it, for simplicity 
z = [y(1:end-2); y(3:end)] %% Take elements 1:end-2 and 3:end and concatenate them 
z = 
    1  2  3  4  5  6  7  8 
    3  4  5  6  7  8  9 10 

你可以做变调,并在一个简单的步骤(见Suever的编辑)重塑,但上述可能更易于阅读,理解和调试初学者。

4

im2col如果你有图像处理工具箱,这里将是你最好的选择。

x = [1 2 
    3 4 
    5 6 
    7 8]; 

im2col(x.', [1 2]) 
% 1  2  3  4  5  6 
% 3  4  5  6  7  8 

如果您还没有图像处理工具箱,您也可以使用内置插件轻松做到这一点。

reshape(permute(cat(3, x(1:end-1,:), x(2:end,:)), [3 2 1]), 2, []) 
% 1  2  3  4  5  6 
% 3  4  5  6  7  8 

这将所有行与下一行组合在一起,将沿第三维的行移动版本连接起来。然后我们使用permute来移动尺寸,然后我们将其重新塑造成所需的尺寸。

+0

im2col是,如果你有工具箱要走的路=) +1 –

2

这里有一个方法来解决它为每个窗口选择L行的一般情况 -

[m,n] = size(x) % Store size 

% Extend rows by indexing into them with a progressive array of indices 
x_ext = x(bsxfun(@plus,(1:L)',0:m-L),:); 

% Split the first dim at L into two dims, out of which "push" back the 
% second dim thus created as the last dim. This would bring in the columns 
% as the second dimension. Then, using linear indexing reshape into the 
% desired shape of L rows for output. 
out = reshape(permute(reshape(x_ext,L,[],n),[1,3,2]),L,[]) 

采样运行 -

x =     % Input array 
    9  1 
    3  1 
    7  5 
    7  8 
    4  9 
    6  2 
L =     % Window length 
    3 
out = 
    9  1  3  1  7  5  7  8 
    3  1  7  5  7  8  4  9 
    7  5  7  8  4  9  6  2