JuliaLang / LinearAlgebra.jl

Julia Linear Algebra standard library
Other
13 stars 0 forks source link

2.0: Reconsider `permutedims(::Vector)` #1020

Open jariji opened 1 year ago

jariji commented 1 year ago
julia> permutedims([1, 2, 3, 4])
1×4 Matrix{Int64}:
 1  2  3  4

This method adds a dimension rather than permuting the existing ones. One of the key properties of a permutation is that it is invertible with a permutation, but this method is not.

It's convenient to have some function for turning a vector into a row vector but it would be much easier to program if functions applied simple composable logic consistently. For example, I would rather the 1-arg permutedims just rotate the dimensions by one. Rather than having custom logic for the Vector case, just apply the same logic and obtain a no-op.

permutedims(a) = permutedims(a, circshift(eachindex(size(a)), 1))

julia> a = reshape(1:24, 2,3,4)    
2×3×4 reshape(::UnitRange{Int64}, 2, 3, 4) with eltype Int64:
[:, :, 1] =
 1  3  5
 2  4  6

[:, :, 2] =
 7   9  11
 8  10  12

[:, :, 3] =
 13  15  17
 14  16  18

[:, :, 4] =
 19  21  23
 20  22  24

julia> permutedims(a, circshift(eachindex(size(a)), 1))
4×2×3 Array{Int64, 3}:
[:, :, 1] =
  1   2
  7   8
 13  14
 19  20

[:, :, 2] =
  3   4
  9  10
 15  16
 21  22

[:, :, 3] =
  5   6
 11  12
 17  18
 23  24

julia> let a = [1,2,3,4]
           permutedims(a, circshift(eachindex(size(a)), 1))
       end
4-element Vector{Int64}:
 1
 2
 3
 4

reshape can be used for adding a dimension to a vector:

julia> reshape([1,2,3,4], 1, :)
1×4 Matrix{Int64}:
 1  2  3  4