Chap vector to matrix with special structure.

조회 수: 2 (최근 30일)
Martijn
Martijn 2012년 3월 8일
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