1

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)

Felix B.
  • 905
  • 9
  • 23

3 Answers3

2

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
mcabbott
  • 2,329
  • 1
  • 4
  • 8
1

The most readable version I found to write standard basis vector e_k was

using LinearAlgebra: I

I[1:n, k]

How this works: The identity is of type Uniform Scaling I = LinearAlgebra.UniformScaling(1.) which means it acts as a (dimensionless) abstract matrix (but is not allocated). We can therefore index into it to get a standard basis vector.

Felix B.
  • 905
  • 9
  • 23
1

An alternative is:

e(n, k) = (1:n) .== k
Bogumił Kamiński
  • 66,844
  • 3
  • 80
  • 107