matlab:将向量划分为固定大小的重叠块 [英] matlab: dividing vector into overlapping chunks of fixed size
问题描述
我有一个向量,我想在 sh
的变换中拆分成大小为 cs
的重叠子向量.想象一下输入向量是:
I've a vector that I would like to split into overlapping subvectors of size cs
in shifts of sh
. Imagine the input vector is:
v=[1 2 3 4 5 6 7 8 9 10 11 12 13]; % A=[1:13]
假设 chunksize
为 4 (cs=4
) 和 shift 为 2 (sh=2
),结果应如下所示:
given a chunksize
of 4 (cs=4
) and shift of 2 (sh=2
), the result should look like:
[1 2 3 4]
[3 4 5 6]
[5 6 7 8]
[7 8 9 10]
[9 10 11 12]
请注意,输入向量不一定能被 chunksize
整除,因此会丢弃一些子向量.有没有什么快速的方法来计算它,而不需要使用例如for
循环?在相关的 帖子中,我找到了如何这样做,但在考虑非重叠子向量时.
note that the input vector is not necessarily divisible by the chunksize
and therefore some subvectors are discarded. Is there any fast way to compute that, without the need of using e.g. a for
loop?
In a related post I found how to do that but when considering non-overlapping subvectors.
推荐答案
你可以使用函数bsxfun
方式如下:
You can use the function bsxfun
in the following manner:
v=[1 2 3 4 5 6 7 8 9 10 11 12 13]; % A=[1:13]
cs=4;
sh=2;
A = v(bsxfun(@plus,(1:cs),(0:sh:length(v)-cs)'));
这是它的工作原理.bsxfun
在 2 个数组上应用一些基本函数,并在输入的大小不合适时执行一些类似 repmat
的操作.在这种情况下,我生成第一个块的索引,并添加每个块的偏移量.由于一个输入是行向量,另一个是列向量,因此结果是一个矩阵.最后,当使用矩阵索引向量时,结果是一个矩阵,这正是您所期望的.
Here is how it works. bsxfun
applies some basic functions on 2 arrays and performs some repmat
-like if the sizes of inputs do not fit. In this case, I generate the indexes of the first chunk, and add the offset of each chunck. As one input is a row-vector and the other is a column-vector, the result is a matrix. Finally, when indexing a vector with a matrix, the result is a matrix, that is precisely what you expect.
而且它是单行的,(几乎)总是很有趣:).
And it is a one-liner, (almost) always fun :).
这篇关于matlab:将向量划分为固定大小的重叠块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!