# Any reason to specify triu()?

**URL:** https://discourse.julialang.org/t/any-reason-to-specify-triu/127361
**Category:** Performance
**Created:** [March 25, 2025, 5:36pm UTC](https://discourse.julialang.org/t/any-reason-to-specify-triu/127361 "2025-03-25T17:36:15Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![Huputus](https://avatars.discourse-cdn.com/v4/letter/h/b2d939/32.png) [@Huputus](https://discourse.julialang.org/u/Huputus)
#### Post date: [March 25, 2025, 5:36pm UTC](https://discourse.julialang.org/t/any-reason-to-specify-triu/127361/1 "2025-03-25T17:36:15Z")

</div>

Is there any reason to use `triu()` when working with upper triangular matrices? Performance-wise, it doesn’t seem to have any impact.

Here is sample code:

```julia
function upper_triangular_means(mate)
    n = size(mate, 1)
    result = triu(zeros(n, n))
    @threads for i in 1:n
        for j in i:n
            result[i, j] = mean(mate[i, :] .== mate[j, :])
        end
    end
    return result
end

```

---

<div class="post-metadata">

### Author: ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)
#### Post date: [March 25, 2025, 5:46pm UTC](https://discourse.julialang.org/t/any-reason-to-specify-triu/127361/2 "2025-03-25T17:46:14Z")

</div>

> [@Huputus](#):
>
> Is there any reason to use `triu()` when working with upper triangular matrices? Performance-wise, it doesn’t seem to have any impact.

`triu` makes a copy of the matrix with the lower-half set to zero. So it makes no sense to call `triu(zeros(n, n))` since `zeros(n,n)` already has a zero lower half. You are just making an unnecessary copy of the matrix.

Furthermore, note that the output of `triu(zeros(n, n))` is simply another ordinary `Matrix`, so there is no performance effect to using it compared to any other `Matrix` (= 2d `Array`).

In contrast, if you have an upper triangular matrix `T` and you are _solving a system of equations_ via `T \ b` or similar, then you are much better off wrapping it in the `UpperTriangular` type, i.e. using `UpperTriangular(T) \ b`, since that dispatches to a different algorithm that exploits the `UpperTriangular` shape. (And there are a few other functions that have specialized `UpperTriangular` variants.)
