matlab: filling matrix diagonalwise [duplicate]

2019-03-04 09:26发布

问题:

This question already has an answer here:

  • adding values to diagonals of matrix using element-wise addition in matlab 3 answers

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).'));