How do I generate the following matrix and vector

2019-01-26 14:36发布

问题:

Suppose I have the inputs data = [1 2 3 4 5 6 7 8 9 10] and num = 4. I want to use these to generate the following:

i = [1 2 3 4 5 6; 2 3 4 5 6 7; 3 4 5 6 7 8; 4 5 6 7 8 9]
o = [5 6 7 8 9 10]

which is based on the following logic:

length of data = 10
num = 4
10 - 4 = 6
i = [first 6; second 6;... num times]
o = [last 6]

What is the best way to automate this in MATLAB?

回答1:

Here's one option using the function HANKEL:

>> data = 1:10;
>> num = 4;
>> i = hankel(data(1:num),data(num:end-1))

i =

     1     2     3     4     5     6
     2     3     4     5     6     7
     3     4     5     6     7     8
     4     5     6     7     8     9

>> o = i(end,:)+1

o =

     5     6     7     8     9    10