Chap vector to matrix with special structure.

2 views (last 30 days)
I have a collumn vector consisting of n elemtents (size nx1):
P=[P1 ..... Pn]'
What I which to do, is transform this into a matrix with a certain number of rows. This is best explained by an example e.g. k=3 rows:
M=
P1 P2 ... Pn-2
P2 P3 ... Pn-1
P3 P4 ... Pn
Or k=4 rows
M=
P1 P2 ... Pn-3
P2 P3 ... Pn-2
P3 P4 ... Pn-1
P4 P5 ... Pn
In general
M=
P1 P2 ... Pn-k+1
P2 P3
. .
. .
Pk Pk+1 ... Pn
I hope my point is clear and you can help me. I'm performing this operation such that I can perform a multiplication more efficiently.
Thank you guys in advance!

Accepted Answer

Martijn
Martijn on 8 Mar 2012
My own answer:
dum=hankel(C)
M=dum(1:k,1:n-k+1)
  4 Comments
Martijn
Martijn on 9 Mar 2012
clear all; clc;
%test timing
P = [1 2 pi 5 exp(1)];
tic
k=3 %free choice variable
dum=hankel(P);
PP1 =dum(1:k,1:length(P)-k+1)
toc
tic
dum=hankel(P);
PP2 =dum(1:3,1:3)
toc
tic
idx = 1:ceil(numel(P)./2);
PP3 = P(bsxfun(@plus,idx',idx-1))
toc
PP1 =
1.0000 2.0000 3.1416
2.0000 3.1416 5.0000
3.1416 5.0000 2.7183
Elapsed time is 0.007529 seconds.
PP2 =
1.0000 2.0000 3.1416
2.0000 3.1416 5.0000
3.1416 5.0000 2.7183
Elapsed time is 0.000640 seconds.
PP3 =
1.0000 2.0000 3.1416
2.0000 3.1416 5.0000
3.1416 5.0000 2.7183
Elapsed time is 0.000752 seconds.
Martijn
Martijn on 9 Mar 2012
Strangely enough it looks like PP is calculated slower when using indices k and n to specify which part to 'select' from the hankel matrix.

Sign in to comment.

More Answers (1)

Sean de Wolski
Sean de Wolski on 8 Mar 2012
P = [1 2 pi 5 exp(1)];
idx = 1:ceil(numel(P)./2);
PP = P(bsxfun(@plus,idx',idx-1))
  3 Comments
Martijn
Martijn on 9 Mar 2012
How does your work for a vector P of length n and, number of row in PP of k? I'm looking for a generic solution.
Martijn
Martijn on 9 Mar 2012
Done it:
tic
idx = 1:k
idx2= 1:length(P)-k+1
PP3 = P(bsxfun(@plus,idx',idx2-1))
toc
Elapsed time is 0.001055 seconds.
While my generic method is : Elapsed time is 0.007312 seconds.

Sign in to comment.

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!