Create matrix by repeatedly overlapping a vector

前端 未结 4 2071
再見小時候
再見小時候 2021-01-19 20:52

I\'m having great difficulty coding the following in MATLAB: Suppose you have the following vector:

a   
b
c
d
e
f
g
h
...

Specifying an (e

4条回答
  •  时光取名叫无心
    2021-01-19 21:32

    Short answer

    bsxfun is your friend in this case. The following one-liner (assuming you know L and v is your vector) does what you want

    v(bsxfun(@plus, [0:L-1]', 1:L/2:numel(v)-L))
    

    Explanation

    To try it out and understand it, lets have a further look. The idea is to first create a vector that determines, where the windows start in the v vector. Windows start every L/2 entries (L is even, so we can divide). But how many windows fit? We can rely on MATLAB to figure this out by saying:

    start_offset = 1:L/2:numel(v)-L;
    

    Here we just only need to specify that

    • first window is at at index 1
    • windows start every L/2 entries
    • the last window should start at least L entries before the end of the v vector. So that the last window fist in there.

    Now, the rest of the example:

    v = 'a':'z';
    L = 4;
    
    % indices in every output matrix column are contiguous
    % and the difference between first and last is `L-1`
    id1 = [0:L-1]';
    
    % start_offset determines where in the input vector v every window starts.
    % windows start every L/2 entries. The last entry that fits will start
    % at some index, from which we can still use L subsequent indices to access v
    start_offset = 1:L/2:numel(v)-L;
    
    % calculate how many entries were dropped from v
    % from number of elements in v subtract the largest index value used
    dropped = numel(v) - (start_offset+L-1);
    
    % window indices are created using bsxfun and singleton expansion.
    % Every window's indices are given by [0:L-1] + window start index
    idx = bsxfun(@plus, id1, start_offset);
    
    v(x)
    
    ans =
    
      acegikmoqsu
      bdfhjlnprtv
      cegikmoqsuw
      dfhjlnprtvx
    

提交回复
热议问题