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

**URL:** <https://discourse.julialang.org/t/how-to-get-upper-triangular-values-of-a-matrix/94391>\
**Category:** General Usage\
**Tags:** matrices\
**Created:** [February 10, 2023, 6:13am UTC](https://discourse.julialang.org/t/how-to-get-upper-triangular-values-of-a-matrix/94391 "2023-02-10T06:13:07Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![singularitti](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/singularitti/32/17678_2.png) [@singularitti](https://discourse.julialang.org/u/singularitti)\
**Post date:** [February 10, 2023, 6:13am UTC](https://discourse.julialang.org/t/how-to-get-upper-triangular-values-of-a-matrix/94391/1 "2023-02-10T06:13:07Z")

</div>

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

```julia
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)`?

---

<div class="post-metadata">

**Author:** ![jules](https://avatars.discourse-cdn.com/v4/letter/j/41988e/32.png) [@jules](https://discourse.julialang.org/u/jules)\
**Post date:** [February 10, 2023, 6:45am UTC](https://discourse.julialang.org/t/how-to-get-upper-triangular-values-of-a-matrix/94391/2 "2023-02-10T06:45:54Z")

</div>

Maybe some variation of this untested snippet

```julia
[mat[row,col] for col in 1:n for row in 1:col]

```

---

<div class="post-metadata">

**Author:** ![mikmoore](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mikmoore/32/31109_2.png) [@mikmoore](https://discourse.julialang.org/u/mikmoore)\
**Post date:** [February 10, 2023, 3:37pm UTC](https://discourse.julialang.org/t/how-to-get-upper-triangular-values-of-a-matrix/94391/3 "2023-02-10T15:37:07Z")

</div>

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

```julia-repl
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

```
