Trouble with spdiags and how it produces Tridiagonal matrix?

55 views (last 30 days)
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

Accepted Answer

Matt J
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
arthurk
arthurk on 25 Feb 2020
Yeah, I guess if you can't get around it this is the best way. thanks
Matt J
Matt J on 25 Feb 2020
You are welcome but please Accept-click the answer to indicate that it solves the problem.

Sign in to comment.

More Answers (1)

Matt J
Matt J on 25 Feb 2020
Edited: Matt J on 25 Feb 2020
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 Comments
arthurk
arthurk on 25 Feb 2020
Edited: arthurk on 25 Feb 2020
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 on 25 Feb 2020
Your repelem's should be applied to column vectors, not row vectors.

Sign in to comment.

Categories

Find more on Programming in Help Center and File Exchange

Tags

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!