Chap vector to matrix with special structure.

2 次查看(过去 30 天)
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!

采纳的回答

Martijn
Martijn 2012-3-8
My own answer:
dum=hankel(C)
M=dum(1:k,1:n-k+1)
  4 个评论
Martijn
Martijn 2012-3-9
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 2012-3-9
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.

请先登录,再进行评论。

更多回答(1 个)

Sean de Wolski
Sean de Wolski 2012-3-8
P = [1 2 pi 5 exp(1)];
idx = 1:ceil(numel(P)./2);
PP = P(bsxfun(@plus,idx',idx-1))
  3 个评论
Martijn
Martijn 2012-3-9
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 2012-3-9
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.

请先登录,再进行评论。

产品

Community Treasure Hunt

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

Start Hunting!

Translated by