Create matrix by repeatedly overlapping a vector

前端 未结 4 2046
再見小時候
再見小時候 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:13

    There are many ways to do this in MATLAB by manipulating indices, procedural approaches, vectorized solutions, etc. Yet, I can't help but think of how simple some tasks might be, if MATLAB had a wee bit of support for functional style of programming. In that spirit, I present the following solution. Ensure that you don't already have any values in those variables at definition time.

    take=@(mat,n)mat(1:n)
    partition=@(mat,L)cell2mat(arrayfun(@(x)take(circshift(mat(:),-x*L/2),L),...
            0:fix((length(mat)-L)/2+1)-1,'UniformOutput',0))
    

    Now try it with a test vector:

    partition(1:10,4)
    
     %ans = 
     %    1     3     5     7
     %    2     4     6     8
     %    3     5     7     9
     %    4     6     8    10
    

    The above solution discards the final values at the end of the vector that don't fit a length L after partition. You can now build up on this to handle other arrangements and figure out optimal window lengths for minimal end wastage, etc.

提交回复
热议问题