Is there a way to transpose an array of Any? I have a `12×500 Array{Any, 2}` I want

Is there a way to transpose an array of Any? I have a 12×500 Array{Any,2} I want it to be 500x12. If I do transpose it throws an error.

500×12 LinearAlgebra.Transpose{Any,Array{Any,2}}:
Error showing value of type LinearAlgebra.Transpose{Any,Array{Any,2}}:
ERROR: MethodError: no method matching transpose(::String)
Closest candidates are:
  transpose(::Missing) at missing.jl:100
  transpose(::Number) at number.jl:168
  transpose(::LinearAlgebra.Transpose) at D:\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.5\LinearAlgebra\src\adjtrans.jl:165

Note that the original poster on Slack cannot see your response here on Discourse. Consider transcribing the appropriate answer back to Slack, or pinging the poster here on Discourse so they can follow this thread.
(Original message :slack:) (More Info)

In Julia, transpose is firmly rooted in linear algebra, but permutedims allows swapping of dimensions of any type of object. In other words,

julia> A = Any["hello" for i = 1:3, j=1:2]
3×2 Matrix{Any}:
 "hello"  "hello"
 "hello"  "hello"
 "hello"  "hello"

julia> permutedims(A, (2, 1))
2×3 Matrix{Any}:
 "hello"  "hello"  "hello"
 "hello"  "hello"  "hello"

julia> transpose(A)
2×3 transpose(::Matrix{Any}) with eltype Any:
Error showing value of type Transpose{Any, Matrix{Any}}:
ERROR: MethodError: no method matching transpose(::String)
...

Why the distinction? Well, notice that the error message is telling you it’s trying to take transpose(::String), which isn’t a defined operation. Why does it take the transpose of elements? It’s useful/necessary for generic linear algebra, as one can see with this vector-of-vectors:

julia> x = [[1,2], [10,11]]
2-element Vector{Vector{Int64}}:
 [1, 2]
 [10, 11]

julia> x'*x
226

julia> x[1]'*x[1] + x[2]'*x[2]
226

So not only does it reshape the container x, it also reshapes each element.

6 Likes

For anyone looking to get involved in Julia development, here’s an issue to get your feet wet: Add hint for MethodError on transpose/adjoint · Issue #39938 · JuliaLang/julia · GitHub

2 Likes