How to get upper triangular values of a `Matrix`?

Suppose I have a Matrix, and I only want the upper triangular values stored in a Vector:

julia> A = [1.0 2.0 3.0; 4.0 5.0 6.0; 7.0 8.0 9.0]
3×3 Matrix{Float64}:
 1.0  2.0  3.0
 4.0  5.0  6.0
 7.0  8.0  9.0

julia> UpperTriangular(A)
3×3 UpperTriangular{Float64, Matrix{Float64}}:
 1.0  2.0  3.0
  ⋅   5.0  6.0
  ⋅    ⋅   9.0

How do I get 1.0 to 9.0 from UpperTriangular(A)?

Maybe some variation of this untested snippet

[mat[row,col] for col in 1:n for row in 1:col]
3 Likes

I think I prefer the above solution, but you can also achieve this using logical indexing:

julia> utri = triu!(trues(size(A)))
3×3 BitMatrix:
 1  1  1
 0  1  1
 0  0  1

julia> A[utri]
6-element Vector{Float64}:
 1.0
 2.0
 5.0
 3.0
 6.0
 9.0
3 Likes