Skip to content

Commit

Permalink
Fix adjoint and transpose for 0×0 matrix, fixes #1066 (#1067)
Browse files Browse the repository at this point in the history
  • Loading branch information
hyrodium authored Aug 2, 2022
1 parent def8fc2 commit 76ce2c5
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
18 changes: 6 additions & 12 deletions src/linalg.jl
Original file line number Diff line number Diff line change
Expand Up @@ -69,15 +69,12 @@ end
@inline transpose(a::Adjoint{<:Any,<:Union{StaticVector,StaticMatrix}}) = conj(a.parent)
@inline transpose(a::Adjoint{<:Real,<:Union{StaticVector,StaticMatrix}}) = a.parent

@generated function _transpose(::Size{S}, m::StaticMatrix) where {S}
Snew = (S[2], S[1])

exprs = [:(transpose(m[$(LinearIndices(S)[j1, j2])])) for j2 = 1:S[2], j1 = 1:S[1]]

@generated function _transpose(::Size{S}, m::StaticMatrix{n1, n2, T}) where {n1, n2, S, T}
exprs = [:(transpose(m[$(LinearIndices(S)[j1, j2])])) for j2 in 1:n2, j1 in 1:n1]
return quote
$(Expr(:meta, :inline))
elements = tuple($(exprs...))
@inbounds return similar_type($m, eltype(elements), Size($Snew))(elements)
@inbounds return similar_type($m, Base.promote_op(transpose, T), Size($(n2,n1)))(elements)
end
end

Expand All @@ -86,15 +83,12 @@ end
@inline adjoint(a::Transpose{<:Real,<:Union{StaticVector,StaticMatrix}}) = a.parent
@inline adjoint(a::Adjoint{<:Any,<:Union{StaticVector,StaticMatrix}}) = a.parent

@generated function _adjoint(::Size{S}, m::StaticMatrix) where {S}
Snew = (S[2], S[1])

exprs = [:(adjoint(m[$(LinearIndices(S)[j1, j2])])) for j2 = 1:S[2], j1 = 1:S[1]]

@generated function _adjoint(::Size{S}, m::StaticMatrix{n1, n2, T}) where {n1, n2, S, T}
exprs = [:(adjoint(m[$(LinearIndices(S)[j1, j2])])) for j2 in 1:n2, j1 in 1:n1]
return quote
$(Expr(:meta, :inline))
elements = tuple($(exprs...))
@inbounds return similar_type($m, eltype(elements), Size($Snew))(elements)
@inbounds return similar_type($m, Base.promote_op(adjoint, T), Size($(n2,n1)))(elements)
end
end

Expand Down
8 changes: 8 additions & 0 deletions test/linalg.jl
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,14 @@ StaticArrays.similar_type(::Union{RotMat2,Type{RotMat2}}) = SMatrix{2,2,Float64,
# Recursive adjoint/transpose correctly handles eltype (#708)
@test (@inferred(adjoint(SMatrix{2,2}(fill([1,2], 2,2)))))::SMatrix == SMatrix{2,2}(fill(adjoint([1,2]), 2,2))
@test (@inferred(transpose(SMatrix{2,2}(fill([1,2], 2,2)))))::SMatrix == SMatrix{2,2}(fill(transpose([1,2]), 2,2))

# 0×0 matrix
for T in (SMatrix{0,0,Float64}, MMatrix{0,0,Float64}, SizedMatrix{0,0,Float64})
m = T()
@test adjoint(m)::T == transpose(m)::T == m
end
@test adjoint(SMatrix{0,0,Vector{Int}}()) isa SMatrix{0,0,Adjoint{Int,Vector{Int}}}
@test transpose(SMatrix{0,0,Vector{Int}}()) isa SMatrix{0,0,Transpose{Int,Vector{Int}}}
end

@testset "normalization" begin
Expand Down

0 comments on commit 76ce2c5

Please sign in to comment.