Trouble with spdiags and how it produces Tridiagonal matrix?

38 次查看(过去 30 天)
matrix = repelem([1 2 3]',[4 , 1 ,5])
matrix2 = repelem([0.5 1.5]',[5,5] )
TridiagonalMatrix = spdiags([matrix matrix2 matrix], -1:1, 10, 10)
full(TridiagonalMatrix)
Output:
matrix matrix2
1 0.5
1 0.5
1 0.5
1 0.5
2 0.5
3 1.5
3 1.5
3 1.5
3 1.5
3 1.5
As you can see although there are 4 1s in the matrix named matrix, however, on the 1st diagonal there are only 3 1s listed.
Why is this the case and how can I fix it so that it has 4 1s, whilst still having 4 1s in the -1st diagonal aswell

采纳的回答

Matt J
Matt J 2020-2-25
编辑:Matt J 2020-2-25
Why is this the case and how can I fix it so that it has 4 1s, whilst still having 4 1s in the -1st diagonal as well
From the documentation:
With the syntax S = spdiags(Bin,d,m,n), if a column of Bin has more elements than the diagonal it is replacing, and m >= n, then spdiags takes elements of super-diagonals from the lower part of the column of Bin.
Solution:
matrix = repelem([1 2 3]',[4 , 1 ,5]);
matrix2 = repelem([0.5 1.5]',[5,5] );
matrix3=repelem([1 2 3].', [5,1,4]);
TridiagonalMatrix = spdiags([matrix matrix2 matrix3], -1:1, 10, 10);
>> full(TridiagonalMatrix)
ans =
0.5000 1.0000 0 0 0 0 0 0 0 0
1.0000 0.5000 1.0000 0 0 0 0 0 0 0
0 1.0000 0.5000 1.0000 0 0 0 0 0 0
0 0 1.0000 0.5000 1.0000 0 0 0 0 0
0 0 0 1.0000 0.5000 2.0000 0 0 0 0
0 0 0 0 2.0000 1.5000 3.0000 0 0 0
0 0 0 0 0 3.0000 1.5000 3.0000 0 0
0 0 0 0 0 0 3.0000 1.5000 3.0000 0
0 0 0 0 0 0 0 3.0000 1.5000 3.0000
0 0 0 0 0 0 0 0 3.0000 1.5000
  2 个评论
arthurk
arthurk 2020-2-25
Yeah, I guess if you can't get around it this is the best way. thanks
Matt J
Matt J 2020-2-25
You are welcome but please Accept-click the answer to indicate that it solves the problem.

请先登录,再进行评论。

更多回答(1 个)

Matt J
Matt J 2020-2-25
编辑:Matt J 2020-2-25
matrix = repelem([1 2 3]',[4 , 1 ,5]);
matrix2 = repelem([0.5 1.5]',[5,5] );
T=spdiags([matrix matrix2/2], -1:0, 10, 10);
TridiagonalMatrix = T+T.';
  2 个评论
arthurk
arthurk 2020-2-25
编辑:arthurk 2020-2-25
Code:
matrix = repelem([1 2 3], [4, 1, 5])
matrix2 = repelem([0.5 1.5], [5, 5])
T=spdiags([matrix matrix2/2], -1:0, 10, 10);
TridiagonalMatrix = T+T.';
Receiving the error:
Error using spdiags (line 95)
For the syntax spdiags(B,d,m,n), the size of B must be min(m,n)-by-length(d).
Error in test (line 4)
T=spdiags([matrix matrix2/2], -1:0, 10, 10);
Matt J
Matt J 2020-2-25
Your repelem's should be applied to column vectors, not row vectors.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

标签

产品


版本

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by