开发者

Reconstruct matrix from diagonals in matlab

开发者 https://www.devze.com 2023-01-28 10:21 出处:网络
Given a vector of the counter-diagonals of a matrix in matlab, is there an easy way to开发者_运维知识库 reconstruct the matrix?

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!


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
0

精彩评论

暂无评论...
验证码 换一张
取 消