matlab:沿对角线填充矩阵 [英] matlab: filling matrix diagonalwise

查看:371
本文介绍了matlab:沿对角线填充矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有特定值的(2n-1)×1向量,我想获得一个n-n矩阵,对角线使用相同的值填充.

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.

例如.如果我有

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

我的矩阵尺寸要大得多,所以我希望这样做尽可能高效.我已经找到以下解决方案:

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)

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.

推荐答案

 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中)所做的事情,以适应此问题:

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

我猜想bsxfun解决方案和thewaywewalk假定是最快的(基本上是相同的)

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

这篇关于matlab:沿对角线填充矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆