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:
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
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.)
3 Likes