karl71
karl71

Reputation: 1092

Rearrange vector into matrix

In Matlab I have the following vector:

a = [ 1 2 3 4 5 6 ];

and I would like to build a matrix making a 1-element swift per row. The output matrix should look as this one:

A =

 1     2     3
 2     3     4
 3     4     5
 4     5     6 

Which is the fastest approach? Thak you in advance!

Upvotes: 1

Views: 254

Answers (4)

rayryeng
rayryeng

Reputation: 104503

Though this is a late answer, you can also cleverly do this with hankel:

A = [1 2 30 4 15 6];
A = hankel(A(1:4), A(4:6))

A =

     1     2    30
     2    30     4
    30     4    15
     4    15     6

Upvotes: 0

Dan
Dan

Reputation: 45752

A simple vectorized solution:

a = [ 1 2 30 4 15 6 ]
m = 4;
n = 3;  %// If you want the last element of a to be the bottom right 
        %// element of your output then n must equal numel(a)-(m-1)

[r,c] = ndgrid(0:(m-1), 1:n);
a(r+c)

ans =

    1    2   30
    2   30    4
   30    4   15
    4   15    6

Upvotes: 5

Nishant
Nishant

Reputation: 2619

a quick answer using arrayfun

A = cell2mat(arrayfun(@(i)(a(:,i:i+2))',1:4,'uni',0))';

More generally if you want first k elements of a in A then use: (in above code k = 3)

A = cell2mat(arrayfun(@(i)(a(:,i:i+k-1))',1:numel(a)-k+1,'uni',0))';

As Dan pointed out, this method is good as a one-liner but isn't fast for large matrices

Upvotes: 2

lakshmen
lakshmen

Reputation: 29064

Using a simple for loop and circshift

A = zeros(4,3);
for i= 0:3
    answer = circshift(a,[0 -i]);
    A(i+1,:) = answer(1:3);
end

Upvotes: 1

Related Questions