我有一个(2n-1)-by-1向量,具有一定的值,我想获得一个n-n矩阵,对角线用相同的值填充。
EG。如果我有
a = [1; 2; 3; 4; 5];
我想获得
A = [[3 4 5];[2 3 4];[1 2 3]]
= 3 4 5
2 3 4
1 2 3
我的矩阵尺寸要大得多,所以我希望尽可能高效。我已经找到了以下解决方案:
n = 3;
A = toeplitz(a);
A = A(1:n,end-n+1:end)
和
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
我想知道是否有更有效的方法来获得这个结果,请记住我正在使用巨大的矩阵并且确实需要速度。
答案 0 :(得分:4)
ix=bsxfun(@plus,[1:n],[n-1:-1:0]'); %generate indices
A=a(ix);
或
A=hankel(a) %might be faster than toeplitz because half the matrix is zero
A(n:-1:1,1:n)
这里是hankel
内部(至少在ML R2013a中)做的,适应了这个问题:
c=[1:n];
r=[n-1:-1:0]';
idx=c(ones(n,1),:)+r(:,ones(n,1));
A=a(ix);
我猜bsxfun解决方案和thewaywewalk
假设的最快(它基本相同)
答案 1 :(得分:1)
一起去:
n = (numel(a)+1)/2;
A = a(bsxfun(@minus, n+1:n+n, (1:n).'));