简体   繁体   English

Octave function 获取矩阵中的连续列组

[英]Octave function to get groups of consecutive columns in matrix

I am trying to find an efficient way of extracting groups of n consecutive columns in a matrix.我试图找到一种有效的方法来提取矩阵中的n个连续列组。 Example:例子:

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

should produce an output similar to this:应该产生一个与此类似的 output:

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

I know this is possible using a for loop, such as the following code snippet:我知道这可以使用for循环来实现,例如以下代码片段:

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

However, I am trying to avoid using a for loop in this case - is there any possibility to vectorize this operation as well (using indexed expressions)?但是,我试图避免在这种情况下使用for循环 - 是否也有可能将此操作向量化(使用索引表达式)?

Using just indexing仅使用索引

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

The index ind is built using linear indexing and implicit expansion .索引ind是使用线性索引隐式扩展构建的。

Using the Image Package / Image Processing Toolbox使用图像 Package / 图像处理工具箱

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

Most of the work here is done by the im2col function with the 'sliding' option.这里的大部分工作是由带有'sliding'选项的im2col function 完成的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM