Chap vector to matrix with special structure.

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!

 采纳的回答

My own answer:
dum=hankel(C)
M=dum(1:k,1:n-k+1)

4 个评论

Elapsed time is 0.000184 seconds.
What is the complete code for yours? i.e. n,k
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.
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 个)

P = [1 2 pi 5 exp(1)];
idx = 1:ceil(numel(P)./2);
PP = P(bsxfun(@plus,idx',idx-1))

3 个评论

Elapsed time is 0.004266 seconds.
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.
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.

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by