Banded matrices¶
Here is a matrix with both lower and upper bandwidth equal to one. Such a matrix is called tridiagonal.
using FundamentalsNumericalComputation
A = [ 2 -1 0 0 0 0
4 2 -1 0 0 0
0 3 0 -1 0 0
0 0 2 2 -1 0
0 0 0 1 1 -1
0 0 0 0 0 2 ]
6×6 Array{Int64,2}:
2 -1 0 0 0 0
4 2 -1 0 0 0
0 3 0 -1 0 0
0 0 2 2 -1 0
0 0 0 1 1 -1
0 0 0 0 0 2
We can extract the elements on any diagonal using the diag
command. The “main” or central diagonal is numbered zero, above and to the right of that is positive, and below and to the left is negative.
@show diag_main = diag(A,0);
diag_main = diag(A, 0) = [2, 2, 0, 2, 1, 2]
@show diag_plusone = diag(A,1);
diag_plusone = diag(A, 1) = [-1, -1, -1, -1, -1]
@show diag_minusone = diag(A,-1);
diag_minusone = diag(A, -1) = [4, 3, 2, 1, 0]
We can also put whatever numbers we like onto any diagonal with the diagm
function.
A = A + diagm(2=>[pi,8,6,7])
6×6 Array{Float64,2}:
2.0 -1.0 3.14159 0.0 0.0 0.0
4.0 2.0 -1.0 8.0 0.0 0.0
0.0 3.0 0.0 -1.0 6.0 0.0
0.0 0.0 2.0 2.0 -1.0 7.0
0.0 0.0 0.0 1.0 1.0 -1.0
0.0 0.0 0.0 0.0 0.0 2.0
L,U = FNC.lufact(A)
L
6×6 Array{Float64,2}:
1.0 0.0 0.0 0.0 0.0 0.0
2.0 1.0 0.0 0.0 0.0 0.0
0.0 0.75 1.0 0.0 0.0 0.0
0.0 0.0 0.36614 1.0 0.0 0.0
0.0 0.0 0.0 0.219155 1.0 0.0
0.0 0.0 0.0 0.0 0.0 1.0
U
6×6 Array{Float64,2}:
2.0 -1.0 3.14159 0.0 0.0 0.0
0.0 4.0 -7.28319 8.0 0.0 0.0
0.0 0.0 5.46239 -7.0 6.0 0.0
0.0 0.0 0.0 4.56298 -3.19684 7.0
0.0 0.0 0.0 0.0 1.7006 -2.53408
0.0 0.0 0.0 0.0 0.0 2.0
Observe above that the lower and upper bandwidths of \(A\) are preserved in the \(L\) and \(U\) results.