matlab: filling matrix diagonalwise [duplicate]

夙愿已清 提交于 2019-12-20 06:21:14

问题


I have an (2n-1)-by-1 vector with certain values and I want to obtain an n-n matrix with the diagonals filled using the same value.

Eg. if I have

a = [1; 2; 3; 4; 5];

I want to obtain

A = [[3 4 5];[2 3 4];[1 2 3]]

  = 3     4     5
    2     3     4
    1     2     3

My matrix dimensions are a lot bigger so I'd want this as efficient as possible. I already found following solutions:

n = 3;
A = toeplitz(a);
A = A(1:n,end-n+1:end)

and

A = a(n)*eye(n);
for j=1:n-1
 A(1+j:n+1:end-j*n) = a(n-j);
 A(j*n+1:n+1:end) = a(n+j);
end

I wonder if there are more efficient ways to obtain this result, keeping in mind that I am working with huge matrices and really need the speed.


回答1:


 ix=bsxfun(@plus,[1:n],[n-1:-1:0]'); %generate indices
 A=a(ix);

or

 A=hankel(a) %might be faster than toeplitz because half the matrix is zero
 A(n:-1:1,1:n)

here is what hankel does internally (at least in ML R2013a), adapted to this problem:

c=[1:n];
r=[n-1:-1:0]';
idx=c(ones(n,1),:)+r(:,ones(n,1));
A=a(ix);

I guess the bsxfun solution and what thewaywewalk supposed is the fastest (it's basically the same)




回答2:


Go with:

n = (numel(a)+1)/2;
A = a(bsxfun(@minus, n+1:n+n, (1:n).'));


来源:https://stackoverflow.com/questions/29028566/matlab-filling-matrix-diagonalwise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!