Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions src/generic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,8 @@ julia> triu(a,-3)
1.0 1.0 1.0 1.0
```
"""
function triu(M::AbstractMatrix, k::Integer = 0)
triu(M::AbstractMatrix, k::Integer = 0) = _triu(M, Val(haszero(eltype(M))), k)
function _triu(M::AbstractMatrix, ::Val{true}, k::Integer)
d = similar(M)
A = triu!(d,k)
if iszero(k)
Expand All @@ -477,6 +478,14 @@ function triu(M::AbstractMatrix, k::Integer = 0)
end
return A
end
function _triu(M::AbstractMatrix, ::Val{false}, k::Integer)
d = similar(M)
# since the zero would need to be evaluated from the elements,
# we copy the array to avoid undefined references in triu!
copy!(d, M)
A = triu!(d,k)
return A
end

"""
tril(M, k::Integer = 0)
Expand Down Expand Up @@ -507,7 +516,8 @@ julia> tril(a,-3)
1.0 0.0 0.0 0.0
```
"""
function tril(M::AbstractMatrix,k::Integer=0)
tril(M::AbstractMatrix,k::Integer=0) = _tril(M, Val(haszero(eltype(M))), k)
function _tril(M::AbstractMatrix, ::Val{true}, k::Integer)
d = similar(M)
A = tril!(d,k)
if iszero(k)
Expand All @@ -520,6 +530,14 @@ function tril(M::AbstractMatrix,k::Integer=0)
end
return A
end
function _tril(M::AbstractMatrix, ::Val{false}, k::Integer)
d = similar(M)
# since the zero would need to be evaluated from the elements,
# we copy the array to avoid undefined references in tril!
copy!(d, M)
A = tril!(d,k)
return A
end

"""
triu!(M)
Expand Down
10 changes: 10 additions & 0 deletions test/dense.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1408,4 +1408,14 @@ end
@test 2^A == 2^Matrix(A)
end

@testset "triu/tril for block matrices" begin
O = ones(2,2)
Z = zero(O)
M = fill(O, 3, 3)
res = fill(Z, size(M))
res[1,2] = res[1,3] = res[2,3] = O
@test triu(GenericArray(M),1) == res
@test tril(GenericArray(M),-1) == res'
end

end # module TestDense