Identity matrix in Julia

Given using LinearAlgebra, the most julianic way of expressing the identity matrix is:

I

This answer may seem trite, but it is also kind of profound. The whole point of the operator I is that in the vast majority of cases where users want an identity matrix, it is not necessary to actually instantiate that matrix.

Let’s say you want a 1000x1000 identity matrix. Why waste time building the entire matrix, when you could just use I, noting that sizeof(I) evaluates to 1 (ie the size of the object is 1 byte). All functions in base Julia (including LinearAlgebra) understand what I is, and can use it appropriately without having to waste time building the actual matrix it represents first.

Now, it may be the case that for some reason you need to specify the type of the elements of your identity matrix. Note:

julia> I
UniformScaling{Bool}
true*I

so in this case, you are using a notional identity matrix with a diagonal of true and off-diagonal of false. This is sufficient in many cases, even if your other matrices are Int or Float64. Internally, Julia will use methods that specialize on the types. However, if you want to specify your identity matrix to contain integers or floats, use:

julia> 1I
UniformScaling{Int64}
1*I

julia> 1.0I
UniformScaling{Float64}
1.0*I

Note that sizeof(1I) evaluates to 8, indicating the notional Int64 types of the members of that matrix.

Also note that you can use e.g. 5I if you want a notional matrix with 5 on the diagonal and 0 elsewhere.

In some cases (and these cases are much rarer than many might think), you may need to actually build the matrix. In this case, you can use e.g.:

Matrix(1I, 3, 3)    # Identity matrix of Int type
Matrix(1.0I, 3, 3)  # Identity matrix of Float64 type
Matrix(I, 3, 3)     # Identity matrix of Bool type

BogumiƂ has also pointed out in the comments that if you are uncomfortable with implying the type of the output in the first argument of the constructors above, you can also use the (slightly more verbose):

Matrix{Int}(I, 3, 3)      # Identity matrix of Int type
Matrix{Float64}(I, 3, 3)  # Identity matrix of Float64 type
Matrix{Bool}(I, 3, 3)     # Identity matrix of Bool type

and specify the type explicitly.

But really, the only times you would probably need to do this are as follows:

  • When you want to input an identity matrix into a function in a package written in such a way that the input must be a concrete matrix type.
  • When you want to start out with an identity matrix but then mutate it in place into something else via one or several transformations.

Leave a Comment