Hello, Is there a easy way how to produce following matrix:
a =
4 5 6 7
3 4 5 6
2 3 4 5
1 2 3 4
which is a projection of vector [1 2 3 4 5 6 7] along diagonal?
thanks
Hello, Is there a easy way how to produce following matrix:
a =
4 5 6 7
3 4 5 6
2 3 4 5
1 2 3 4
which is a projection of vector [1 2 3 4 5 6 7] along diagonal?
thanks
You can do this using the functions HANKEL and FLIPUD:
a = flipud(hankel(1:4,4:7));
Or using the functions TOEPLITZ and FLIPLR:
a = toeplitz(fliplr(1:4),4:7);
a = toeplitz(4:-1:1,4:7); %# Without fliplr
You could also generalize these solutions to an arbitrary vector where you have chosen the center point at which to break the vector. For example:
>> 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
The above example places the first three elements of the vector running up the first column and the last four elements of the vector running along the first row.
Consider this alternative solution:
a = bsxfun(@plus, (4:-1:1)', 0:3)
The corresponding general solution which accepts any vector and any column length:
x = randi(50, [1 10])
num = 5;
idx = bsxfun(@plus, (num:-1:1)', 0:(numel(x)-num));
a = x(idx)
with a sample output:
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