How to extract the upper/lower triangular matrix values except the diagonal?

Consider the following matrix:

julia> c = rand(2, 2)
2×2 Matrix{Float64}:
 0.0443768  0.515352
 0.531426   0.967584

Expected output:

1-element Vector{Float64}:
0.531426

I can do:

julia> using LinearAlgebra: LowerTriangular

julia> LowerTriangular(c)
2×2 LowerTriangular{Float64, Matrix{Float64}}:
 0.0443768   ⋅
 0.531426   0.967584

Collecting the previous lower triangular includes the diagonal of the matrix too. I want to omit the diagonal. How to do it?

You can use the tril function:

julia> c = rand(4,4)
4×4 Matrix{Float64}:
 0.508891  0.659778  0.639252  0.569137
 0.212345  0.834971  0.233612  0.564073
 0.812287  0.760213  0.224285  0.466787
 0.872574  0.516204  0.701075  0.359622

julia> LowerTriangular(tril(c, -1))
4×4 LowerTriangular{Float64, Matrix{Float64}}:
 0.0        ⋅         ⋅         ⋅ 
 0.212345  0.0        ⋅         ⋅ 
 0.812287  0.760213  0.0        ⋅ 
 0.872574  0.516204  0.701075  0.0

It’s not clear how useful the LowerTriangular type is here, however, rather than simply tril(c, -1) stored as a Matrix. The main utility of the LowerTriangular type is to support fast methods for solving Lx =b lower-triangular systems, but with a zero diagonal the problem is singular so those methods aren’t applicable.

(Another application of LowerTriangular is to have an in-place lower-triangular view of a matrix where you are storing something else in the upper triangle, as sometimes happens with in-place matrix factorizations, but that’s not the case if you use tril.)

1 Like

Isn’t tril(c, -1) enough?

Thank you so much!

Yes, depends on what matrix type you want to use. See also the comments at the bottom of my revised post (I was editing it while you responded).

1 Like

If you wanted the vector of entries, maybe this will do:

julia> A = rand(3,3)
3×3 Matrix{Float64}:
 0.212689  0.222497  0.34268
 0.376084  0.004906  0.706805
 0.395929  0.334694  0.883166

julia> [v for (k,v) in pairs(A) if k[1]>k[2]]
3-element Vector{Float64}:
 0.37608410776838963
 0.3959294893831178
 0.33469399665884414
3 Likes