Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab vector to matrix conversion

I want to convert the following vector A into matrix B, best demonstrated by this example:

n = 4;

A = [1 2 3 4 5 6];

B = [ 1 2 3 4;
      2 3 4 5;
      3 4 5 6; ]

I am currently using a loop to achieve this and wondered if it was possible to vectorize it?

Thanks L.

like image 470
ladidalimey Avatar asked Feb 22 '26 09:02

ladidalimey


2 Answers

You can use bsxfun -

A(bsxfun(@plus,[0:numel(A)-n]',1:n))

You can also use hankel -

hankel(A(1:n),A(n:end)).'

Sample run -

>> A = [3,4,6,0,1,2]
A =
     3     4     6     0     1     2
>> n
n =
     4
>> A(bsxfun(@plus,[0:numel(A)-n]',1:n))
ans =
     3     4     6     0
     4     6     0     1
     6     0     1     2
>> hankel(A(1:n),A(n:end)).'
ans =
     3     4     6     0
     4     6     0     1
     6     0     1     2
like image 55
Divakar Avatar answered Feb 24 '26 08:02

Divakar


If you have the Signal Processing Toolbox you can also use convmtx:

n = 4;
A = [1 2 3 4 5 6];

m = numel(A)-n;
B = flipud(convmtx(A,m+1));
B = B(:,m+1:end-m);
like image 33
Luis Mendo Avatar answered Feb 24 '26 09:02

Luis Mendo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!