MATLAB function to process vector with sliding win

2019-07-21 16:05发布

Assuming vector v of size 1 x n and function fun that takes in a vector of length L and returns a vector of size p x 1.

Is there a MATLAB function that would take in vector v, process each sliding window of length L with function fun, and return a matrix of size p x n (or p x (n-L)).

I am aware this could be achieved with creating a matrix of windowed vectors with im2col and processing each of those, but this takes too much memory for a long vector v.

2条回答
叛逆
2楼-- · 2019-07-21 16:53
funsl=@(is) fun(v(is:is+l-1));
cell2mat(arrayfun(funsl,1:length(v)-l+1,'UniformOutput',false))

What I did here is define an anonymous function that, for a fixed v and l and a starting index parameter (is), gets the respective slice of v and applies fun to it.

Then this function is applied, via arrayfun, to all useful values for this starting index. For reasons I myself cannot quite name at the moment, each application returns a p x 1 vector, but arrayfun cannot arrange it into a proper matrix, thus the UniformOutput=false setting and the cell2mat call around it.

Edit: To test this with a function that turns 1-by-5 vectors into 4-by-1 vectors I used

l=5;v=1:12; fun=@(x) cumsum(x(2:end))';

and got this result:

ans =

 2     3     4     5     6     7     8     9
 5     7     9    11    13    15    17    19
 9    12    15    18    21    24    27    30
14    18    22    26    30    34    38    42

Note again that in the definition of funsl v is fixed, To apply this approach to different v you could make another function that takes v (and l, if you do not want to fix this) as parameter(s), contains the two lines above and returns the result of the second one.

查看更多
来,给爷笑一个
3楼-- · 2019-07-21 16:57

The same solution from this other post could apply (with some modifications):

n = 7; L = 3;
v = rand(1,n);                        %# 1-by-n vector
M = num2cell(v(hankel(1:L,L:n)),1);   %# sliding windows of length L
fcn = @(x)[min(x);max(x);sum(x)];     %# function that takes a vector of length L
                                      %# and returns a p-by-1 vector (p=3)
%# apply function to sliding windows, result is a p-by-(n-L+1) matrix
M = cell2mat(cellfun(fcn, M, 'UniformOutput',false));
查看更多
登录 后发表回答