Octave函数获取矩阵中连续列的组

Octave function to get groups of consecutive columns in matrix

我正在尝试找到一种有效的方法来提取矩阵中的 n 连续列组。示例:

A = [0, 1, 2, 3, 4; 0, 1, 2, 3, 4; 0, 1, 2, 3, 4]; 
n = 3;

应该产生类似这样的输出:

answer = cat(3, ...
                [0, 1, 2; 0, 1, 2; 0, 1, 2], ...
                [1, 2, 3; 1, 2, 3; 1, 2, 3], ...
                [2, 3, 4; 2, 3, 4; 2, 3, 4]);

我知道这可以使用 for 循环实现,例如以下代码片段:

answer = zeros([3, 3, 3]);
for i=1:3
  answer(:, :, i) = A(:, i:i+2);
endfor

但是,我试图避免在这种情况下使用 for 循环 - 是否有可能对这个操作进行向量化(使用索引表达式)?

仅使用索引

ind = reshape(1:size(A,1)*n, [], n) + reshape((0:size(A,2)-n)*size(A,1), 1, 1, []); 
result = A(ind);

索引 ind 是使用 linear indexing and implicit expansion 构建的。

使用图像包/图像处理工具箱

result = reshape(im2col(A, [size(A,1) n], 'sliding'), size(A,1), n, []);

这里的大部分工作都是由带有 'sliding' 选项的 im2col 函数完成的。