Ell
Ell

Reputation: 101

Make matrix from shifted vector matlab vectorization

Geetings, here's the little problem.

I have a vector v (size(v) = T), a positive number P, P < T nad positive number N, N < T. And want to make matrix M with size PxN, so that:

M = [v(T),     v(T-1), ....., v(T-N+2),   v(T-N+1);
     v(T-1),   v(T-2), ....., v(T-N+1),   v(T-N)  ;
     v(T-2),   v(T-3), ....., v(T-N),     v(T-N-1);
        .        .       .       .           .    ;
        .        .       .       .           .    ;
     v(T-P+1), v(T-P), ....., v(T-P-N+3), v(T-P-N+2)]

It holds that T > P + N.

Let given an example.

v = [1, 2, 3, 4, 5]';
P = 3;
N = 3;
M = [5, 4, 3;
     4, 3, 2;
     3, 2, 1]

I know how to do this using for loop, but I also think that it is possible do by vectorizations - here the problem is - I am not so skilled in vectorizations.

Thx for hints and so on :))

Upvotes: 2

Views: 244

Answers (2)

Jonas
Jonas

Reputation: 74940

Use the Hankel matrix:

v = [1 2 3 4 5];
T = length(v);
P = 3;
N = 3;
out = hankel(v(T:-1:T-P+1),v(T-P+1:-1:T-P-N+2));

Upvotes: 7

H.Muster
H.Muster

Reputation: 9317

You can make use of bsxfun

v = [1, 2, 3, 4, 5]';
P = 3;
N = 3;
idx = bsxfun(@minus, length(v):-1:length(v)-N+1, (0:P-1)');

result  = v(idx);

this will result in

result =

     5     4     3
     4     3     2
     3     2     1

Upvotes: 3

Related Questions