简体   繁体   English

创建带状对角矩阵时,spdiags出现“索引超出矩阵尺寸”错误?

[英]“Index exceeds matrix dimensions” error with spdiags when creating band diagonal matrix?

I have this sample code that creates a band diagonal matrix 我有此示例代码创建带对角矩阵

T = 6;
d1 = ones(T-2, 1);
d2 = 2*ones(T-1, 1);
d3 = 3*ones(T, 1);

f = sparse(diag(d1, -2) + diag(d2, -1) + diag(d3) + diag(d2, 1) + diag(d1, 2));

but I want to avoid creating the full TxT matrix, so I want to use spdiags, like this: 但我想避免创建完整的TxT矩阵,因此我想使用spdiags,如下所示:

f2 = spdiags(d1, -2, T, T) + spdiags(d2, -1, T, T) + spdiags(d3, 0, T, T) + ...
    spdiags(d2, 1, T, T) + spdiags(d1, 2, T, T);

matlab tells me that "index exceeds matrix dimensions" and the problem comes from these commands matlab告诉我“索引超出矩阵尺寸”,问题出在这些命令上

spdiags(d2, 1, T, T)
spdiags(d3, 2, T, T)

but these commands work normally: 但是这些命令可以正常工作:

spdiags(d1, -2, T, T)
spdiags(d2, -1, T, T)

What's going on here? 这里发生了什么? The final matrix should look like the sparse form of this: 最终的矩阵看起来应该像这样的稀疏形式:

f =
     3     2     1     0     0     0
     2     3     2     1     0     0
     1     2     3     2     1     0
     0     1     2     3     2     1
     0     0     1     2     3     2
     0     0     0     1     2     3

Also these are sample matrices that Im using as examples only. 这些也是Im仅用作示例的示例矩阵。

This code works too: 此代码也适用:

T = 6;
d1 = ones(T-2, 1);
d2 = 2*ones(T-1, 1);
d3 = 3*ones(T, 1);

f = sparse(diag(d1, -2) + diag(d2, -1) + diag(d3) + diag(d2, 1) + diag(d1, 2));

B = [[d1;0;0], [d2;0], d3, [0;d2], [0;0;d1]];
f2 = spdiags(B, -2:2, T, T);

The documentation is not very clear. 文档不是很清楚。 It looks like you need your d vector to be of length T , even if some values will be ignored (namely, the first values are ignored for positive diagonals, and the last are ignored for negative diagonals). 看起来您的d向量长度必须为T ,即使某些值将被忽略(即对于正对角线,第一个值将被忽略,对于负对角线,最后一个值将被忽略)。 But somehow Matlab only actually complains for positive diagonals; 但是不知何故,Matlab实际上只是抱怨正对角线。 for negative diagonals it does accept shorter vectors. 对于负对角线,它确实接受较短的向量。

So: use all d vectors of length T : 因此:使用所有d个长度为T向量:

T = 6;
d1 = ones(T, 1);
d2 = 2*ones(T, 1);
d3 = 3*ones(T, 1);
f2 = spdiags(d1, -2, T, T) + spdiags(d2, -1, T, T) + spdiags(d3, 0, T, T) + ...
    spdiags(d2, 1, T, T) + spdiags(d1, 2, T, T);

By the way, you can build a matrix containing all d vectors as columns (now that they all have the same length) and call spdiags just once: 顺便说一句,您可以构建一个包含所有d向量作为列的矩阵(现在它们都具有相同的长度), spdiags只需调用一次spdiags

f2 = spdiags([d1 d2 d3 d2 d1], -2:2, T, T);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM