5

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?

gnovice
  • 125,304
  • 15
  • 256
  • 359
Lazer
  • 90,700
  • 113
  • 281
  • 364

1 Answers1

10

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
gnovice
  • 125,304
  • 15
  • 256
  • 359
  • @Jacob: It's funny, I learned about matrix-building functions like this relatively recently (actually, from an answer here on SO: http://stackoverflow.com/questions/1000535/how-can-i-create-a-triangular-matrix-based-on-a-vector-in-matlab/1000889#1000889), and now that I know them I keep finding *sooo* many places to use them. ;) – gnovice Nov 04 '09 at 19:06
  • Nice. I would have used something based on circshift, but this is much more elegant – Kena Nov 04 '09 at 19:32
  • 2
    just that my data won't be always `1:10`, so I have used `o = data(:,(num+1:end));`. I was thinking of using multiple for loops to achieve the same. `hankel` is just so much more elegant. – Lazer Nov 05 '09 at 04:36
  • @gnovice first I tried your original answer: `i = hankel(data); o = i(num+1,1:(end-num)); i = (1:num,1:(end-num));` but I was getting Out of memory error [my data is actually ~8000 points]. Using `hankel` this way is so much less computation intensive. – Lazer Nov 05 '09 at 04:40
  • @eSKay: Yeah, I noticed that my first solution was doing some extra work, generating a larger matrix and then selecting part of it. That probably caused your out-of-memory error, since it would have been creating a roughly 8000-by-8000 matrix. Luckily, I remembered that you can call `hankel` with 2 inputs to generate the matrix you want directly. – gnovice Nov 05 '09 at 04:49