Trouble with spdiags and how it produces Tridiagonal matrix?
55 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Matt J
on 25 Feb 2020
Edited: Matt J
on 25 Feb 2020
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 Comments
Matt J
on 25 Feb 2020
You are welcome but please Accept-click the answer to indicate that it solves the problem.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!