4
votes

Given a vector of the counter-diagonals of a matrix in matlab, is there an easy way to reconstruct the matrix?

For example, given

x = [1 2 3 4 5 6 7 8 9]

is there any easy way to reconstruct it to the following?

1 2 4
3 5 7
6 8 9

This is made slightly easier by the fact that the dimensions of the original block are known. Reconstructing a rotation or transposition of the original matrix is fine, since rotating and transposing are easy to undo. Faster is better, this calculation has to be done on many xs.

Thanks!

1
x is missing a 9. which makes the question weird. - carlosdc

1 Answers

4
votes

You can create the corresponding Hankel matrix and use it for sorting (works only if the output is a square matrix!):

x = [1 2 3 4 5 6 7 8 9];

%# find size of output (works only with square arrays)
n=sqrt(length(x));

%# create Hankel matrix
hh = hankel(1:n,n:(2*n-1));

%# sort to get order of elements (conveniently, sort doesn't disturb ties)
[~,sortIdx]=sort(hh(:));

%# reshape and transpose
out = reshape(x(sortIdx),n,n)'; %'# SO formatting

out =
     1     2     4
     3     5     7
     6     8     9