julialinear-algebramemory-efficient

How to get a standard basis vector in Julia?


What is the most readable and efficient way to write a standard basis vector

e_1 = [1,0,...,0]
...
e_n = [0,...,0,1]

in Julia? (Similar question to this and this matlab question)


Solution

  • The existing answers produce an Array{Bool} or a BitArray. Depending on what you're doing, you may also be interested in OneHotArrays.jl:

    julia> (1:3) .== 2
    3-element BitVector:
     0
     1
     0
    
    julia> using LinearAlgebra
    
    julia> I[1:3, 2]
    3-element Vector{Bool}:
     0
     1
     0
    
    julia> using OneHotArrays
    
    julia> onehot(2, 1:3)
    3-element OneHotVector(::UInt32) with eltype Bool:
     ⋅
     1
     ⋅
    
    julia> dump(ans)
    OneHotVector{UInt32}
      indices: UInt32 0x00000002
      nlabels: Int64 3