views:

102

answers:

1

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?

+10  A: 

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
+1 - You learn something new (`hankel`) everyday .. on SO!
Jacob
@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
Nice. I would have used something based on circshift, but this is much more elegant
Kena
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
@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
@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

related questions