How to convert from bool to float

I would like to take a matrix that is currently made of bools and turn it into floats.

If I is this matrix of bools, I’ve been trying commands like convert(Int8, I) and getting errors like

ERROR: MethodError: Cannot `convert` an object of type Matrix{Bool} to an object of type Int64
Closest candidates are:
  convert(::Type{T}, ::T) where T<:Number at number.jl:6
  convert(::Type{T}, ::Number) where T<:Number at number.jl:7
  convert(::Type{T}, ::Base.TwicePrecision) where T<:Number at twiceprecision.jl:273

What actually works if I want to be able to do arithmetic operations like matrix multiplications, log etc on an indicator matrix originally made from bools?

I really just want to one-hot encode a vector.
So I’ve been doing something like

using StatsBase
v = [1 2 3]
I = indicatormat(v)

But then the issue is that the code I have written to run matrix decomposition on I says things like "There are no methods matching what you want to do, and it objects to the fact that my first entry is a ::LinearAlgebra.Transpose{Bool, Matrix{Bool}} when it wants a ::Matrix{<:Real}

You can broadcast the type constructor over the matrix:

julia> a = rand(Bool, 2, 2)
2×2 Matrix{Bool}:
 0  1
 1  0

julia> Float32.(a)
2×2 Matrix{Float32}:
 0.0  1.0
 1.0  0.0
2 Likes

You can convert the matrix, i.e., convert(Matrix{Float64}, I) or use broadcasting convert.(Float64, I).
In any case, using a dense Boolean matrix for one-hot vectors is rather wasteful. OneHotArrays.jl has a special data type which only stores the indices of the positions which are one.