Diagonal vector projection onto a matrix

Is there an easy way to create the following matrix:

a = 
  4 5 6 7
  3 4 5 6
  2 3 4 5
  1 2 3 4

which is the projection of the vector [1 2 3 4 5 6 7] along the diagonal?

thank

+5
source share
2 answers

You can do this using the HANKEL and FLIPUD functions :

a = flipud(hankel(1:4,4:7));

Or using the TOEPLITZ and FLIPLR functions :

a = toeplitz(fliplr(1:4),4:7);
a = toeplitz(4:-1:1,4:7);       %# Without fliplr

You can also generalize these solutions to an arbitrary vector at which you have chosen the center point at which the vector can be divided. For instance:

>> vec = [6 3 45 1 1 2];  %# A sample vector
>> centerIndex = 3;
>> a = flipud(hankel(vec(1:centerIndex),vec(centerIndex:end)))

a =

    45     1     1     2
     3    45     1     1
     6     3    45     1

In the above example, the first three elements of the vector that starts the first column and the last four elements of the vector along the first row are placed.

+5

:

a = bsxfun(@plus, (4:-1:1)', 0:3)

, :

x = randi(50, [1 10])
num = 5;
idx = bsxfun(@plus, (num:-1:1)', 0:(numel(x)-num));
a = x(idx)

:

x =
    41    46     7    46    32     5    14    28    48    49

a =
    32     5    14    28    48    49
    46    32     5    14    28    48
     7    46    32     5    14    28
    46     7    46    32     5    14
    41    46     7    46    32     5
+2

All Articles