本文介绍了在Matlab中向量化数组索引/子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个长数据向量y,外加一些索引.我想在每个索引周围提取一个简短的代码段或窗口.

Suppose I have a long data vector y, plus some indices into it. I want to extract a short snippet or window around every index.

例如,假设我要构造一个矩阵,该矩阵包含每个值小于3的之前的64个样本和之后的64个样本.在for循环中这样做很简单:

For example, suppose I want to construct a matrix containing 64 samples before and 64 samples after every value that is below three. This is trivial to do in a for-loop:

WIN_SIZE = 64;

% Sample data with padding
data = [nan(WIN_SIZE,1); randn(1e6,1); nan(WIN_SIZE,1)];

% Sample events, could be anything
index = find(data < 3);

snippets = nan(length(index), 2*WIN_SIZE + 1);
for ii=1:length(index)
   snippets(ii,:) = data((index(ii)-WIN_SIZE):(index(ii)+WIN_SIZE));
end

但是,这并没有很快.是否有任何方法可以矢量化(或加快)此操作?

However,this is not blazingly fast. Is there any way to vectorize (or otherwise speed up) this operation?

(如果不清楚,索引可以是任何东西,也不一定是数据的属性;我只想简单地说明一下这个想法.)

(In case this is unclear, the index could be anything and may not necessarily be a property of the data; I just wanted something simple to illustrate the idea.)

推荐答案

使用 bsxfun -

snippets = data(bsxfun(@plus,index(:),[-WIN_SIZE:WIN_SIZE]))

这篇关于在Matlab中向量化数组索引/子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 22:30