Create a matrix by sliding down a given vector by one step for every column

matlab, matrix, vectorization

Solution

One way to do it:

a = [1 2 3 4]
n = numel(a);

%// create circulant matrix from input vector
b = gallery('circul',[a zeros(1,n-1)]).' %'

%// crop the result
c = b(:,1:n)

Another way:

b = union( tril(toeplitz(a)), triu(toeplitz(fliplr(a))),'rows','stable')

or its slightly variation

b = union( toeplitz(a,a.*0),toeplitz(fliplr(a),a.*0).','rows','stable')

and probably even faster:

b = [ toeplitz(a,a.*0) ; toeplitz(fliplr(a),a.*0).' ]
b(numel(a),:) = []

Problem

Given this vector ``` a = [1 2 3 4] ``` I want to create a matrix like this ``` b = [1 0 0 0; 2 1 0 0; 3 2 1 0; 4 3 2 1; 0 4 3 2; 0 0 4 3; 0 0 0 4] ``` in a vectorized way not using loops.

Original source